-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcollect.py
221 lines (185 loc) · 5.05 KB
/
collect.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env python
import datetime
from distutils.dir_util import mkpath
import json
import os
import time
import socket
import sys
import uuid
import RPi.GPIO as GPIO
from picamera import PiCamera
from pytz import timezone
import ntplib
import lib.ext.dht11 as dht11
import lib.ext.mg811 as mg811
import lib.collect.config as config
import lib.collect.backend as backend
WORK_DIR = config.WORK_DIR
COLLECT_API_LOG = config.COLLECT_API_LOG
API_VERSION = 0
CLIENT_ID = 0
CLIENT_VERSION = 0
CLIENT_MODEL = 'mark0'
CAMERA_MODEL = 'Kuman SC15-JP'
LED_MODEL = 'cheap'
FAN_MODEL = 'cheap'
SENSOR_TEMPERATURE_MODEL = 'DHT-11'
SENSOR_HUMIDITY_MODEL = 'DHT-11'
DHT_PIN = 15
SENSOR_CO2_MODEL = 'MG-811'
MG811_PIN = 8
SENSORS = [
'dht11',
'mg811',
]
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
def snapshot():
name = '.'.join([
datetime.datetime.now().strftime('%Y%m%d%H%M%S'),
str(uuid.uuid4()),
'jpg'
])
path = os.path.sep.join([WORK_DIR, name])
camera = PiCamera()
camera.start_preview()
time.sleep(5)
camera.capture(path)
camera.stop_preview()
payload = {
'm': CAMERA_MODEL,
'u': 'jpg',
'v': os.path.sep.join([
str(CLIENT_ID),
str(CLIENT_MODEL),
str(CLIENT_VERSION),
name,
]),
}
return payload, path
def cmd(turn_red_on = True, turn_blue_on = True):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server_address = config.DEVICES_D_ADDRESS
result = {}
try:
sock.connect(server_address)
try:
message = json.dumps({
'reds': turn_red_on,
'blues': turn_blue_on,
})
print("Send to socket: %s" % message)
sock.sendall(message)
# TODO Get confirmation from daemon
#amount_received = 0
#amount_expected = len(message)
#while amount_received < amount_expected:
# data = sock.recv(16)
# amount_received += len(data)
# result['red'] = ...
# result['blue'] = ...
result['leds'] = {}
result['leds']['red'] = {
'm': LED_MODEL,
'u': 'bool',
'v': turn_red_on,
}
result['leds']['blue'] = {
'm': LED_MODEL,
'u': 'bool',
'v': turn_blue_on,
}
#result['fan'] = {
# 'm': FAN_MODEL,
# 'u': 'bool',
# 'v': turn_fan_on,
#}
finally:
sock.close()
return result
except socket.error:
print("Could not UDS communicate with LED daemon.")
def sensor_harvest():
readings = {}
for sensor in SENSORS:
readings.update(eval("harvest_" + sensor + "()"))
return readings
def harvest_mg811():
instance = mg811.MG811(MG811_PIN, in_analog_ch=1)
result = instance.read()
return {
'co2': {
'm': SENSOR_CO2_MODEL,
'u': 'relative',
'v': result.raw(),
}
}
def harvest_dht11():
instance = dht11.DHT11(pin=DHT_PIN)
result = instance.read()
if result.is_valid():
return {
'temperature': {
'm': SENSOR_TEMPERATURE_MODEL,
'u': 'celsius',
'v': result.temperature,
},
'humidity': {
'm': SENSOR_HUMIDITY_MODEL,
'u': 'percent',
'v': result.humidity,
}
}
else:
print("Could not read DHT11")
return {}
def backup(img_file, key):
backend.api.backups([img_file], [key])
def post(data):
data['client'] = {
'v': CLIENT_VERSION,
'i': CLIENT_ID,
'm': CLIENT_MODEL,
}
data['api'] = API_VERSION
backend.api.record(data)
def run():
# Get local time
try:
time_client = ntplib.NTPClient()
response = time_client.request('pool.ntp.org')
local_time = datetime.datetime.fromtimestamp(response.tx_time)
except:
local_time = datetime.datetime.now()
night_start = datetime.time(21)
night_end = datetime.time(4)
if local_time.time() > night_start or local_time.time() < night_end:
turn_on_leds = True
else:
turn_on_leds = False
camera, full_path = snapshot()
sensors = sensor_harvest()
#if sensors['co2']['v'] > 0 and mg811.MG811Result(sensors['co2']['v']).compared_to_air() == 'low':
# turn_fan_on=True
#else:
# turn_fan_on=False
cmd_results = cmd(
turn_blue_on=turn_on_leds,
turn_red_on=turn_on_leds
)
state = {
'camera': camera,
'leds': cmd_results['leds'],
}
state.update(sensors)
post({
'ts': datetime.datetime.utcnow().isoformat(),
'state': state
})
backup(full_path, camera['v'])
if os.path.exists(full_path):
os.remove(full_path)
if __name__ == '__main__':
run()