forked from kizniche/Mycodo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalembic_post.py
1284 lines (1154 loc) · 63.9 KB
/
alembic_post.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 -*-
#
# Script to be executed following an alembic update of the SQLite database
#
# Alembic is used to update the database schema. This script is used to
# execute code after all database schema updates have been performed, and
# typically involves database entry modifications.
#
# Note: Newest revision at the top
#
# The following code is also needed in the upgrade() function of the alembic
# upgrade script to indicate which section of this script to run. This should
# already be included in the alembic script template.
#
# import sys
# import os
# sys.path.append(os.path.abspath(os.path.join(__file__, "../../../..")))
# from alembic.alembic_post_utils import write_revision_post_alembic
# def upgrade():
# write_revision_post_alembic(revision)
#
import sys
import traceback
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "../..")))
from alembic_db.alembic_post_utils import read_revision_file
from mycodo.config import ALEMBIC_UPGRADE_POST
from mycodo.config import MYCODO_DB_PATH
from mycodo.databases.utils import session_scope
def upgrade_revision(error, revision):
"""Execute code following a database upgrade to the specified alembic revision."""
if not revision:
print("Error: Revision ID empty")
# elif revision == 'REPLACE_WITH_ALEMBIC_REVISION_ID':
# pass # Code goes here
elif revision == 'b354722c9b8b':
import json
import os
import shutil
import subprocess
import shlex
from sqlalchemy import and_
from mycodo.databases.models import Actions
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import OutputChannel
from mycodo.databases.models import Widget
from mycodo.config import INSTALL_DIRECTORY
# Delete and regenerate virtualenv (removes --system-site-packages)
try:
print("Deleting virtualenv...")
shutil.rmtree(os.path.join(INSTALL_DIRECTORY, 'env'))
except Exception as err:
print(f"Error removing env: {err}")
try:
print("Setting up virtualenv...")
command = f'/bin/bash {INSTALL_DIRECTORY}/mycodo/scripts/upgrade_commands.sh setup-virtualenv-full'
process = subprocess.Popen(shlex.split(command), shell=False, stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if process.poll() is not None:
break
if output:
print(output.strip().decode())
rc = process.poll()
except Exception as err:
print(f"Error setting up virtualenv: {err}")
with session_scope(MYCODO_DB_PATH) as session:
# Update output widget custom option format for output selection
widgets = session.query(Widget).filter(
Widget.graph_type == "widget_output").all()
for widget in widgets:
try:
custom_options = json.loads(widget.custom_options)
if "output" in custom_options:
device_id = custom_options["output"].split(",")[0]
channel_id = custom_options["output"].split(",")[2]
custom_options["output"] = "{},{}".format(device_id, channel_id)
widget.custom_options = json.dumps(custom_options)
session.commit()
except:
pass
# Refactor Action system to single-file modules
for action in session.query(Actions).all():
try:
custom_options = json.loads(action.custom_options)
except:
custom_options = {}
try:
if action.action_type == "pause_actions":
custom_options["duration"] = action.pause_duration
elif action.action_type == "flash_lcd_on":
action.action_type = "display_flash_on"
custom_options["controller"] = action.do_unique_id
elif action.action_type == "flash_lcd_off":
action.action_type = "display_flash_off"
custom_options["controller"] = action.do_unique_id
elif action.action_type == "lcd_backlight_on":
action.action_type = "display_backlight_on"
custom_options["controller"] = action.do_unique_id
elif action.action_type == "lcd_backlight_off":
action.action_type = "display_backlight_off"
custom_options["controller"] = action.do_unique_id
elif action.action_type == "lcd_backlight_color":
action.action_type = "display_backlight_color"
custom_options["controller"] = action.do_unique_id
custom_options["color"] = action.do_action_string
elif action.action_type == "resume_pid":
custom_options["controller"] = action.do_unique_id
elif action.action_type == "pause_pid":
custom_options["controller"] = action.do_unique_id
elif action.action_type == "activate_controller":
custom_options["controller"] = action.do_unique_id
elif action.action_type == "deactivate_controller":
custom_options["controller"] = action.do_unique_id
elif action.action_type == 'camera_timelapse_pause':
custom_options["controller"] = action.do_unique_id
elif action.action_type == 'camera_timelapse_resume':
custom_options["controller"] = action.do_unique_id
elif action.action_type == 'webhook':
custom_options["webhook"] = action.do_action_string
elif action.action_type == 'photo':
custom_options["controller"] = action.do_unique_id
elif action.action_type == 'photo_email':
custom_options["controller"] = action.do_unique_id
custom_options["email"] = action.do_action_string
elif action.action_type == 'method_pid':
custom_options["controller"] = action.do_unique_id
custom_options["method"] = action.do_action_string
elif action.action_type == 'setpoint_pid':
custom_options["controller"] = action.do_unique_id
try:
custom_options["setpoint"] = float(action.do_action_string)
except:
custom_options["setpoint"] = 0
elif action.action_type in ['setpoint_pid_raise', 'setpoint_pid_lower']:
custom_options["controller"] = action.do_unique_id
try:
custom_options["amount"] = float(action.do_action_string)
except:
custom_options["amount"] = 0
elif action.action_type == "command":
custom_options["user"] = action.do_output_state
custom_options["command"] = action.do_action_string
elif action.action_type == "create_note":
custom_options["tag"] = []
if action.do_action_string:
custom_options["tag"] = ["{},tag".format(action.do_action_string)]
elif action.action_type == "email":
custom_options["email"] = action.do_action_string
elif action.action_type == "email_multiple":
action.action_type = "email" # Convert email_multiple to email action
custom_options["email"] = action.do_action_string
elif action.action_type == "input_force_measurements":
if "," in action.do_unique_id:
custom_options["input"] = action.do_unique_id.split(',')[0]
elif action.action_type in ["output",
"output_pwm",
"output_volume",
"output_value",
"output_ramp_pwm"]:
custom_options["output"] = action.do_unique_id
if action.action_type == "output":
action.action_type = "output_on_off"
custom_options["state"] = action.do_output_state
custom_options["duration"] = action.do_output_duration
elif action.action_type == "output_pwm":
custom_options["duty_cycle"] = action.do_output_pwm
elif action.action_type == "output_volume":
custom_options["volume"] = action.do_output_amount
elif action.action_type == "output_value":
custom_options["value"] = action.do_output_amount
elif action.action_type == "output_ramp_pwm":
custom_options["duty_cycle_start"] = action.do_output_pwm
custom_options["duty_cycle_end"] = action.do_output_pwm2
custom_options["duty_cycle_increment"] = action.do_action_string
custom_options["duration"] = action.do_output_duration
elif action.action_type == "mqtt_publish":
pass # Already saved in custom_options as JSON
action.custom_options = json.dumps(custom_options)
session.commit()
except Exception as err:
print("Error parsing actions: {}".format(err))
elif revision == '6e394f2e8fec':
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import Input
from mycodo.databases.models import InputChannel
from mycodo.utils.inputs import parse_input_information
dict_inputs = parse_input_information()
with session_scope(MYCODO_DB_PATH) as session:
for each_input in session.query(Input).all():
if each_input.device == "ATLAS_EC":
# Check if only 1 channel exists
measurements = session.query(DeviceMeasurements).filter(
DeviceMeasurements.device_id == each_input.unique_id).count()
if measurements > 1:
continue
# Add missing measurements
if (each_input.device in dict_inputs and
'measurements_dict' in dict_inputs[each_input.device] and
dict_inputs[each_input.device]['measurements_dict']):
for each_channel in dict_inputs[each_input.device]['measurements_dict']:
if each_channel == 0:
continue # Channel 0 measurement already exists
measure_info = dict_inputs[each_input.device]['measurements_dict'][each_channel]
new_measurement = DeviceMeasurements()
if 'name' in measure_info:
new_measurement.name = measure_info['name']
new_measurement.device_id = each_input.unique_id
new_measurement.is_enabled = False
new_measurement.measurement = measure_info['measurement']
new_measurement.unit = measure_info['unit']
new_measurement.channel = each_channel
session.add(new_measurement)
session.commit()
elif revision == 'bdc03b708ac6':
from mycodo.databases.models import Input
from mycodo.databases.models import Output
from mycodo.databases.models import OutputChannel
from mycodo.databases.models import DisplayOrder
from mycodo.databases.models import CustomController
from mycodo.databases.models import Function
from mycodo.databases.models import Trigger
from mycodo.databases.models import PID
from mycodo.databases.models import Conditional
with session_scope(MYCODO_DB_PATH) as session:
display_order = session.query(DisplayOrder).first()
# Convert Function display order to positions
if display_order and "," in display_order.function:
position = 0
for each_id in display_order.function.split(","):
conditional = session.query(Conditional).filter(
Conditional.unique_id == each_id).first()
if conditional:
conditional.position_y = position
position += 1
pid = session.query(PID).filter(
PID.unique_id == each_id).first()
if pid:
pid.position_y = position
position += 1
trigger = session.query(Trigger).filter(
Trigger.unique_id == each_id).first()
if trigger:
trigger.position_y = position
position += 1
function = session.query(Function).filter(
Function.unique_id == each_id).first()
if function:
function.position_y = position
position += 1
custom = session.query(CustomController).filter(
CustomController.unique_id == each_id).first()
if custom:
custom.position_y = position
position += 1
session.commit()
# Convert Input display order to positions
if display_order and "," in display_order.inputs:
position = 0
for each_id in display_order.inputs.split(","):
input_dev = session.query(Input).filter(
Input.unique_id == each_id).first()
if input_dev:
input_dev.position_y = position
position += 1
session.commit()
# Convert Output display order to positions
if display_order and "," in display_order.output:
first = True
last_position = 0
last_size = 0
for each_id in display_order.output.split(","):
output = session.query(Output).filter(
Output.unique_id == each_id).first()
if output:
channels = session.query(OutputChannel).filter(
OutputChannel.output_id == output.unique_id).count()
if channels > 1:
output.size_y = channels + 1
else:
output.size_y = 2
if first:
output.position_y = 0
first = False
else:
output.position_y = last_position + last_size
last_position = output.position_y
last_size = output.size_y
session.commit()
elif revision == '110d2d00e91d':
from sqlalchemy import and_
from mycodo.databases.models import Conversion
with session_scope(MYCODO_DB_PATH) as session:
conv = session.query(Conversion).filter(
and_(Conversion.convert_unit_from == "kPa",
Conversion.convert_unit_to == "jPa")).first()
if conv:
session.delete(conv)
session.commit()
elif revision == 'cc7261a89a87':
# This version adds Input Channel Options
# We need to create Input channels and copy the measurement name to the new
# custom channel option for the MQTT and TTN Inputs.
import json
from sqlalchemy import and_
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import Input
from mycodo.databases.models import InputChannel
with session_scope(MYCODO_DB_PATH) as session:
for each_input in session.query(Input).all():
if each_input.device in ["MQTT_PAHO", "TTN_DATA_STORAGE"]:
for each_measure in session.query(DeviceMeasurements).filter(
DeviceMeasurements.device_id == each_input.unique_id).all():
# does Input Channel exist?
channel_exist = session.query(InputChannel).filter(and_(
InputChannel.input_id == each_input.unique_id,
InputChannel.channel == each_measure.channel)).first()
if not channel_exist:
new_channel = InputChannel()
new_channel.input_id = each_input.unique_id
new_channel.channel = each_measure.channel
if each_input.device == "MQTT_PAHO":
custom_options = {"subscribe_topic": each_measure.name}
elif each_input.device == "TTN_DATA_STORAGE":
custom_options = {"variable_name": each_measure.name}
new_channel.custom_options = json.dumps(custom_options)
session.add(new_channel)
elif revision == '313a6fb99082':
from mycodo.databases.models import Actions
with session_scope(MYCODO_DB_PATH) as session:
for each_action in session.query(Actions).all():
try:
if each_action.action_type == 'command' and not each_action.do_output_state:
# "pi" was the default prior to this update.
# The new default is "mycodo"
each_action.do_output_state = 'pi'
session.commit()
except Exception:
msg = "ERROR: Update Action {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
elif revision == '0e150fb8020b':
import json
from mycodo.databases.models import Actions
from mycodo.databases.models import Camera
from mycodo.databases.models import ConditionalConditions
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import Input
from mycodo.databases.models import Math
from mycodo.databases.models import Output
from mycodo.databases.models import OutputChannel
from mycodo.databases.models import PID
from mycodo.databases.models import Trigger
from mycodo.databases.models import Widget
from mycodo.utils.inputs import parse_input_information
with session_scope(MYCODO_DB_PATH) as session:
# Update Input custom_options
dict_inputs = parse_input_information()
for each_input in session.query(Input).all():
custom_options = {}
if 'custom_options' not in dict_inputs[each_input.device]:
continue
try:
for each_option_default in dict_inputs[each_input.device]['custom_options']:
try:
option_value = each_option_default['default_value']
if each_input.custom_options:
for each_option in each_input.custom_options.split(';'):
option = each_option.split(',')[0]
if option == each_option_default['id']:
option_value = each_option.split(',', 1)[1]
if each_option_default['type'] == 'integer':
custom_options[each_option_default['id']] = int(option_value)
elif each_option_default['type'] == 'float':
custom_options[each_option_default['id']] = float(option_value)
elif each_option_default['type'] == 'bool':
custom_options[each_option_default['id']] = bool(option_value)
elif each_option_default['type'] in ['multiline_text',
'text',
'select_measurement',
'select_device']:
custom_options[each_option_default['id']] = str(option_value)
elif each_option_default['type'] == 'select':
option_value = str(option_value)
if 'cast_value' in each_option_default and each_option_default['cast_value']:
if each_option_default['cast_value'] == 'integer':
option_value = int(option_value)
elif each_option_default['cast_value'] == 'float':
option_value = float(option_value)
custom_options[each_option_default['id']] = option_value
else:
print("Unknown custom_option type '{}'".format(each_option_default['type']))
except Exception:
print("Error parsing custom_options")
except Exception:
msg = "ERROR: Update Input {}: {}".format(revision, traceback.format_exc())
error.append(msg)
print(msg)
each_input.custom_options = json.dumps(custom_options)
session.commit()
# Update outputs
for each_output in session.query(Output).all():
try:
custom_options = {
'pin': each_output.pin,
'amps': each_output.amps,
'protocol': each_output.protocol,
'pulse_length': each_output.pulse_length,
'linux_command_user': each_output.linux_command_user,
'on_command': each_output.on_command,
'off_command': each_output.off_command,
'pwm_command': each_output.pwm_command,
'force_command': each_output.force_command,
'trigger_functions_at_start': each_output.trigger_functions_at_start,
'startup_value': each_output.startup_value,
'shutdown_value': each_output.shutdown_value,
'pwm_hertz': each_output.pwm_hertz,
'pwm_library': each_output.pwm_library,
'pwm_invert_signal': each_output.pwm_invert_signal,
'flow_mode': each_output.output_mode,
'flow_rate': each_output.flow_rate,
'state_startup': each_output.state_startup,
'state_shutdown': each_output.state_shutdown
}
try:
custom_options['state_startup'] = int(each_output.state_startup)
except:
pass
try:
custom_options['state_shutdown'] = int(each_output.state_shutdown)
except:
pass
try:
custom_options['on_state'] = int(each_output.on_state)
except:
pass
# Add any custom options already present
if each_output.custom_options and "," in each_output.custom_options:
for each_set in each_output.custom_options.split(";"):
if len(each_set.split(",")) > 1:
key = each_set.split(",")[0]
value = each_set.split(",")[1]
if key in ['port', 'keepalive']:
value = int(value)
custom_options[key] = value
if each_output.output_type in ["python",
"command",
"wireless_rpi_rf",
"MQTT_PAHO"]:
try:
custom_options['state_startup'] = int(each_output.state_startup)
custom_options['state_shutdown'] = int(each_output.state_shutdown)
except:
pass
new_channel = OutputChannel()
new_channel.output_id = each_output.unique_id
new_channel.channel = 0
new_channel.custom_options = json.dumps(custom_options)
session.add(new_channel)
each_output.custom_options = ''
session.commit()
except Exception:
msg = "ERROR: Update Output {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Math outputs
for each_math in session.query(Math).all():
try:
if (each_math.math_type in ['average',
'difference',
'redundancy',
'statistics',
'sum',
'verification'] and
each_math.inputs):
selections = each_math.inputs.split(";")
new_list = []
for each_selection in selections:
if "," in each_selection:
output_id = each_selection.split(",")[0]
output = session.query(Output).filter(Output.unique_id == output_id).first()
if output:
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
new_list.append("{},{}".format(output_id, output_channel.unique_id))
else:
new_list.append(each_selection)
each_math.inputs = ";".join(new_list)
elif (each_math.math_type in ['average_single',
'sum_single'] and
each_math.inputs):
output_id = each_math.inputs.split(",")[0]
output = session.query(Output).filter(Output.unique_id == output_id).first()
if output:
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_math.inputs = "{},{}".format(output_id, output_channel.unique_id)
session.commit()
except Exception:
msg = "ERROR: Update Math {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update PID outputs
for each_pid in session.query(PID).all():
try:
if each_pid.raise_output_id:
output_id = each_pid.raise_output_id
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_pid.raise_output_id = "{},{}".format(output_id, output_channel.unique_id)
if each_pid.lower_output_id:
output_id = each_pid.lower_output_id
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_pid.lower_output_id = "{},{}".format(output_id, output_channel.unique_id)
session.commit()
except Exception:
msg = "ERROR: Update PID {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Trigger outputs
for each_trigger in session.query(Trigger).all():
try:
if (each_trigger.trigger_type in ['trigger_output',
'trigger_output_pwm'] and
each_trigger.unique_id_1):
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == each_trigger.unique_id_1).first()
each_trigger.unique_id_2 = output_channel.unique_id
elif (each_trigger.trigger_type == 'trigger_run_pwm_method' and
each_trigger.unique_id_2):
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == each_trigger.unique_id_2).first()
each_trigger.unique_id_3 = output_channel.unique_id
session.commit()
except Exception:
msg = "ERROR: Update Trigger {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Function Action outputs
for each_action in session.query(Actions).all():
try:
if each_action.action_type in ['output',
'output_pwm',
'output_ramp_pwm',
'output_volume']:
output_id = each_action.do_unique_id
output = session.query(Output).filter(
Output.unique_id == output_id).first()
if not output:
continue
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_action.do_unique_id = "{},{}".format(output_id, output_channel.unique_id)
session.commit()
except Exception:
msg = "ERROR: Update Action {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Conditional Condition outputs
for each_cond in session.query(ConditionalConditions).all():
try:
if each_cond.condition_type in ['output_state',
'output_duration_on']:
output_id = each_cond.output_id
output = session.query(Output).filter(
Output.unique_id == output_id).first()
if not output:
continue
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_cond.output_id = "{},{}".format(output_id, output_channel.unique_id)
session.commit()
except Exception:
msg = "ERROR: Update Condition {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Widget outputs
for each_widget in session.query(Widget).all():
try:
custom_options = json.loads(each_widget.custom_options)
if each_widget.graph_type in ["widget_output",
"widget_output_pwm_slider",
"widget_measurement",
"widget_indicator"]:
if each_widget.graph_type in ["widget_output",
"widget_output_pwm_slider"]:
option_name = "output"
elif each_widget.graph_type in ["widget_measurement",
"widget_indicator"]:
option_name = "measurement"
if custom_options[option_name] and "," in custom_options[option_name]:
output_id = custom_options[option_name].split(",")[0]
output = session.query(Output).filter(
Output.unique_id == output_id).first()
if not output:
continue
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
measurement = session.query(DeviceMeasurements).filter(
DeviceMeasurements.device_id == output_id).first()
custom_options[option_name] = "{},{},{}".format(
output_id, measurement.unique_id, output_channel.unique_id)
each_widget.custom_options = json.dumps(custom_options)
session.commit()
except Exception:
msg = "ERROR: Update Widget {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Camera outputs
for each_camera in session.query(Camera).all():
try:
output_id = each_camera.output_id
output = session.query(Output).filter(
Output.unique_id == output_id).first()
if not output:
continue
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_camera.output_id = "{},{}".format(output_id, output_channel.unique_id)
session.commit()
except Exception:
msg = "ERROR: Update Camera {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
# Update Input outputs
for each_input in session.query(Input).all():
try:
output_id = each_input.pre_output_id
output = session.query(Output).filter(
Output.unique_id == output_id).first()
if not output:
continue
output_channel = session.query(OutputChannel).filter(
OutputChannel.output_id == output_id).first()
each_input.pre_output_id = "{},{}".format(output_id, output_channel.unique_id)
session.commit()
except Exception:
msg = "ERROR: Update Input {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
elif revision == 'd66e33093e8e':
# convert database entries to JSON string for custom_options entry
import json
from mycodo.databases.models import Widget
with session_scope(MYCODO_DB_PATH) as session:
for each_widget in session.query(Widget).all():
custom_options = {
'refresh_seconds': each_widget.refresh_duration,
'x_axis_minutes': each_widget.x_axis_duration,
'decimal_places': each_widget.decimal_places,
'enable_status': each_widget.enable_status,
'enable_value': each_widget.enable_value,
'enable_name': each_widget.enable_name,
'enable_unit': each_widget.enable_unit,
'enable_measurement': each_widget.enable_measurement,
'enable_channel': each_widget.enable_channel,
'enable_timestamp': each_widget.enable_timestamp,
'enable_navbar': each_widget.enable_navbar,
'enable_rangeselect': each_widget.enable_rangeselect,
'enable_export': each_widget.enable_export,
'enable_title': each_widget.enable_title,
'enable_auto_refresh': each_widget.enable_auto_refresh,
'enable_xaxis_reset': each_widget.enable_xaxis_reset,
'enable_manual_y_axis': each_widget.enable_manual_y_axis,
'enable_start_on_tick': each_widget.enable_start_on_tick,
'enable_end_on_tick': each_widget.enable_end_on_tick,
'enable_align_ticks': each_widget.enable_align_ticks,
'use_custom_colors': each_widget.use_custom_colors,
'max_measure_age': each_widget.max_measure_age,
'stops': each_widget.stops,
'min': each_widget.y_axis_min,
'max': each_widget.y_axis_max,
'option_invert': each_widget.option_invert,
'font_em_name': each_widget.font_em_name,
'font_em_value': each_widget.font_em_value,
'font_em_timestamp': each_widget.font_em_timestamp,
'enable_output_controls': each_widget.enable_output_controls,
'show_pid_info': each_widget.show_pid_info,
'show_set_setpoint': each_widget.show_set_setpoint,
'camera_id': each_widget.camera_id,
'camera_image_type': each_widget.camera_image_type,
'max_age': each_widget.camera_max_age
}
try:
custom_options['custom_yaxes'] = each_widget.math_ids.split(";")
custom_options['custom_colors'] = each_widget.math_ids.split(",")
custom_options['range_colors'] = each_widget.math_ids.split(";")
custom_options['disable_data_grouping'] = each_widget.math_ids.split(",")
except:
pass
if each_widget.graph_type == 'graph':
each_widget.graph_type = 'widget_graph_synchronous'
try:
custom_options['measurements_math'] = each_widget.math_ids.split(";")
custom_options['measurements_note_tag'] = each_widget.note_tag_ids.split(";")
custom_options['measurements_input'] = each_widget.input_ids_measurements.split(";")
custom_options['measurements_output'] = each_widget.output_ids.split(";")
custom_options['measurements_pid'] = each_widget.pid_ids.split(";")
except:
pass
elif each_widget.graph_type == 'spacer':
each_widget.graph_type = 'widget_spacer'
elif each_widget.graph_type == 'gauge_angular':
each_widget.graph_type = 'widget_gauge_angular'
custom_options['measurement'] = each_widget.input_ids_measurements
elif each_widget.graph_type == 'gauge_solid':
each_widget.graph_type = 'widget_gauge_solid'
custom_options['measurement'] = each_widget.input_ids_measurements
elif each_widget.graph_type == 'indicator':
each_widget.graph_type = 'widget_indicator'
custom_options['measurement'] = each_widget.input_ids_measurements
elif each_widget.graph_type == 'measurement':
each_widget.graph_type = 'widget_measurement'
custom_options['measurement'] = each_widget.input_ids_measurements
elif each_widget.graph_type == 'output':
each_widget.graph_type = 'widget_output'
custom_options['output'] = each_widget.output_ids
elif each_widget.graph_type == 'output_pwm_slider':
each_widget.graph_type = 'widget_output_pwm_slider'
custom_options['output'] = each_widget.output_ids
elif each_widget.graph_type == 'pid_control':
each_widget.graph_type = 'widget_pid'
custom_options['pid'] = each_widget.pid_ids
elif each_widget.graph_type == 'camera':
each_widget.graph_type = 'widget_camera'
each_widget.custom_options = json.dumps(custom_options)
session.commit()
elif revision == '4d3258ef5864':
# The post-script for 4ea0a59dee2b didn't work to change minute to sec
# This one works
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import Output
with session_scope(MYCODO_DB_PATH) as session:
for each_output in session.query(Output).all():
if each_output.output_type == 'atlas_ezo_pmp':
measurements = session.query(DeviceMeasurements).filter(
DeviceMeasurements.device_id == each_output.unique_id).all()
for meas in measurements:
if meas.unit == 'minute':
meas.unit = 's'
session.commit()
elif revision == '4ea0a59dee2b':
# Only LCDs with I2C interface were supported until this revision.
# "interface" column added in this revision.
# Sets all current interfaces to I2C.
# Atlas Scientific pump output duration measurements are set to minute.
# Change unit minute to the SI unit second, like other outputs.
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import LCD
from mycodo.databases.models import Output
with session_scope(MYCODO_DB_PATH) as session:
for meas in session.query(DeviceMeasurements).all():
if meas.measurement == 'acceleration_g_force':
meas.measurement = 'acceleration'
elif meas.measurement == 'acceleration_x_g_force':
meas.measurement = 'acceleration_x'
elif meas.measurement == 'acceleration_y_g_force':
meas.measurement = 'acceleration_y'
elif meas.measurement == 'acceleration_z_g_force':
meas.measurement = 'acceleration_z'
session.commit()
outputs = session.query(Output).filter(
Output.output_type == 'atlas_ezo_pmp').all()
for each_output in outputs:
measurements = session.query(DeviceMeasurements).filter(
DeviceMeasurements.device_id == each_output.unique_id).all()
for meas in measurements:
if meas.unit == 'minute':
meas.unit = 's'
session.commit()
for lcd in session.query(LCD).all():
lcd.interface = 'I2C'
session.commit()
elif revision == 'af5891792291':
# Set the output_type for PID controller outputs
from mycodo.utils.outputs import parse_output_information
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import Output
from mycodo.databases.models import PID
dict_outputs = parse_output_information()
with session_scope(MYCODO_DB_PATH) as session:
for each_pid in session.query(PID).all():
try:
new_measurement = DeviceMeasurements()
new_measurement.name = "Output (Volume)"
new_measurement.device_id = each_pid.unique_id
new_measurement.measurement = 'volume'
new_measurement.unit = 'ml'
new_measurement.channel = 8
session.add(new_measurement)
if each_pid.raise_output_id:
output_raise = session.query(Output).filter(
Output.unique_id == each_pid.raise_output_id).first()
if output_raise: # Use first output type listed (default)
each_pid.raise_output_type = dict_outputs[output_raise.output_type]['output_types'][0]
if each_pid.lower_output_id:
output_lower = session.query(Output).filter(
Output.unique_id == each_pid.lower_output_id).first()
if output_lower: # Use first output type listed (default)
each_pid.lower_output_type = dict_outputs[output_lower.output_type]['output_types'][0]
session.commit()
except:
msg = "ERROR-1: post-alembic revision {}: {}".format(
revision, traceback.format_exc())
error.append(msg)
print(msg)
elif revision == '561621f634cb':
from mycodo.databases.models import DeviceMeasurements
from mycodo.databases.models import Output
from mycodo.utils.outputs import parse_output_information
dict_outputs = parse_output_information()
with session_scope(MYCODO_DB_PATH) as session:
for each_output in session.query(Output).all():
if not session.query(DeviceMeasurements).filter(
DeviceMeasurements.device_id == each_output.unique_id).first():
# No output device measurements exist. Need to create them.
if ('measurements_dict' in dict_outputs[each_output.output_type] and
dict_outputs[each_output.output_type]['measurements_dict'] != []):
for each_channel in dict_outputs[each_output.output_type]['measurements_dict']:
measure_info = dict_outputs[each_output.output_type]['measurements_dict'][each_channel]
new_measurement = DeviceMeasurements()
if 'name' in measure_info:
new_measurement.name = measure_info['name']
new_measurement.device_id = each_output.unique_id
new_measurement.measurement = measure_info['measurement']
new_measurement.unit = measure_info['unit']
new_measurement.channel = each_channel
session.add(new_measurement)
session.commit()
elif revision == '61a0d0568d24':
from mycodo.databases.models import Role
with session_scope(MYCODO_DB_PATH) as session:
for role in session.query(Role).all():
if role.name in ['Kiosk', 'Guest']:
role.reset_password = False
else:
role.reset_password = True
session.commit()
elif revision == 'f5b77ef5f17c':
from mycodo.databases.models import SMTP
with session_scope(MYCODO_DB_PATH) as session:
for smtp in session.query(SMTP).all():
error = []
if smtp.ssl:
smtp.protocol = 'ssl'
if smtp.port == 465:
smtp.port = None
elif not smtp.ssl:
smtp.protocol = 'tls'
if smtp.port == 587:
smtp.port = None
else:
smtp.protocol = 'unencrypted'
if not error:
session.commit()
else:
for each_error in error:
print("Error: {}".format(each_error))
elif revision == '0a8a5eb1be4b':
from mycodo.databases.models import Input
with session_scope(MYCODO_DB_PATH) as session:
for each_input in session.query(Input).all():
error = []
if each_input.device == 'DS18B20' and 'library,ow_shell' in each_input.custom_options:
each_input.device = 'DS18B20_OWS'
each_input.custom_options = ''
if not error:
session.commit()
else:
for each_error in error:
print("Error: {}".format(each_error))
elif revision == '55aca47c2362':
from mycodo.databases.models import Widget
from mycodo.databases.models import Dashboard
with session_scope(MYCODO_DB_PATH) as session:
new_dash = Dashboard()
new_dash.name = 'Default Dashboard'
session.add(new_dash)
for each_widget in session.query(Widget).all():
each_widget.dashboard_id = new_dash.unique_id
session.commit()
if not error:
session.commit()
else:
for each_error in error:
print("Error: {}".format(each_error))
elif revision == '895ddcdef4ce':
# Add PID setpoint_tracking_type and setpoint_tracking_id
# If method_id set, set setpoint_tracking_type to 'method;
# and copy method_id to new setpoint_tracking_id.
# PID.method_id deleted after executing this code.
from mycodo.databases.models import PID
with session_scope(MYCODO_DB_PATH) as session:
for each_pid in session.query(PID).all():
error = []
if each_pid.setpoint_tracking_id:
each_pid.setpoint_tracking_type = 'method'