micro_mpc_kmk/main.py

82 lines
2.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
from switch import Switch
import select
from machine import Pin
SWITCHES = dict()
LED = Pin("LED", Pin.OUT) # "LED" — специальное имя для встроенного индикатора
def load_switches():
with open("config.json", "r") as file:
import json
config = json.load(file)
for sw_cfg in config["switches"]:
sw = Switch(
id=sw_cfg["id"],
pin=sw_cfg["pin"],
angle_minus=sw_cfg["angle_minus"],
angle_plus=sw_cfg["angle_plus"]
)
SWITCHES[sw.id] = sw
# print(f"Loaded {len(SWITCHES)} switch{'es' if len(SWITCHES) > 1 else ''}.")
def resolve_command(command: str):
parts = command.split()
if len(parts) == 4 and parts[0] == "SWITCH" and parts[2] == "TURN":
try:
sw_id = int(parts[1])
except ValueError:
return "ERROR Invalid ID"
direction = parts[3]
if direction not in ("+", "-"):
return "ERROR Invalid direction"
if sw_id not in SWITCHES:
return f"ERROR Switch {sw_id} not found"
# Выполняем действие
if direction == "+":
SWITCHES[sw_id].set_plus()
else:
SWITCHES[sw_id].set_minus()
# РОВНО ОДНА СТРОКА — подтверждение успеха
return f"EVENT SWITCH {sw_id} {direction}"
elif parts[0] == "GET" and parts[1] == "ALL":
evts = []
for id, sw in SWITCHES.items():
evts.append(f"EVENT SWITCH {id} {sw.pos}")
return "\n".join(evts)
def work():
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
while True:
events = poll.poll()
for fd, event in events:
if event & select.POLLIN:
try:
line = sys.stdin.readline().strip()
if not line:
continue
parts = line.split()
result = resolve_command(line)
if result:
print(result)
except Exception as e:
# Любая неожиданная ошибка — тоже одна строка
print(f"ERROR {e}")
if __name__ == "__main__":
LED.on()
load_switches()
work()