-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontroller.py
More file actions
94 lines (81 loc) · 2.86 KB
/
Copy pathcontroller.py
File metadata and controls
94 lines (81 loc) · 2.86 KB
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
import machine
import time
from wifi_manager import WifiManager
from event_queue import EventQueue
from telegram_sender import TelegramSender
from state_manager import StateManager
import time_sync
from config import (
PIN_PUBLIC,
PIN_PRIVATE,
POLL_INTERVAL_MS,
SEND_RETRY_DELAY,
CHAT_ID_PUBLIC,
TOPIC_ID_PUBLIC,
CHAT_ID_PRIVATE,
TOPIC_ID_PRIVATE,
STATE_FILE_PUBLIC,
STATE_FILE_PRIVATE,
)
class Controller:
def __init__(self):
print("[SYS] Booting...")
self.wifi = WifiManager()
self.queue = EventQueue()
self.sender = TelegramSender()
# Each monitor watches one pin and targets one Telegram group.
self.monitors = [
self._make_monitor(
"public", PIN_PUBLIC, STATE_FILE_PUBLIC,
CHAT_ID_PUBLIC, TOPIC_ID_PUBLIC, "visitantes",
),
self._make_monitor(
"private", PIN_PRIVATE, STATE_FILE_PRIVATE,
CHAT_ID_PRIVATE, TOPIC_ID_PRIVATE, "membros",
),
]
def _make_monitor(self, name, pin_number, state_file, chat_id, topic_id, audience):
pin = machine.Pin(pin_number, machine.Pin.IN, machine.Pin.PULL_UP)
state_mgr = StateManager(pin, state_file, name)
return {
"name": name,
"state_mgr": state_mgr,
"chat_id": chat_id,
"topic_id": topic_id,
"audience": audience,
}
def run(self):
print("[SYS] Starting main loop")
self.wifi.connect()
time_sync.sync()
while True:
print("\n[LOOP] Tick ----------------")
# 1. Detect state changes on every monitored pin
for monitor in self.monitors:
changed, state = monitor["state_mgr"].check_for_change()
if changed:
event = {
"state": state,
"ts": time.time(),
"chat_id": monitor["chat_id"],
"topic_id": monitor["topic_id"],
"audience": monitor["audience"],
}
self.queue.push(event)
# 2. Send queued events
if self.queue.peek():
print("[LOOP] Queue has data")
if self.wifi.ensure():
event = self.queue.peek()
if self.sender.send(event):
print("[LOOP] Send success")
self.queue.pop()
else:
print("[LOOP] Send failed, retrying later")
time.sleep(SEND_RETRY_DELAY)
else:
print("[LOOP] No Wi-Fi")
time.sleep(SEND_RETRY_DELAY)
else:
print("[LOOP] Queue empty")
time.sleep_ms(POLL_INTERVAL_MS)