from machine import Pin
import ujson
import network
from time import sleep_ms
from umqtt.simple import MQTTClient
WiFi_ssid = 'Wokwi-GUEST'
WiFi_pwd = ''
MQTT_BROKER = 'mqtt.netpie.io'
MQTT_CLIENT_ID = 'f73f23b5-8799-4958-ad2a-0b1ce8cc8056' # Copied from your device
MQTT_TOKEN = 'XJZit3uWyUjRYRNK1hyNpAnz1dFHx2Uw'
MQTT_SECRET = '' # May leave it blank
# Connect to WiFi
sta_if = network.WLAN(network.STA_IF) # Set WiFi Mode to Station
sta_if.active(True)
sta_if.connect(WiFi_ssid,WiFi_pwd) # Start Connecting
print('WiFi ', end='')
while not sta_if.isconnected():
print('.', end='')
time.sleep(0.5)
print(' ', sta_if.ifconfig()[0], '[Connected]')
# Connect to MQTT broker
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_TOKEN, password=MQTT_SECRET)
print('MQTT ... ', MQTT_BROKER, end='')
try:
client.connect()
print(' [Connected]')
except:
print(' [Error]')
# Callback function for responding to the subscribed topics
def on_message(topic,msg):
print(type(msg))
client.set_callback(on_message)
client.subscribe('@shadow/data/update')
while True:
data = ujson.dumps({
'pump': pump_status
})
message = ujson.dumps({'data':data})
print(message)
client.publish('@shadow/data/update', message)
sleep(1)