from time import sleep
import machine
import network
import socket
import time
import random
import json
from umqtt.simple import MQTTClient
server="mqtt.favoriot.com"
Device = "training_iot_1_device@mijimy81"
token = "nUZ2pmd4BOqlNN4kQE3p23EXKo4yttwK"
topic_publish = "/v2/streams"
topic_rpc = "/v2/rpc"
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('network config:', wlan.ipconfig('addr4'))
print("wifi connected")
def mqtt_connect():
print('Connected to MQTT Broker "%s"' % (server))
#client = MQTTClient(ClientID, server, 1883, user, password)
client = MQTTClient(token, server, 1883, token, token)
client.connect()
return client
def update_mqtt(t,p,h):
header='"device_developer_id":'+'"'+Device+'",'+'"data":'
send1='"temperature":'+'"'+str(t)+'"'
send2='"humidity":'+'"'+str(h)+'"'
send3='"pressure":'+'"'+str(p)+'"'
msg=b'{'+header+'{'+send1+','+send2+','+send3+'}}'
print('send message %s on topic %s' % (msg, topic_publish))
client.publish(token+topic_publish, msg, qos=0)
client.ping()
client.wait_msg()
def mqtt_msg_received(topicr, msgr):
print("Received:", str(msgr), "Topic:", str(topicr))
# Convert JSON string to Python dictionary
parsed = json.loads(msgr)
# Extract key and value
for key, value in parsed.items():
variable = key
val = value
print("Variable:", variable)
print("Value:", val)
if variable=="button":
led.value(int(val))
#start of program
wlan_connect()
client = mqtt_connect()
client.set_callback(mqtt_msg_received)
client.subscribe(token+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