01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | from simple import MQTTClient from machine import Pin import network import time SSID = 'YOURSSID' PASSWORD = 'YOURPARSSWORD' led = Pin( 2 , Pin.OUT, value = 1 ) SERVER = '119.29.244.94' [ / size][size = 3 ] #mqtt服务器的IP[/size][size=3] CLIENT_ID = 'imliubo' #设备ID TOPIC = b 'led' #设备订阅的主题 客户端推送消息的主题 TOPIC2 = b 'ledled' #手机客户端订阅的主题 设备推送消息的主题 username = '123123' #随便填。。。。 password = '321321' state = 0 c = None def sub_cb(topic, msg): global state print ((topic, msg)) if msg = = b 'on' : led.value( 0 ) state = 1 c.publish(TOPIC2, 'on-state' ,retain = True ) elif msg = = b 'off' : led.value( 1 ) state = 0 c.publish(TOPIC2, 'off-state' ,retain = True ) def connectWifi(ssid,passwd): global wlan wlan = network.WLAN(network.STA_IF) wlan.active( True ) wlan.disconnect() wlan.connect(ssid,passwd) while (wlan.ifconfig()[ 0 ] = = '0.0.0.0' ): time.sleep( 1 ) try : connectWifi(SSID,PASSWORD) server = SERVER c = MQTTClient(CLIENT_ID, server, 0 ,username,password) c.set_callback(sub_cb) c.connect() c.subscribe(TOPIC) c.publish(TOPIC2, 'shebeishangxian' ,retain = True ) print ( 'Connected to %s, subscribed to %s topic' % (server, TOPIC)) while True : c.wait_msg() finally : if (c is not None ): c.disconnect() wlan.disconnect() wlan.active( False ) |
联系客服