-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
99 lines (81 loc) · 2.88 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
from machine import ADC, Pin
from AnalogSensor import AnalogSensor
from ACAnalogSensor import ACAnalogSensor
from Pump import Pump
import ujson
import sys
import select
import micropython
from Relay import Relay
micropython.alloc_emergency_exception_buf(100)
led = Pin(25, Pin.OUT)
led.on()
with open("""/serial_no.json""") as serial_json_file:
serial_json = ujson.load(serial_json_file)
serial_no = serial_json["serial_no"]
poll = select.poll()
poll.register(sys.stdin, select.POLLIN)
config = {}
def init():
global config, io_components
io_components = {}
try:
with open("""/config.json""") as data_file:
config = ujson.load(data_file)
for v in config["channels"]:
if v['type'] == 'sensor':
analog_sensor = AnalogSensor(v)
io_components[str(analog_sensor.index)] = analog_sensor
elif v['type'] == 'acsensor':
analog_sensor = ACAnalogSensor(v)
io_components[str(analog_sensor.index)] = analog_sensor
elif v['type'] == 'pump':
pump = Pump(v)
io_components[str(pump.index)] = pump
elif v['type'] == 'relay':
relay = Relay(v)
io_components[str(relay.index)] = relay
except Exception as e:
print(e)
config = {}
return io_components
def loop():
global poll, io_components, led, serial_no
command = ''
try:
command = (str(poll.poll(200)[0][0].readline())).strip()
command_json = ujson.loads(command)
except Exception as e:
command_json = {}
finally:
try:
if 'command' in command_json.keys():
command = command_json['command']
if command == 'data':
channel = command_json['channel']
print(io_components[str(channel)].response_dict)
elif command == 'serial':
print(serial_no)
elif command == 'init':
new_config = command_json['config']
try:
with open("""/config.json""", 'w') as data_file:
ujson.dump(new_config, data_file)
except Exception as e:
print(e)
io_components = init()
elif command == 'state':
channel = command_json['channel']
state = command_json['state']
print(str(io_components[channel].set_state(state)))
except Exception as e:
print(e)
finally:
for sensor in io_components.values():
if sensor.type == 'sensor' or sensor.type == 'acsensor':
sensor.add_value()
sensor.update_response_dict()
led.toggle()
io_components = init()
while True:
loop()