from time import sleep
import machine
import network
import socket
import time
import random
import ujson
from umqtt.simple import MQTTClient
server="mqtt.favoriot.com"
Device = "test_board_1_device@mijimy81"
token = "FZxoCMHqL76koZ9GtmVM69prGrkeF5kh"
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+'}}'
msg = ujson.dumps({
"device_developer_id" :Device,
"temperature": str(t),
"humidity": str(h),
"pressure": str(p),
})
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 = ujson.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
value=[0,0,0]
while True:
import random #random number function
value[0]=26.5+random.uniform(-5, 5)
value[1]=45+random.uniform(-5, 5)
value[2]=23+random.uniform(-5, 5)
for i in range(3):
value[i]=round(float(value[i]),2)
update_mqtt(value[0],value[1],value[2])
print("temp:",value[0],"^C")
print("press:",value[1],"hPA")
print("humidity:",value[2],"%")
sleep(2) # wait