# pub.py
import network
import socket
import time
import random
from umqtt.simple import MQTTClient
server="backend.thinger.io"
ClientID = f'mqtt_test'
user = "mijimy"
password = "12345678"
topic = "value"
topic1 = "temp3"
#msg = b'{"msg":"hello"}'
#TOPIC = "Properties"
#TOPIC = "mqtt_test/{{device}}/value"
TOPIC = "temp3"
# Replace with your Wi-Fi credentials
SSID = "Wokwi-GUEST"
PASSWORD = ""
# Connect to Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
# Wait for connection
while not wlan.isconnected():
print("Connecting to Wi-Fi...")
time.sleep(1)
print("Connected to Wi-Fi:", wlan.ifconfig())
def connect():
print('Connected to MQTT Broker "%s"' % (server))
client = MQTTClient(ClientID, server, 1883, user, password)
client.connect()
return client
def reconnect():
print('Failed to connect to MQTT broker, Reconnecting...' % (server))
time.sleep(5)
client.reconnect()
try:
client = connect()
except OSError as e:
reconnect()
def msg_received(topicr, msgr):
print("Received:", str(msgr), "Topic:", str(topicr))
client.set_callback(msg_received)
client.subscribe(TOPIC)
print("Subscribed to", TOPIC)
while True:
temperature=25+(random.randrange(1,50))/10
temperature2=28+(random.randrange(1,50))/10
temperature3=100+(random.randrange(1,50))/10
send1='"temp1":'+'"'+str(temperature)+'"'
send2='"temp2":'+'"'+str(temperature2)+'"'
#print(send1,send2)
# msg = b'{"temp":"send"}'
msg=b'{'+send1+','+send2+'}'
#msg2=b'{'+send2+'}'
# msg=msg1+' '+msg2
print('send message %s on topic %s' % (msg, topic))
client.publish(topic, msg, qos=0)
msg1=str(temperature3)
print('send message %s on topic %s' % (msg1, topic1))
client.publish(topic1, msg1, qos=0)
time.sleep(1)
client.ping()
client.wait_msg()
time.sleep(1)