-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
123 lines (85 loc) · 2.66 KB
/
main.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
"""Put a Sonoff S20 onto CatBus."""
# pylint: disable=bare-except
# pylint: disable=import-error
# pylint: disable=invalid-name
# pylint: disable=too-few-public-methods
# pylint: disable=unused-argument
import time
import machine
import umqtt.simple as umqtt
import catbus_config
class Button(machine.Pin):
"""An input button that calls a callback when pressed."""
def __init__(self, pin=0):
super().__init__(pin, machine.Pin.IN)
# Timer -1 is a "virtual" RTOS timer, rather than a hardware one.
self._timer = machine.Timer(-1)
def set_callback(self, callback):
# The timer callback has a parameter, so this consumes that.
def _callback(timer):
callback()
def debounce_button(pin):
self._timer.init(mode=machine.Timer.ONE_SHOT,
period=200, callback=_callback)
self.irq(trigger=machine.Pin.IRQ_RISING, handler=debounce_button)
class Relay(machine.Pin):
"""An output relay."""
def __init__(self, pin=12):
super().__init__(pin, machine.Pin.OUT)
def toggle(self):
if self.value() == 0:
self.on()
else:
self.off()
def value_catbus(self):
return b'on' if self.value() else b'off'
class LED(machine.Pin):
"""The non-relay LED on the front of the device.
The LED on the Sonoff is LOW for on and HIGH for off."""
def __init__(self, pin=13):
super().__init__(pin, machine.Pin.OUT)
def on(self):
super().off()
def off(self):
super().on()
button = Button()
relay = Relay()
status_led = LED()
def main():
# Setup begins.
status_led.on()
config = catbus_config.Config()
if not config.device_name:
# We haven't been set up and can't do anything.
return
topic = config.mqtt_topic.encode('utf-8')
def on_message(topic, data):
if data == b'on':
relay.on()
elif data == b'off':
relay.off()
else:
pass
mqtt = umqtt.MQTTClient(config.device_name, config.mqtt_broker)
mqtt.set_callback(on_message)
mqtt.connect()
mqtt.subscribe(topic, qos=1)
def on_button_pressed():
relay.toggle()
mqtt.publish(topic, relay.value_catbus(),
retain=True, qos=1)
button.set_callback(on_button_pressed)
# Setup finished.
status_led.off()
while True:
try:
mqtt.wait_msg()
except:
status_led.on()
try:
mqtt.connect()
mqtt.subscribe(topic, qos=1)
status_led.off()
except:
time.sleep(1)
main()