-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflask_app.py
343 lines (294 loc) · 10.2 KB
/
flask_app.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
from flask import Flask, request, Response
from flask_sqlalchemy import SQLAlchemy
from flask_restful_swagger_2 import Api
from flask_restful_swagger_2 import swagger, Resource, Schema
from collections import OrderedDict
from configparser import ConfigParser
from werkzeug import secure_filename
import os
# Read config file
config = ConfigParser()
config.read('flask_app.cfg')
database_uri = config.get('SQLAlchemy', 'database_uri')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = database_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
db = SQLAlchemy(app)
ALLOWED_EXTENSIONS = ['jpg']
# Use the swagger Api class as you would use the flask restful class.
# It supports several (optional) parameters, these are the defaults:
api = Api(app, api_version='0.0', api_spec_url='/api/swagger')
class MifloraModel(Schema):
type = 'object'
properties = {
'device': {
'type': 'string'
},
'timestamp': {
'type': 'string'
},
'moisture': {
'type': 'number'
},
'temperature': {
'type': 'number'
},
'conductivity': {
'type': 'number'
},
'light': {
'type': 'number'
}
}
class BME280Model(Schema):
type = 'object'
properties = {
'device': {
'type': 'string'
},
'timestamp': {
'type': 'string'
},
'temperature': {
'type': 'number'
},
'pressure': {
'type': 'number'
},
'humidity': {
'type': 'number'
}
}
class SI1145Model(Schema):
type = 'object'
properties = {
'device': {
'type': 'string'
},
'timestamp': {
'type': 'string'
},
'visible': {
'type': 'number'
},
'IR': {
'type': 'number'
},
'UV': {
'type': 'number'
}
}
class PumpModel(Schema):
type = 'object'
properties = {
'device': {
'type': 'string'
},
'timestamp': {
'type': 'string'
},
'duration': {
'type': 'number'
}
}
class ErrorModel(Schema):
type = 'object'
properties = {
'message': {
'type': 'string'
}
}
class MifloraResource(Resource):
@swagger.doc({
'tags': ['measurement'],
'description': 'Adds a measurement from the plant sensor',
'parameters': [
{
'name': 'measurement',
'description': 'Measurement that needs to be added to a csv file and to the database',
'in': 'body',
'schema': MifloraModel,
'required': True,
}
],
'responses': {
'201': {
'description': 'Added measurement',
'schema': MifloraModel
}
}
})
def post(self):
# curl -H "Content-Type: application/json" -X POST -d '{"device":"C4:7C:8D:65:BD:76", "timestamp": "2018-01-23 22:00:41.062114", "moisture": 0, "temperature": 19.7, "conductivity": 0, "light": 39}' http://ec2-34-243-27-176.eu-west-1.compute.amazonaws.com:5000/measurement
# Validate request body with schema model
try:
measurement = MifloraModel(**request.get_json())
except ValueError as e:
return ErrorModel(**{'message': e.args[0]}), 400
print(measurement)
# Make sure the entries are in the correct order
keys = ['timestamp', 'moisture', 'temperature', 'conductivity', 'light']
ordered = OrderedDict([(key, measurement[key]) for key in keys])
# Append to a csv file for the device
csvfile = "/data/measurements/{}.csv".format(measurement['device'].replace(':', ''))
with open(csvfile, "a") as f:
f.write(", ".join([str(x) for x in ordered.values()]) + '\n')
# Insert into PostgreSQL database
query = """INSERT INTO measurements (device, time, moisture, temperature, conductivity, light)
VALUES ('%(device)s', '%(timestamp)s', %(moisture)s, %(temperature)s, %(conductivity)s, %(light)s);""" % measurement
db.engine.execute(query)
return measurement, 201
api.add_resource(MifloraResource, '/measurement')
class BME280Resource(Resource):
@swagger.doc({
'tags': ['measurement'],
'description': 'Adds a measurement from the BME280 sensor',
'parameters': [
{
'name': 'measurement',
'description': 'Measurement that needs to be added to a csv file and to the database',
'in': 'body',
'schema': BME280Model,
'required': True,
}
],
'responses': {
'201': {
'description': 'Added measurement',
'schema': BME280Model
}
}
})
def post(self):
# Validate request body with schema model
try:
measurement = BME280Model(**request.get_json())
except ValueError as e:
return ErrorModel(**{'message': e.args[0]}), 400
print(measurement)
# Make sure the entries are in the correct order
keys = ['timestamp', 'temperature', 'pressure', 'humidity']
ordered = OrderedDict([(key, measurement[key]) for key in keys])
# Append to a csv file for the device
csvfile = "/data/measurements/BME280_{}.csv".format(measurement['device'])
with open(csvfile, "a") as f:
f.write(", ".join([str(x) for x in ordered.values()]) + '\n')
# Insert into PostgreSQL database
query = """INSERT INTO bme280 (device, time, temperature, pressure, humidity)
VALUES ('%(device)s', '%(timestamp)s', %(temperature)s, %(pressure)s, %(humidity)s);""" % measurement
db.engine.execute(query)
return measurement, 201
api.add_resource(BME280Resource, '/bme280')
class SI1145Resource(Resource):
@swagger.doc({
'tags': ['measurement'],
'description': 'Adds a measurement from the SI1145 sensor',
'parameters': [
{
'name': 'measurement',
'description': 'Measurement that needs to be added to a csv file and to the database',
'in': 'body',
'schema': SI1145Model,
'required': True,
}
],
'responses': {
'201': {
'description': 'Added measurement',
'schema': SI1145Model
}
}
})
def post(self):
# Validate request body with schema model
try:
measurement = SI1145Model(**request.get_json())
except ValueError as e:
return ErrorModel(**{'message': e.args[0]}), 400
print(measurement)
# Make sure the entries are in the correct order
keys = ['timestamp', 'visible', 'IR', 'UV']
ordered = OrderedDict([(key, measurement[key]) for key in keys])
# Append to a csv file for the device
csvfile = "/data/measurements/SI1145_{}.csv".format(measurement['device'])
with open(csvfile, "a") as f:
f.write(", ".join([str(x) for x in ordered.values()]) + '\n')
# Insert into PostgreSQL database
query = """INSERT INTO si1145 (device, time, visible, IR, UV)
VALUES ('%(device)s', '%(timestamp)s', %(visible)s, %(IR)s, %(UV)s);""" % measurement
db.engine.execute(query)
return measurement, 201
api.add_resource(SI1145Resource, '/si1145')
class PumpResource(Resource):
@swagger.doc({
'tags': ['pump'],
'description': 'Adds a pump watering duration',
'parameters': [
{
'name': 'pump',
'description': 'Pump watering duration that needs to be added to a csv file and to the database',
'in': 'body',
'schema': PumpModel,
'required': True,
}
],
'responses': {
'201': {
'description': 'Added pump watering duration',
'schema': PumpModel
}
}
})
def post(self):
# Validate request body with schema model
try:
pump_log = PumpModel(**request.get_json())
except ValueError as e:
return ErrorModel(**{'message': e.args[0]}), 400
print(pump_log)
# Make sure the entries are in the correct order
keys = ['timestamp', 'duration']
ordered = OrderedDict([(key, pump_log[key]) for key in keys])
# Append to a csv file for the device
csvfile = "/data/measurements/pump_{}.csv".format(pump_log['device'].replace(':', ''))
with open(csvfile, "a") as f:
f.write(", ".join([str(x) for x in ordered.values()]) + '\n')
# Insert into PostgreSQL database
query = """INSERT INTO pump (device, time, duration)
VALUES ('%(device)s', '%(timestamp)s', %(duration)s);""" % pump_log
db.engine.execute(query)
return pump_log, 201
api.add_resource(PumpResource, '/pump')
class ImageResource(Resource):
@swagger.doc({
'tags': ['image'],
'description': 'Adds an image',
'parameters': [
{
'name': 'image',
'description': 'Snapshot that needs to be saved as a file',
'in': 'formData',
'type': 'file',
'required': True,
}
],
'responses': {
'201': {
'description': 'Added image',
}
}
})
def post(self):
f = request.files['file']
filename = secure_filename(f.filename)
if '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS:
print(filename)
f.save(os.path.join('/data/images', filename))
else:
return None, 400
return None, 201
api.add_resource(ImageResource, '/image')
if __name__ == '__main__':
# Specify host 0.0.0.0 to make the service visible to the outside world.
app.run(host='0.0.0.0', port=5000)