10、通过主题消息“on”和“off”开关LED灯
#MicroPython动手做(29)——物联网之SIoT
#通过主题消息“on”和“off”开关LED灯
from mpython import *
import network
from umqtt.simple import MQTTClient
import music
import time
from machine import Timer
import ubinascii
my_wifi = wifi()
my_wifi.connectWiFi("zh", "zy1567")
mqtt = MQTTClient("ok", "192.168.31.248", 1883, "siot", "dfrobot", keepalive=30)
try:
mqtt.connect()
print('Connected')
except:
print('Disconnected')
def mqtt_topic_6561676c6572382f7a6b6231(_msg):
global i
if str(_msg) == "on":
rgb.fill((int(255), int(0), int(0)))
rgb.write()
time.sleep_ms(1)
oled.DispChar(" 开灯", 0, 32, 1)
oled.show()
if str(_msg) == "off":
rgb.fill( (0, 0, 0) )
rgb.write()
time.sleep_ms(1)
oled.DispChar(" 关灯", 0, 32, 1)
oled.show()
def on_button_a_down(_):
global i
time.sleep_ms(10)
if button_a.value() == 1: return
mqtt.publish("eagler8/zkb1", "on")
music.play('E5:1')
def on_button_b_down(_):
global i
time.sleep_ms(10)
if button_b.value() == 1: return
mqtt.publish("eagler8/zkb1", "off")
music.play('D5:1')
def mqtt_callback(topic, msg):
try:
topic = topic.decode('utf-8', 'ignore')
_msg = msg.decode('utf-8', 'ignore')
eval('mqtt_topic_' + bytes.decode(ubinascii.hexlify(topic)) + '("' + _msg + '")')
except: print((topic, msg))
mqtt.set_callback(mqtt_callback)
mqtt.subscribe("eagler8/zkb1")
def timer14_tick(_):
mqtt.ping()
tim14 = Timer(14)
tim14.init(period=20000, mode=Timer.PERIODIC, callback=timer14_tick)
button_a.irq(trigger=Pin.IRQ_FALLING, handler=on_button_a_down)
button_b.irq(trigger=Pin.IRQ_FALLING, handler=on_button_b_down)
mqtt.publish("eagler8/zkb1", "hello")
music.play('G5:1')
oled.fill(0)
oled.DispChar(" 连接SIoT成功", 0, 16, 1)
oled.show()
rgb[1] = (int(0), int(51), int(0))
rgb.write()
time.sleep_ms(1)
while True:
mqtt.wait_msg()