"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin,ADC
import dht
import ujson
from umqtt.simple import MQTTClient
from math import log
import ubinascii
import urequests
import ntptime
# MQTT Server Parameters
MQTT_CLIENT_ID = "200247P"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC = "abnormal_temp_sensor"
sensor_pin=ADC(Pin(15))
sta_if = network.WLAN(network.STA_IF)
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
def cal_time(t):
year,month,date,hour,minute,second = t[0],t[1],t[2],t[3],t[4],t[5]
hour+=5
minute+=30
if second >= 60: second -= 60; minute += 1
if minute >= 60: minute -= 60; hour += 1
if hour >= 24: hour -= 24; date += 1
if month == 2:
if year%4 == 0:
if date > 29: date -= 29; month = 3
elif date > 28: date -= 28; month = 3
elif (any(month == i for i in (1, 3, 5, 7, 8, 9, 10, 12))):
if date > 31: date -= 31; month += 1
elif (any(month == i for i in (4, 6, 9, 11))):
if date > 30: date -= 30; month += 1
if month > 12: month -= 12; year += 1
return "%02d:%02d:%02d on %04d/%02d/%02d" % (hour, minute, second,
year, month, date)
def send(temp):
print("Connecting to WiFi", end="")
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
print("Connecting to MQTT server... ", end="")
client.connect()
print("Connected!")
ntptime.settime()
current_time = cal_time(time.localtime())
message = ujson.dumps({
f"High temperature detected at {current_time} ": temp})
print(current_time)
print("Reporting to MQTT topic {}: {}".format(MQTT_TOPIC, message))
client.publish(MQTT_TOPIC, message)
print("Updated")
return 0
while True:
sta_if.active(False)
sensor_value = sensor_pin.read_u16()
temperature= 1 / (log(1 / (65535/ sensor_value - 1)) / 3950 + 1.0 / 298.15) - 273.15
if temperature>39.5:
send(temperature)
time.sleep(1)