-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
187 lines (142 loc) · 4.51 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# This is your main script.
import machine
import network
import time
from umqtt.simple import MQTTClient
import json
import sys
# ------------------------------------------------------------------
# CONSTANTS
CONFIG_FILE = 'config.json'
# ------------------------------------------------------------------
# Global Variables
sta_if = None # Wifi Interface
settings = None # Json File Parsed
sensors = {} # List of water sensors
led = None # Status led pin
mqtt_client = None
last_update_status = 0
last_update_pulses = 0
last_update_litres = 0
# ------------------------------------------------------------------
'''
Loading JSON Configuration File
'''
def loadConfigFile():
global CONFIG_FILE, settings
try:
f = open(CONFIG_FILE,'r')
settings = json.load(f)
f.close()
except OSError:
return False
# ------------------------------------------------------------------
'''
Connect to Wifi
'''
def connectWifi():
global sta_if, settings
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(settings['wifi']['SSID'], settings['wifi']['PSK'])
while True:
print("Connecting...")
time.sleep(1)
if sta_if.isconnected():
print("Connected!")
print(sta_if.ifconfig())
break
# ------------------------------------------------------------------
'''
Connect broker
'''
def connectMqtt():
global settings, mqtt_client
mqtt_client = MQTTClient(settings['mqtt']['client'], settings['mqtt']['broker'])
mqtt_client.connect()
mqtt_client.publish(settings['mqtt']['prefix'] + settings['mqtt']['t_status'], 'water sensor up')
print("MQTT Connected!")
# ------------------------------------------------------------------
'''
Setup pins (GPIO)
'''
def setupPins():
global settings, sensors, led
for sensor in settings['sensors']:
s = machine.Pin(sensor['pin'], machine.Pin.IN)
sensors[str(sensor['pin'])] = {}
sensors[str(sensor['pin'])]['name'] = sensor['name']
sensors[str(sensor['pin'])]['m3'] = 0
sensors[str(sensor['pin'])]['pulses'] = 0
sensors[str(sensor['pin'])]['litres'] = 0
s.irq(trigger=machine.Pin.IRQ_FALLING, handler=water_tick_handler)
if 'statusLed' in settings:
led = machine.Pin(settings['statusLed'], machine.Pin.OUT)
# ------------------------------------------------------------------
'''
Status led toggling
'''
def toggleLed():
global led
if led is not None:
led.value(led.value()^1)
# ------------------------------------------------------------------
def water_tick_handler(p):
global sensors
id = str(p)[4:-1]
sensors[id]['pulses'] += 1
if sensors[id]['pulses'] == settings['pulsesPerLitre']:
sensors[id]['pulses'] = 0
sensors[id]['litres'] += 1
if sensors[id]['litres'] == 1000:
sensors[id]['litres'] = 0
sensors[id]['m3'] += 1
toggleLed()
# ------------------------------------------------------------------
def send_mqtt_volume_update():
global sensors, settings, mqtt_client
print("[+] Status update")
for s_id in sensors:
strValue = str(sensors[s_id]['m3']) + '.' \
"{:03d}".format(sensors[s_id]['litres']) + \
"{:03d}".format(int(sensors[s_id]['pulses'] / settings['pulsesPerLitre'] * 1000))
sName = sensors[s_id]['name']
sPulses = str(sensors[s_id]['pulses'])
mqtt_client.publish( \
settings['mqtt']['prefix'] + sName + '/' + settings['mqtt']['t_cons'], \
'{ "value": ' + strValue + \
', "pulses": ' + sPulses + ' }' \
)
# ------------------------------------------------------------------
def save():
global sensors
print("[+] Saving State")
f = open('state.json','w')
json.dump(sensors, f)
f.close()
# ------------------------------------------------------------------
def restore():
global sensors
try:
f = open('state.json','r')
print("[+] Restoring State")
sensors = json.load(f)
f.close()
except OSError:
return False
# ------------------------------------------------------------------
# Main Program
if loadConfigFile() == False:
print("[!] Missing " + CONFIG_FILE + " configuration file. Exiting.")
sys.exit()
setupPins()
restore()
connectWifi()
connectMqtt()
while True:
#toggleLed()
time.sleep(1)
if time.time() % 5 == 0:
send_mqtt_volume_update()
if time.time() % 60 == 0:
save()