from time import sleep
import machine
import network
import socket
import time
import random
import ujson
from umqtt.simple import MQTTClient
server="backend.thinger.io"
ClientID ='mqtt_test'
user = "mijimy"
password = "12345678"
topic_publish ="value"
topic_rpc = "value"
wifi_ap="Wokwi-GUEST"
wifi_pswd=""
led=machine.Pin(14,machine.Pin.OUT)
def wlan_connect():
wlan = network.WLAN()
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect(wifi_ap,wifi_pswd)
while not wlan.isconnected():
machine.idle()
print("wifi connected")
def mqtt_connect():
print('Connected to MQTT Broker "%s"' % (server))
client = MQTTClient(ClientID, server, 1883, user, password)
client.connect()
return client
def update_mqtt(t,p,h):
msg = ujson.dumps({
"temperature": str(t),
"humidity": str(h),
"pressure": str(p),
})
print('send message %s on topic %s' % (msg, topic_publish))
client.publish(topic_publish, msg, qos=0)
client.ping()
client.wait_msg()
def mqtt_msg_received(topicr, msgr):
print("Received:", str(msgr), "Topic:", str(topicr))
parsed = ujson.loads(msgr)
for key, value in parsed.items():
variable = key
val = value
print("Variable:", variable)
print("Value:", val)
if variable=="led":
led.value(int(val))
#start of program
wlan_connect()
client = mqtt_connect()
client.set_callback(mqtt_msg_received)
client.subscribe(topic_rpc)
print("Subscribed to", topic_rpc)
sleep(2) # wait
while True:
import random #random number function
temp=26.5+random.uniform(-5, 5)
pressure=45+random.uniform(-5, 5)
humidity=23+random.uniform(-5, 5)
update_mqtt(temp,pressure,humidity)
print("temp:",temp,"^C")
print("press:",pressure,"hPA")
print("humidity:",humidity,"%")
sleep(2) # wait