-
Notifications
You must be signed in to change notification settings - Fork 36
/
example_sub_led.py
48 lines (40 loc) · 1.11 KB
/
example_sub_led.py
1
2
3
4
5
6
7
8
9
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
from umqtt.simple2 import MQTTClient
from machine import Pin
import ubinascii
import machine
import micropython
# ESP8266 ESP-12 modules have blue, active-low LED on GPIO2, replace
# with something else if needed.
led = Pin(2, Pin.OUT, value=1)
# Default MQTT server to connect to
SERVER = "192.168.1.35"
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
TOPIC = b"led"
state = 0
def sub_cb(topic, msg, r, d):
global state
print((topic, msg))
if msg == b"on":
led.value(0)
state = 1
elif msg == b"off":
led.value(1)
state = 0
elif msg == b"toggle":
# LED is inversed, so setting it to current state
# value will make it toggle
led.value(state)
state = 1 - state
def main(server=SERVER):
c = MQTTClient(CLIENT_ID, server)
# Subscribed messages will be delivered to this callback
c.set_callback(sub_cb)
c.connect()
c.subscribe(TOPIC)
print("Connected to %s, subscribed to %s topic" % (server, TOPIC))
try:
while 1:
# micropython.mem_info()
c.wait_msg()
finally:
c.disconnect()