58 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			58 lines
		
	
	
		
			1.4 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
import time
 | 
						|
from machine import Pin
 | 
						|
from umqtt.simple import MQTTClient
 | 
						|
 | 
						|
 | 
						|
import network
 | 
						|
import time
 | 
						|
from math import sin
 | 
						|
 | 
						|
 | 
						|
# Received messages from subscriptions will be delivered to this callback
 | 
						|
def sub_cb(topic, msg):
 | 
						|
    print((topic, msg))
 | 
						|
    if msg == b'on':
 | 
						|
        print("turn LED on")
 | 
						|
        #can do some hardware control here
 | 
						|
    elif msg == b'off':
 | 
						|
        print("turn LED off")
 | 
						|
 | 
						|
 | 
						|
# Replace details in code below
 | 
						|
 | 
						|
def main(server="192.168.1.XX"):
 | 
						|
    # Fill in your WiFi network name (ssid) and password here:
 | 
						|
    wifi_ssid = "XXXXXXXXX"
 | 
						|
    wifi_password = "XXXXXXXXX"
 | 
						|
 | 
						|
    # 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")
 | 
						|
 | 
						|
    #client name should be unique
 | 
						|
    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()
 |