File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ from umqtt .simple import MQTTClient
2+ from machine import Pin
3+ import ubinascii
4+ import machine
5+ import micropython
6+
7+
8+ # ESP8266 ESP-12 modules have blue, active-low LED on GPIO2, replace
9+ # with something else if needed.
10+ led = Pin (2 , Pin .OUT , value = 1 )
11+
12+ # Default MQTT server to connect to
13+ SERVER = "192.168.1.35"
14+ CLIENT_ID = ubinascii .hexlify (machine .unique_id ())
15+ TOPIC = b"led"
16+
17+
18+ state = 0
19+
20+ def sub_cb (topic , msg ):
21+ global state
22+ print ((topic , msg ))
23+ if msg == b"on" :
24+ led .value (0 )
25+ state = 1
26+ elif msg == b"off" :
27+ led .value (1 )
28+ state = 0
29+ elif msg == b"toggle" :
30+ # LED is inversed, so setting it to current state
31+ # value will make it toggle
32+ led .value (state )
33+ state = 1 - state
34+
35+
36+ def main (server = SERVER ):
37+ c = MQTTClient (CLIENT_ID , server )
38+ # Subscribed messages will be delivered to this callback
39+ c .set_callback (sub_cb )
40+ c .connect ()
41+ c .subscribe (TOPIC )
42+ print ("Connected to %s, subscribed to %s topic" % (server , TOPIC ))
43+
44+ try :
45+ while 1 :
46+ #micropython.mem_info()
47+ c .wait_msg ()
48+ finally :
49+ c .disconnect ()
You can’t perform that action at this time.
0 commit comments