MQTT_Aug7CreativeTech/rp2040_client/main.py

58 lines
1.4 KiB
Python
Raw Normal View History

2024-08-06 15:33:18 +00:00
import time
2024-08-08 00:18:07 +00:00
from machine import Pin
2024-08-06 15:33:18 +00:00
from umqtt.simple import MQTTClient
import network
import time
from math import sin
2024-08-08 00:18:07 +00:00
2024-08-06 15:33:18 +00:00
# Received messages from subscriptions will be delivered to this callback
def sub_cb(topic, msg):
print((topic, msg))
2024-08-08 00:18:07 +00:00
if msg == b'on':
print("turn LED on")
2024-09-01 23:19:04 +00:00
#can do some hardware control here
2024-08-08 00:18:07 +00:00
elif msg == b'off':
print("turn LED off")
2024-08-06 15:33:18 +00:00
2024-09-01 23:19:04 +00:00
# Replace details in code below
def main(server="192.168.1.XX"):
2024-08-06 15:33:18 +00:00
# Fill in your WiFi network name (ssid) and password here:
2024-09-01 23:19:04 +00:00
wifi_ssid = "XXXXXXXXX"
wifi_password = "XXXXXXXXX"
2024-08-06 15:33:18 +00:00
# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifi_ssid, wifi_password)
while wlan.isconnected() == False:
print('Waiting for connection...')
time.sleep(1)
print("Connected to WiFi")
2024-09-01 23:19:04 +00:00
#client name should be unique
2024-08-06 15:33:18 +00:00
c = MQTTClient("pico_board", server, 1883)
c.set_callback(sub_cb)
c.connect()
c.subscribe(b"godot/#")
while True:
if True:
# Blocking wait for message
c.wait_msg()
else:
# Non-blocking wait for message
c.check_msg()
# Then need to sleep to avoid 100% CPU usage (in a real
# app other useful actions would be performed instead)
time.sleep(1)
c.disconnect()
if __name__ == "__main__":
main()