-
-
Notifications
You must be signed in to change notification settings - Fork 488
/
flaskutils.py
2841 lines (2508 loc) · 113 KB
/
flaskutils.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import logging
import bcrypt
import functools
import gzip
import os
import re
import requests
import sqlalchemy
import time
import flask_login
from collections import OrderedDict
from datetime import datetime
from cStringIO import StringIO as IO
from flask import (
after_this_request,
flash,
redirect,
request,
url_for
)
from mycodo.mycodo_flask.extensions import db
from flask_babel import gettext
from RPi import GPIO
# Classes
from mycodo.databases.models import (
Camera,
Conditional,
ConditionalActions,
DisplayOrder,
Graph,
LCD,
Method,
MethodData,
Misc,
PID,
Relay,
Remote,
Role,
SMTP,
Sensor,
Timer,
User
)
from mycodo.mycodo_client import DaemonControl
from mycodo.utils.utils import (
test_username,
test_password
)
from mycodo.utils.send_data import send_email
from mycodo.utils.system_pi import (
csv_to_list_of_int,
is_int,
list_to_csv
)
from mycodo.config import (
CAMERAS,
DEVICES_DEFAULT_LOCATION,
INSTALL_DIRECTORY
)
logger = logging.getLogger(__name__)
#
# Method Development
#
def is_positive_integer(number_string):
try:
if int(number_string) < 0:
flash(gettext(u"Duration must be a positive integer"), "error")
return False
except ValueError:
flash(gettext(u"Duration must be a valid integer"), "error")
return False
return True
def validate_method_data(form_data, this_method):
if form_data.method_select.data == 'setpoint':
if this_method.method_type == 'Date':
if (not form_data.startTime.data or
not form_data.endTime.data or
form_data.startSetpoint.data == ''):
flash(gettext(u"Required: Start date/time, end date/time, "
u"start setpoint"), "error")
return 1
try:
start_time = datetime.strptime(form_data.startTime.data,
'%Y-%m-%d %H:%M:%S')
end_time = datetime.strptime(form_data.endTime.data,
'%Y-%m-%d %H:%M:%S')
except ValueError:
flash(gettext(u"Invalid Date/Time format. Correct format: "
u"DD/MM/YYYY HH:MM:SS"), "error")
return 1
if end_time <= start_time:
flash(gettext(u"The end time/date must be after the start "
u"time/date."), "error")
return 1
elif this_method.method_type == 'Daily':
if (not form_data.startDailyTime.data or
not form_data.endDailyTime.data or
form_data.startSetpoint.data == ''):
flash(gettext(u"Required: Start time, end time, start "
u"setpoint"), "error")
return 1
try:
start_time = datetime.strptime(form_data.startDailyTime.data,
'%H:%M:%S')
end_time = datetime.strptime(form_data.endDailyTime.data,
'%H:%M:%S')
except ValueError:
flash(gettext(u"Invalid Date/Time format. Correct format: "
u"HH:MM:SS"), "error")
return 1
if end_time <= start_time:
flash(gettext(u"The end time must be after the start time."),
"error")
return 1
elif this_method.method_type == 'Duration':
if (not form_data.DurationSec.data or
form_data.startSetpoint.data == ''):
flash(gettext(u"Required: Duration, start setpoint"),
"error")
return 1
if not is_positive_integer(form_data.DurationSec.data):
return 1
elif form_data.method_select.data == 'relay':
if this_method.method_type == 'Date':
if (not form_data.relayTime.data or
not form_data.relayID.data or
not form_data.relayState.data):
flash(gettext(u"Required: Date/Time, Relay ID, and Relay "
"State"), "error")
return 1
try:
datetime.strptime(form_data.relayTime.data,
'%Y-%m-%d %H:%M:%S')
except ValueError:
flash(gettext(u"Invalid Date/Time format. Correct format: "
u"DD-MM-YYYY HH:MM:SS"), "error")
return 1
elif this_method.method_type == 'Duration':
if (not form_data.DurationSec.data or
not form_data.relayID.data or
not form_data.relayState.data):
flash(gettext(u"Required: Relay ID, Relay State, and Relay Duration"),
"error")
return 1
if not is_positive_integer(form_data.relayDurationSec.data):
return 1
elif this_method.method_type == 'Daily':
if (not form_data.relayDailyTime.data or
not form_data.relayID.data or
not form_data.relayState.data):
flash(gettext(u"Required: Time, Relay ID, and Relay State"),
"error")
return 1
try:
datetime.strptime(form_data.relayDailyTime.data,
'%H:%M:%S')
except ValueError:
flash(gettext(u"Invalid Date/Time format. Correct format: "
u"HH:MM:SS"), "error")
return 1
def method_create(form_create_method):
""" Create new method table entry (all data stored in method_data table) """
action = u'{action} {controller}'.format(
action=gettext(u"Create"),
controller=gettext(u"Method"))
error = []
try:
# Create method
new_method = Method()
new_method.name = form_create_method.name.data
new_method.method_type = form_create_method.method_type.data
db.session.add(new_method)
db.session.commit()
# Add new method line id to method display order
method_order = DisplayOrder.query.first()
display_order = csv_to_list_of_int(method_order.method)
method_order.method = add_display_order(display_order, new_method.id)
db.session.commit()
# For tables that require only one entry to configure,
# create that single entry now with default values
if new_method.method_type == 'DailySine':
new_method_data = MethodData()
new_method_data.method_id = new_method.id
new_method_data.amplitude = 1.0
new_method_data.frequency = 1.0
new_method_data.shift_angle = 0
new_method_data.shift_y = 1.0
db.session.add(new_method_data)
db.session.commit()
elif new_method.method_type == 'DailyBezier':
new_method_data = MethodData()
new_method_data.method_id = new_method.id
new_method_data.shift_angle = 0.0
new_method_data.x0 = 20.0
new_method_data.y0 = 20.0
new_method_data.x1 = 10.0
new_method_data.y1 = 13.5
new_method_data.x2 = 22.5
new_method_data.y2 = 30.0
new_method_data.x3 = 0.0
new_method_data.y3 = 20.0
db.session.add(new_method_data)
db.session.commit()
# Add new method data line id to method_data display order
if new_method.method_type in ['DailyBezier', 'DailySine']:
display_order = csv_to_list_of_int(new_method.method_order)
method = Method.query.filter(Method.id == new_method.id).first()
method.method_order = add_display_order(display_order,
new_method_data.id)
db.session.commit()
return 0
except Exception as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('method_routes.method_list'))
def method_add(form_add_method):
""" Add line to method_data table """
action = u'{action} {controller}'.format(
action=gettext(u"Add"),
controller=gettext(u"Method"))
error = []
method = Method.query.filter(Method.id == form_add_method.method_id.data).first()
display_order = csv_to_list_of_int(method.method_order)
try:
if validate_method_data(form_add_method, method):
return 1
if method.method_type == 'DailySine':
add_method_data = MethodData.query.filter(
MethodData.method_id == form_add_method.method_id.data).first()
add_method_data.amplitude = form_add_method.amplitude.data
add_method_data.frequency = form_add_method.frequency.data
add_method_data.shift_angle = form_add_method.shiftAngle.data
add_method_data.shift_y = form_add_method.shiftY.data
db.session.commit()
return 0
elif method.method_type == 'DailyBezier':
if not 0 <= form_add_method.shiftAngle.data <= 360:
flash(gettext(u"Error: Angle Shift is out of range. It must be "
u"<= 0 and <= 360."), "error")
return 1
if form_add_method.x0.data <= form_add_method.x3.data:
flash(gettext(u"Error: X0 must be greater than X3."), "error")
return 1
add_method_data = MethodData.query.filter(
MethodData.method_id == form_add_method.method_id.data).first()
add_method_data.shift_angle = form_add_method.shiftAngle.data
add_method_data.x0 = form_add_method.x0.data
add_method_data.y0 = form_add_method.y0.data
add_method_data.x1 = form_add_method.x1.data
add_method_data.y1 = form_add_method.y1.data
add_method_data.x2 = form_add_method.x2.data
add_method_data.y2 = form_add_method.y2.data
add_method_data.x3 = form_add_method.x3.data
add_method_data.y3 = form_add_method.y3.data
db.session.commit()
return 0
if form_add_method.method_select.data == 'setpoint':
if method.method_type == 'Date':
start_time = datetime.strptime(form_add_method.startTime.data,
'%Y-%m-%d %H:%M:%S')
end_time = datetime.strptime(form_add_method.endTime.data,
'%Y-%m-%d %H:%M:%S')
elif method.method_type == 'Daily':
start_time = datetime.strptime(form_add_method.startDailyTime.data,
'%H:%M:%S')
end_time = datetime.strptime(form_add_method.endDailyTime.data,
'%H:%M:%S')
if method.method_type in ['Date', 'Daily']:
# Check if the start time comes after the last entry's end time
display_order = csv_to_list_of_int(method.method_order)
if display_order:
last_method = MethodData.query.filter(MethodData.id == display_order[-1]).first()
else:
last_method = None
if last_method is not None:
if method.method_type == 'Date':
last_method_end_time = datetime.strptime(last_method.time_end,
'%Y-%m-%d %H:%M:%S')
elif method.method_type == 'Daily':
last_method_end_time = datetime.strptime(last_method.time_end,
'%H:%M:%S')
if start_time < last_method_end_time:
flash(gettext(u"The new entry start time (%(st)s) "
u"cannot overlap the last entry's end "
u"time (%(et)s). Note: They may be the "
u"same time.",
st=last_method_end_time,
et=start_time),
"error")
return 1
elif form_add_method.method_select.data == 'relay':
if method.method_type == 'Date':
start_time = datetime.strptime(form_add_method.relayTime.data,
'%Y-%m-%d %H:%M:%S')
elif method.method_type == 'Daily':
start_time = datetime.strptime(form_add_method.relayDailyTime.data,
'%H:%M:%S')
add_method_data = MethodData()
add_method_data.method_id = form_add_method.method_id.data
if method.method_type == 'Date':
if form_add_method.method_select.data == 'setpoint':
add_method_data.time_start = start_time.strftime('%Y-%m-%d %H:%M:%S')
add_method_data.time_end = end_time.strftime('%Y-%m-%d %H:%M:%S')
if form_add_method.method_select.data == 'relay':
add_method_data.time_start = form_add_method.relayTime.data
elif method.method_type == 'Daily':
if form_add_method.method_select.data == 'setpoint':
add_method_data.time_start = start_time.strftime('%H:%M:%S')
add_method_data.time_end = end_time.strftime('%H:%M:%S')
if form_add_method.method_select.data == 'relay':
add_method_data.time_start = form_add_method.relayDailyTime.data
elif method.method_type == 'Duration':
add_method_data.duration_sec = form_add_method.DurationSec.data
if form_add_method.method_select.data == 'setpoint':
add_method_data.setpoint_start = form_add_method.startSetpoint.data
add_method_data.setpoint_end = form_add_method.endSetpoint.data
elif form_add_method.method_select.data == 'relay':
add_method_data.relay_id = form_add_method.relayID.data
add_method_data.relay_state = form_add_method.relayState.data
add_method_data.relay_duration = form_add_method.relayDurationSec.data
db.session.add(add_method_data)
db.session.commit()
# Add line to method data list if not a relay duration
if form_add_method.method_select.data != 'relay':
method.method_order = add_display_order(display_order,
add_method_data.id)
db.session.commit()
if form_add_method.method_select.data == 'setpoint':
if method.method_type == 'Date':
flash(gettext(u"Added duration to method from %(st)s to "
u"%(end)s", st=start_time, end=end_time),
"success")
elif method.method_type == 'Daily':
flash(gettext(u"Added duration to method from %(st)s to "
u"%(end)s",
st=start_time.strftime('%H:%M:%S'),
end=end_time.strftime('%H:%M:%S')),
"success")
elif method.method_type == 'Duration':
flash(gettext(u"Added duration to method for %(sec)s seconds",
sec=form_add_method.DurationSec.data), "success")
elif form_add_method.method_select.data == 'relay':
if method.method_type == 'Date':
flash(gettext(u"Added relay modulation to method at start "
u"time: %(tm)s", tm=start_time), "success")
elif method.method_type == 'Daily':
flash(gettext(u"Added relay modulation to method at start "
u"time: %(tm)s",
tm=start_time.strftime('%H:%M:%S')), "success")
elif method.method_type == 'Duration':
flash(gettext(u"Added relay modulation to method at start "
u"time: %(tm)s",
tm=form_add_method.DurationSec.data), "success")
except Exception as except_msg:
logger.exception(1)
error.append(except_msg)
flash_success_errors(error, action, url_for('method_routes.method_list'))
def method_mod(form_mod_method):
action = u'{action} {controller}'.format(
action=gettext(u"Modify"),
controller=gettext(u"Method"))
error = []
method = Method.query.filter(
Method.id == form_mod_method.method_id.data).first()
method_data = MethodData.query.filter(
MethodData.id == form_mod_method.method_data_id.data).first()
display_order = csv_to_list_of_int(method.method_order)
try:
if form_mod_method.Delete.data:
delete_entry_with_id(MethodData,
form_mod_method.method_data_id.data)
if form_mod_method.method_select.data != 'relay':
method_order = Method.query.filter(Method.id == method.id).first()
display_order = csv_to_list_of_int(method_order.method_order)
display_order.remove(method_data.id)
method_order.method_order = list_to_csv(display_order)
db.session.commit()
return 0
if form_mod_method.rename.data:
method.name = form_mod_method.name.data
db.session.commit()
return 0
# Ensure data is valid
if validate_method_data(form_mod_method, method):
return 1
if form_mod_method.method_select.data == 'setpoint':
if method.method_type == 'Date':
start_time = datetime.strptime(form_mod_method.startTime.data, '%Y-%m-%d %H:%M:%S')
end_time = datetime.strptime(form_mod_method.endTime.data, '%Y-%m-%d %H:%M:%S')
# Ensure the start time comes after the previous entry's end time
# and the end time comes before the next entry's start time
# method_id_set is the id given to all method entries, 'method_id', not 'id'
previous_method = None
next_method = None
for index, each_order in enumerate(display_order):
if each_order == method_data.id:
if len(display_order) > 1 and index > 0:
previous_method = MethodData.query.filter(
MethodData.id == display_order[index-1]).first()
if len(display_order) > index+1:
next_method = MethodData.query.filter(
MethodData.id == display_order[index+1]).first()
if previous_method is not None and previous_method.time_end is not None:
previous_end_time = datetime.strptime(
previous_method.time_end, '%Y-%m-%d %H:%M:%S')
if previous_end_time is not None and start_time < previous_end_time:
error.append(
gettext(u"The entry start time (%(st)s) cannot "
u"overlap the previous entry's end time "
u"(%(et)s)",
st=start_time, et=previous_end_time))
if next_method is not None and next_method.time_start is not None:
next_start_time = datetime.strptime(
next_method.time_start, '%Y-%m-%d %H:%M:%S')
if next_start_time is not None and end_time > next_start_time:
error.append(
gettext(u"The entry end time (%(et)s) cannot "
u"overlap the next entry's start time "
u"(%(st)s)",
et=end_time, st=next_start_time))
method_data.time_start = start_time.strftime('%Y-%m-%d %H:%M:%S')
method_data.time_end = end_time.strftime('%Y-%m-%d %H:%M:%S')
elif method.method_type == 'Duration':
method_data.duration_sec = form_mod_method.DurationSec.data
elif method.method_type == 'Daily':
method_data.time_start = form_mod_method.startDailyTime.data
method_data.time_end = form_mod_method.endDailyTime.data
method_data.setpoint_start = form_mod_method.startSetpoint.data
method_data.setpoint_end = form_mod_method.endSetpoint.data
elif form_mod_method.method_select.data == 'relay':
if method.method_type == 'Date':
method_data.time_start = form_mod_method.relayTime.data
elif method.method_type == 'Duration':
method_data.duration_sec = form_mod_method.DurationSec.data
if form_mod_method.relay_id.data == '':
method_data.relay_id = None
else:
method_data.relay_id = form_mod_method.relayID.data
method_data.relay_state = form_mod_method.relayState.data
method_data.relay_duration = form_mod_method.relayDurationSec.data
elif method.method_type == 'DailySine':
if form_mod_method.method_select.data == 'relay':
method_data.time_start = form_mod_method.relayTime.data
if form_mod_method.relay_id.data == '':
method_data.relay_id = None
else:
method_data.relay_id = form_mod_method.relayID.data
method_data.relay_state = form_mod_method.relayState.data
method_data.relay_duration = form_mod_method.relayDurationSec.data
if not error:
db.session.commit()
except Exception as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('method_routes.method_list'))
def method_del(method_id):
action = u'{action} {controller}'.format(
action=gettext(u"Delete"),
controller=gettext(u"Method"))
error = []
try:
delete_entry_with_id(Method,
method_id)
except Exception as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('method_routes.method_list'))
#
# Authenticate remote hosts
#
def check_new_credentials(address, user, passw):
credentials = {
'user': user,
'passw': passw
}
url = 'https://{}/newremote/'.format(address)
try:
r = requests.get(url, params=credentials, verify=False)
return r.json()
except Exception as msg:
return {
'status': 1,
'message': "Error connecting to host: {err}".format(err=msg)
}
def auth_credentials(address, user, password_hash):
credentials = {
'user': user,
'pw_hash': password_hash
}
url = 'https://{}/auth/'.format(address)
try:
r = requests.get(url, params=credentials, verify=False)
return int(r.text)
except Exception as e:
logger.error(
"'auth_credentials' raised an exception: {err}".format(err=e))
return 1
def remote_host_add(form_setup, display_order):
if not user_has_permission('edit_settings'):
return redirect(url_for('general_routes.home'))
if form_setup.validate():
try:
pw_check = check_new_credentials(form_setup.host.data,
form_setup.username.data,
form_setup.password.data)
if pw_check['status']:
flash(pw_check['message'], "error")
return 1
new_remote_host = Remote()
new_remote_host.host = form_setup.host.data
new_remote_host.username = form_setup.username.data
new_remote_host.password_hash = pw_check['message']
try:
db.session.add(new_remote_host)
db.session.commit()
flash(gettext(u"Remote Host %(host)s with ID %(id)s (%(uuid)s)"
u" successfully added",
host=form_setup.host.data,
id=new_remote_host.id,
uuid=new_remote_host.unique_id),
"success")
DisplayOrder.query.first().remote_host = add_display_order(
display_order, new_remote_host.id)
db.session.commit()
except sqlalchemy.exc.OperationalError as except_msg:
flash(gettext(u"Remote Host Error: %(msg)s", msg=except_msg),
"error")
except sqlalchemy.exc.IntegrityError as except_msg:
flash(gettext(u"Remote Host Error: %(msg)s", msg=except_msg),
"error")
except Exception as except_msg:
flash(gettext(u"Remote Host Error: %(msg)s", msg=except_msg),
"error")
else:
flash_form_errors(form_setup)
def remote_host_del(form_setup):
if not user_has_permission('edit_settings'):
return redirect(url_for('general_routes.home'))
try:
delete_entry_with_id(Remote,
form_setup.remote_id.data)
display_order = csv_to_list_of_int(DisplayOrder.query.first().remote_host)
display_order.remove(int(form_setup.remote_id.data))
DisplayOrder.query.first().remote_host = list_to_csv(display_order)
db.session.commit()
except Exception as except_msg:
flash(gettext(u"Remote Host Error: %(msg)s", msg=except_msg), "error")
#
# Manipulate relay settings while daemon is running
#
def manipulate_relay(action, relay_id, setup_pin=False):
"""
Add, delete, and modify relay settings while the daemon is active
:param relay_id: relay ID in the SQL database
:type relay_id: str
:param action: add, del, or mod
:type action: str
:param setup_pin: Initialize new pin (if changed)
:type setup_pin: bool
"""
control = DaemonControl()
return_values = control.relay_setup(action, relay_id, setup_pin)
if return_values[0]:
flash(gettext(u"Error: %(err)s",
err=u'{action} Relay: Daemon response: {msg}'.format(
action=action,
msg=return_values[1])),
"error")
else:
flash(gettext(u"Success: %(err)s",
err=u'{action} Relay: Daemon response: {msg}'.format(
action=gettext(action),
msg=return_values[1])),
"success")
#
# Activate/deactivate controller
#
def controller_activate_deactivate(controller_action,
controller_type,
controller_id):
"""
Activate or deactivate controller
:param controller_action: Activate or deactivate
:type controller_action: str
:param controller_type: The controller type (LCD, PID, Sensor, Timer)
:type controller_type: str
:param controller_id: Controller with ID to activate or deactivate
:type controller_id: str
"""
if not user_has_permission('edit_controllers'):
return redirect(url_for('general_routes.home'))
if controller_action == 'activate':
activated = True
else:
activated = False
translated_names = {
"LCD": gettext(u"LCD"),
"PID": gettext(u"PID"),
"Sensor": gettext(u"Sensor"),
"Timer": gettext(u"Timer")
}
mod_controller = None
if controller_type == 'LCD':
mod_controller = LCD.query.filter(
LCD.id == int(controller_id)).first()
elif controller_type == 'PID':
mod_controller = PID.query.filter(
PID.id == int(controller_id)).first()
elif controller_type == 'Sensor':
mod_controller = Sensor.query.filter(
Sensor.id == int(controller_id)).first()
elif controller_type == 'Timer':
mod_controller = Timer.query.filter(
Timer.id == int(controller_id)).first()
if mod_controller is None:
return redirect(url_for('general_routes.home'))
try:
mod_controller.is_activated = activated
db.session.commit()
if activated:
flash(gettext(u"%(cont)s controller activated in SQL database",
cont=translated_names[controller_type]),
"success")
else:
flash(gettext(u"%(cont)s controller deactivated in SQL database",
cont=translated_names[controller_type]),
"success")
except Exception as except_msg:
flash(gettext(u"Error: %(err)s",
err=u'SQL: {msg}'.format(msg=except_msg)),
"error")
try:
control = DaemonControl()
if controller_action == 'activate':
return_values = control.controller_activate(controller_type,
int(controller_id))
else:
return_values = control.controller_deactivate(controller_type,
int(controller_id))
if return_values[0]:
flash("{err}".format(err=return_values[1]), "error")
else:
flash("{err}".format(err=return_values[1]), "success")
except Exception as except_msg:
flash(gettext(u"Error: %(err)s",
err=u'Daemon: {msg}'.format(msg=except_msg)),
"error")
#
# Choices
#
# return a dictionary of all available measurements
# Used to produce a multi-select form input for creating/modifying custom graphs
def choices_sensors(sensor):
choices = OrderedDict()
# populate form multi-select choices for sensors and measurements
for each_sensor in sensor:
if each_sensor.device == 'MYCODO_RAM':
value = '{},disk_space'.format(each_sensor.unique_id)
display = '{} ({}) Daemon Ram Use (MB)'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device == 'RPiCPULoad':
value = '{},cpu_load_1m'.format(each_sensor.unique_id)
display = '{} ({}) CPU Load (1m)'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
value = '{},cpu_load_5m'.format(each_sensor.unique_id)
display = '{} ({}) CPU Load (5m)'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
value = '{},cpu_load_15m'.format(each_sensor.unique_id)
display = '{} ({}) CPU Load (15m)'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device == 'RPiFreeSpace':
value = '{},disk_space'.format(each_sensor.unique_id)
display = '{} ({}) Free Space'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device == 'CHIRP':
value = '{},moisture'.format(each_sensor.unique_id)
display = '{} ({}) Moisture'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device in ['AM2315', 'ATLAS_PT1000', 'BME280', 'BMP',
'CHIRP', 'DHT11', 'DHT22', 'DS18B20',
'HTU21D', 'RPi', 'SHT1x_7x', 'SHT2x']:
value = '{},temperature'.format(each_sensor.unique_id)
display = '{} ({}) Temperature'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device == 'TMP006':
value = '{},temperature_object'.format(each_sensor.unique_id)
display = '{} ({}) Temperature (Object)'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
value = '{},temperature_die'.format(each_sensor.unique_id)
display = '{} ({}) Temperature (Die)'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device in ['AM2315', 'BME280', 'DHT11', 'DHT22', 'HTU21D',
'SHT1x_7x', 'SHT2x']:
value = '{},humidity'.format(each_sensor.unique_id)
display = '{} ({}) Humidity'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
value = '{},dewpoint'.format(each_sensor.unique_id)
display = '{} ({}) Dew Point'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device == 'K30':
value = '{},co2'.format(each_sensor.unique_id)
display = '{} ({}) CO2'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device in ['BME280', 'BMP']:
value = '{},pressure'.format(each_sensor.unique_id)
display = '{} ({}) Pressure'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
value = '{},altitude'.format(each_sensor.unique_id)
display = '{} ({}) Altitude'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device == 'EDGE':
value = '{},edge'.format(each_sensor.unique_id)
display = '{} ({}) Edge'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
if each_sensor.device in ['ADS1x15', 'MCP342x']:
value = '{},voltage'.format(each_sensor.unique_id)
display = '{} ({}) Volts'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
value = '{},{}'.format(each_sensor.unique_id, each_sensor.adc_measure)
display = '{} ({}) {}'.format(
each_sensor.id, each_sensor.name, each_sensor.adc_measure)
choices.update({value: display})
if each_sensor.device in ['CHIRP', 'TSL2561']:
value = '{},lux'.format(each_sensor.unique_id)
display = '{} ({}) Lux'.format(
each_sensor.id, each_sensor.name)
choices.update({value: display})
return choices
# Return a dictionary of all available ids and names
# produce a multi-select form input for creating/modifying custom graphs
def choices_id_name(table):
choices = OrderedDict()
# populate form multi-select choices for relays
for each_entry in table:
value = each_entry.unique_id
display = '{id} ({name})'.format(id=each_entry.id,
name=each_entry.name)
choices.update({value: display})
return choices
#
# Graph
#
def graph_add(form_add_graph, display_order):
action = u'{action} {controller}'.format(
action=gettext(u"Add"),
controller=gettext(u"Graph"))
error = []
if (form_add_graph.name.data and form_add_graph.width.data and
form_add_graph.height.data and form_add_graph.xAxisDuration.data and
form_add_graph.refreshDuration.data):
new_graph = Graph()
new_graph.name = form_add_graph.name.data
if form_add_graph.pidIDs.data:
pid_ids_joined = ",".join(str(form_add_graph.pidIDs.data))
new_graph.pid_ids = pid_ids_joined
if form_add_graph.relayIDs.data:
relay_ids_joined = ",".join(str(form_add_graph.relayIDs.data))
new_graph.relay_ids = relay_ids_joined
if form_add_graph.sensorIDs.data:
sensor_ids_joined = ";".join(form_add_graph.sensorIDs.data)
new_graph.sensor_ids_measurements = sensor_ids_joined
new_graph.width = form_add_graph.width.data
new_graph.height = form_add_graph.height.data
new_graph.x_axis_duration = form_add_graph.xAxisDuration.data
new_graph.refresh_duration = form_add_graph.refreshDuration.data
new_graph.enable_navbar = form_add_graph.enableNavbar.data
new_graph.enable_rangeselect = form_add_graph.enableRangeSelect.data
new_graph.enable_export = form_add_graph.enableExport.data
try:
new_graph.save()
flash(gettext(
u"Graph with ID %(id)s successfully added",
id=new_graph.id),
"success")
DisplayOrder.query.first().graph = add_display_order(
display_order, new_graph.id)
db.session.commit()
except sqlalchemy.exc.OperationalError as except_msg:
error.append(except_msg)
except sqlalchemy.exc.IntegrityError as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('page_routes.page_graph'))
else:
flash_form_errors(form_add_graph)
def graph_mod(form_mod_graph, request_form):
action = u'{action} {controller}'.format(
action=gettext(u"Modify"),
controller=gettext(u"Graph"))
error = []
if form_mod_graph.validate():
def is_rgb_color(color_hex):
return bool(re.compile(r'#[a-fA-F0-9]{6}$').match(color_hex))
# Get variable number of color inputs, turn into CSV string
colors = {}
f = request_form
for key in f.keys():
if 'color_number' in key:
for value in f.getlist(key):
if not is_rgb_color(value):
flash(gettext(u"Invalid hex color value"), "error")
return redirect(url_for('page_routes.page_graph'))
colors[key[12:]] = value
sorted_list = [(k, colors[k]) for k in sorted(colors)]
short_list = []
for each_color in sorted_list:
short_list.append(each_color[1])
sorted_colors_string = ",".join(short_list)
try:
mod_graph = Graph.query.filter(
Graph.id == form_mod_graph.graph_id.data).first()
mod_graph.custom_colors = sorted_colors_string
mod_graph.use_custom_colors = form_mod_graph.use_custom_colors.data
mod_graph.name = form_mod_graph.name.data
if form_mod_graph.pidIDs.data:
pid_ids_joined = ",".join(form_mod_graph.pidIDs.data)
mod_graph.pid_ids = pid_ids_joined
else:
mod_graph.pid_ids = ''
if form_mod_graph.relayIDs.data:
relay_ids_joined = ",".join(form_mod_graph.relayIDs.data)
mod_graph.relay_ids = relay_ids_joined
else:
mod_graph.relay_ids = ''
if form_mod_graph.sensorIDs.data:
sensor_ids_joined = ";".join(form_mod_graph.sensorIDs.data)
mod_graph.sensor_ids_measurements = sensor_ids_joined
else:
mod_graph.sensor_ids_measurements = ''
mod_graph.width = form_mod_graph.width.data
mod_graph.height = form_mod_graph.height.data
mod_graph.x_axis_duration = form_mod_graph.xAxisDuration.data
mod_graph.refresh_duration = form_mod_graph.refreshDuration.data
mod_graph.enable_navbar = form_mod_graph.enableNavbar.data
mod_graph.enable_export = form_mod_graph.enableExport.data
mod_graph.enable_rangeselect = form_mod_graph.enableRangeSelect.data
db.session.commit()
except sqlalchemy.exc.OperationalError as except_msg:
error.append(except_msg)
except sqlalchemy.exc.IntegrityError as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('page_routes.page_graph'))
else:
flash_form_errors(form_mod_graph)
def graph_del(form_del_graph):
action = u'{action} {controller}'.format(
action=gettext(u"Delete"),
controller=gettext(u"Graph"))
error = []
if form_del_graph.validate():
try:
delete_entry_with_id(Graph,
form_del_graph.graph_id.data)
display_order = csv_to_list_of_int(DisplayOrder.query.first().graph)
display_order.remove(int(form_del_graph.graph_id.data))
DisplayOrder.query.first().graph = list_to_csv(display_order)
db.session.commit()
except Exception as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('page_routes.page_graph'))
else:
flash_form_errors(form_del_graph)
def graph_reorder(graph_id, display_order, direction):
action = u'{action} {controller}'.format(
action=gettext(u"Reorder"),
controller=gettext(u"Graph"))
error = []
try:
status, reord_list = reorder(display_order,
graph_id,
direction)
if status == 'success':
DisplayOrder.query.first().graph = ','.join(map(str, reord_list))
db.session.commit()
else:
error.append(reord_list)
except Exception as except_msg:
error.append(except_msg)
flash_success_errors(error, action, url_for('page_routes.page_graph'))