-
Notifications
You must be signed in to change notification settings - Fork 2
/
irrigation_ctrl_startup.py
executable file
·1478 lines (1128 loc) · 62.4 KB
/
irrigation_ctrl_startup.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
import datetime
import time
import string
import urllib2
import math
import redis
import json
import eto
import py_cf
import os
import base64
import load_files
import watch_dog
class SprinklerQueueElementControl( ):
def __init__(self,redis,io_control,alarm_queue,counter_devices):
self.redis = redis
self.alarm_queue = alarm_queue
self.io_control = io_control
self.counter_devices = counter_devices
self.app_files = load_files.APP_FILES(redis)
self.redis.hset("CONTROL_VARIBALES","MAX_FLOW_TIME",0)
def check_for_excessive_flow_rate( self,*args ):
flow_value = float( check_redis_value( "global_flow_sensor_corrected" ) )
max_flow = float( check_redis_value( "FLOW_CUT_OFF"))
if max_flow == 0:
return # feature is not turned on
compact_data = self.redis.lindex( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE",0 )
json_string = base64.b64decode(compact_data)
json_object = json.loads(json_string)
run_time = int( json_object["run_time"])
elasped_time = int(json_object["elasped_time"])
schedule_step = int(json_object["step"])
step_number = json_object["step"]
schedule_name = json_object["schedule_name"]
if elasped_time < 3 :
return # let flow stabilize
if flow_value > max_flow:
over_load_time = int(self.redis.hget("CONTROL_VARIBALES","MAX_FLOW_TIME")) +1
if over_load_time > 2:
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","ON")
self.alarm_queue.store_past_action_queue("IRRIGATION:FLOW_ABORT","RED", { "schedule_name":json_object["schedule_name"],"step_number":json_object["step"],
"flow_value":flow_value,"max_flow":max_flow } )
self.redis.hset("CONTROL_VARIBALES","MAX_FLOW_TIME",0)
else:
self.redis.hset("CONTROL_VARIBALES","MAX_FLOW_TIME",over_load_time)
else:
self.redis.hset("CONTROL_VARIBALES","MAX_FLOW_TIME",0)
def check_redis_value( self,key):
value = redis.hget( "CONTROL_VARIABLES",key )
if value == None:
value = 0
return value
def check_current(self,*args):
compact_data = self.redis.lindex( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE",0 )
json_string = base64.b64decode(compact_data)
#print "json_string",json_string
json_object = json.loads(json_string)
temp = float( self.redis.hget( "CONTROL_VARIABLES","coil_current" ))
print "check_current temp",temp
if temp > 24:
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","ON")
self.clean_up_irrigation_cell( json_object )
self.alarm_queue.store_past_action_queue("IRRIGATION:CURRENT_ABORT","RED", { "schedule_name":json_object["schedule_name"],"step_number":json_object["step"] } )
return "RESET"
else:
return "DISABLE"
def start(self, *args ):
#print "start ------------------------------------------------->"
self.redis.hset("CONTROL_VARIBALES","MAX_FLOW_TIME",0)
compact_data = self.redis.lindex( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE",0 )
json_string = base64.b64decode(compact_data)
json_object = json.loads(json_string)
if self.check_redis_value("SUSPEND") == "ON":
#self.log_start_step( schedule_name, json_object["step"])
#self.io_control.turn_off_io(json_object["io_setup"])
#self.io_control.disable_all_sprinklers()
return # System is not processing commands right now
#print "start --- #1"
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","OFF")
#print "made it here"
run_time = int( json_object["run_time"])
elasped_time = int(json_object["elasped_time"])
schedule_step = int(json_object["step"])
step_number = json_object["step"]
schedule_name = json_object["schedule_name"]
#print "run_time",run_time
if json_object["eto_enable"] == True:
run_time = self.eto_update( run_time , json_object["io_setup"] )
#print "start ---#2 runtime",run_time
if run_time == 0:
self.clean_up_irrigation_cell(json_object)
json_object["run_time"] = 0
self.alarm_queue.store_past_action_queue("IRRIGATION:START:ETO_RESTRICTION","YELLOW", json_object )
return "RESET"
self.io_control.load_duration_counters( run_time )
#print "made it here"
self.io_control.turn_on_master_valves()
self.io_control.turn_on_io( json_object["io_setup"] )
station_by_pass = 0
elasped_time = 1
self.redis.hset( "CONTROL_VARIABLES","sprinkler_ctrl_mode","AUTO")
self.redis.hset( "CONTROL_VARIABLES","schedule_name", schedule_name )
self.redis.hset( "CONTROL_VARIABLES","schedule_step_number", step_number )
self.redis.hset( "CONTROL_VARIABLES","schedule_step", schedule_step )
self.redis.hset( "CONTROL_VARIABLES","schedule_time_count", elasped_time )
self.redis.hset( "CONTROL_VARIABLES","schedule_time_max", run_time )
self.log_start_step( schedule_name, json_object["step"])
#print "current_log",self.current_log_object
#print "flow_log", self.flow_log_object
json_object["elasped_time"] = elasped_time
json_object["run_time"] = run_time
json_string = json.dumps( json_object )
compact_data = base64.b64encode(json_string)
#print "start #end json string ",json_string
self.redis.lset( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE", 0, compact_data )
return "DISABLE"
def monitor( self, *args ):
#print "monitor --------------->"
# check to see if something is in the queue
length = self.redis.llen( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE" )
#print "length",length
if length == 0 :
return "CONTINUE"
compact_data = self.redis.lindex( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE",0 )
json_string = base64.b64decode(compact_data)
json_object = json.loads(json_string)
run_time = int( json_object["run_time"])
elasped_time = int(json_object["elasped_time"])
schedule_step = int(json_object["step"])
step_number = json_object["step"]
schedule_name = json_object["schedule_name"]
if (self.check_redis_value("SUSPEND") == "ON") :
#self.io_control.turn_off_io(json_object["io_setup"])
#self.io_control.disable_all_sprinklers()
return "HALT" # System is not processing commands right now
elasped_time = elasped_time +1
self.log_sensors( schedule_name, schedule_step)
if json_object["eto_enable"] == True:
self.update_eto_queue_a( 1, json_object["io_setup"] )
if (elasped_time <= run_time ) and ( self.check_redis_value("SKIP_STATION") != "ON" ):
self.io_control.turn_on_io( json_object["io_setup"] )
self.io_control.turn_on_master_valves()
self.redis.hset( "CONTROL_VARIABLES","schedule_time_count", elasped_time )
json_object["elasped_time"] = elasped_time
json_string = json.dumps( json_object )
compact_data = base64.b64encode(json_string)
self.redis.lset( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE", 0, compact_data )
return_value = "RESET"
else:
#print "normal end"
self.log_step_stop()
self.clean_up_irrigation_cell(json_object)
return_value = "DISABLE"
#print "cell returnValue is ",return_value
return return_value
def clean_up_irrigation_cell( self ,json_object ):
#print "made it to cleanup"
self.redis.delete("QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE")
self.redis.hset("CONTROL_VARIABLES", "schedule_name","offline" )
self.redis.hset("CONTROL_VARIABLES", "schedule_step_number",0 )
self.redis.hset("CONTROL_VARIABLES", "schedule_step",0 )
self.redis.hset("CONTROL_VARIABLES", "schedule_time_count",0 )
self.redis.hset( "CONTROL_VARIABLES","schedule_time_max",0 )
self.redis.hset( "CONTROL_VARIABLES","sprinkler_ctrl_mode","AUTO")
self.redis.hset( "CONTROL_VARIABLES","SKIP_STATION","OFF")
self.io_control.turn_off_io(json_object["io_setup"])
self.io_control.disable_all_sprinklers()
self.io_control.clear_duration_counters()
self.io_control.turn_off_master_valves()
def log_sensors(self, schedule_name,step):
if hasattr(self, 'current_log_object') == False:
self.current_log_object = self.initialize_object( "current_log",schedule_name,step)
if hasattr(self, 'flow_log_object') == False:
self.flow_log_object = self.initialize_object( "flow_log",schedule_name,step )
coil_current = float( self.redis.hget( "CONTROL_VARIABLES","coil_current" ))
self.log_coil_current ( coil_current )
for i in self.counter_devices.keys():
sensor_name = i
flow_value = self.redis.lindex("QUEUES:SPRINKLER:FLOW:"+str(i),0)
self.log_flow_rate( sensor_name, flow_value )
def log_flow_rate( self, sensor_name, flow_value ):
if self.flow_log_object["fields"].has_key( sensor_name ) == False:
self.initialize_field( self.flow_log_object, sensor_name )
temp = self.flow_log_object["fields"][ sensor_name ]
temp["count"] = temp["count"]+1
temp["data"].append( flow_value)
if flow_value > temp["max"] :
temp["max"] = flow_value
if flow_value < temp["min"] :
temp["min"] = flow_value
def log_coil_current ( self,coil_current ):
if self.current_log_object["fields"].has_key( "coil_current" ) == False:
self.initialize_field( self.current_log_object, "coil_current")
temp = self.current_log_object["fields"]["coil_current"]
temp["count"] = temp["count"]+1
temp["data"].append( coil_current )
if coil_current > temp["max"] :
temp["max"] = coil_current
if coil_current < temp["min"] :
temp["min"] = coil_current
def log_start_step( self, schedule_name, step):
#print "made it log start step"
self.current_log_object = self.initialize_object( "current_log",schedule_name,step)
self.flow_log_object = self.initialize_object( "flow_log",schedule_name,step )
self.alarm_queue.store_event_queue( "start_step", { "schedule":schedule_name, "step":step } )
def log_step_stop( self ):
if hasattr(self, 'flow_log_object') == False:
return # case when eto abort
obj = self.flow_log_object
self.alarm_queue.store_past_action_queue("IRRIGATION:END","GREEN", { "schedule_name":obj["schedule_name"],"step_name":obj["step"] } )
self.store_object( self.current_log_object, "coil" )
self.store_object( self.flow_log_object, "flow" )
obj = {}
obj["coil"] = self.current_log_object
obj["flow"] = self.flow_log_object
self.alarm_queue.store_event_queue( "irrigatation_store_object", obj )
self.current_log_object = None
self.flow_log_object = None
def store_object( self, obj ,queue_type ):
if obj == None:
return
#self.add_limits(obj, queue_type )
self.compute_object_statistics( obj )
queue = "log_data:"+queue_type+":"+obj["schedule_name"]+":"+str(obj["step"])
json_string = json.dumps(obj)
compact_data = base64.b64encode(json_string)
self.redis.lpush( queue, json_string )
self.redis.ltrim( queue,0,100)
def initialize_object( self, name,schedule_name,step ):
obj = {}
obj["name"] = name
obj["time"] = time.time()
obj["schedule_name"] = schedule_name
obj["step"] = step
obj["fields"] = {}
return obj
def initialize_field( self, obj ,field):
if obj["fields"].has_key(field) == False:
obj["fields"][field] = {}
obj["fields"][field]["max"] = -1000000
obj["fields"][field]["min"] = 1000000
obj["fields"][field]["count"] = 0
obj["fields"][field]["data"] = []
def compute_object_statistics( self, obj ):
#print "compute object statistics", obj
for j in obj["fields"] :
temp = obj["fields"][j]
temp["total"] = 0
count = 0
for m in temp["data"]:
m = float(m)
count = count +1
if count > 5:
temp["total"] = temp["total"] + m
#print "count ",count
if count > 5:
temp["average"] = temp["total"]/(count -5)
else:
temp["average"] = 0
temp["std"] = 0
count = 0
for m in temp["data"]:
m = float(m)
count = count +1
if count > 5 :
temp["std"] = temp["std"] + (m -temp["average"])*(m-temp["average"])
temp["std"] = math.sqrt(temp["std"]/(count-5))
else:
temp["std"] = 0
## 1 gallon is 0.133681 ft3
## assuming a 5 foot radius
## a 12 gallon/hour head 0.2450996343 inch/hour
## a 14 gallon/hour head 0.2859495733 inch/hour
## a 16 gallon/hour head 0.3267995123 inch/hour
##
##
##
##
## capacity of soil
## for silt 2 feet recharge rate 30 % recharge inches -- .13 * 24 *.3 = .936 inch
## for sand 1 feet recharge rate 30 % recharge inches -- .06 * 12 *.3 = .216 inch
##
## recharge rate for is as follows for 12 gallon/hour head:
## sand 1 feet .216/.245 which is 52 minutes
## silt 2 feet recharge rate is 3.820 hours or 229 minutes
##
## {"controller":"satellite_1", "pin": 9, "recharge_eto": 0.216, "recharge_rate":0.245 },
## eto_site_data
def eto_update( self, schedule_run_time, io_list ):
self.eto_site_data = self.app_files.load_file( "eto_site_setup.json" )
manage_eto = self.redis.hget( "CONTROL_VARIABLES","ETO_MANAGE_FLAG" )
if manage_eto == None:
manage_eto = 1
self.redis.hset("CONTROL_VARIABLES", "ETO_MANAGE_FLAG",manage_eto)
manage_eto = int( manage_eto )
if manage_eto == 1:
sensor_list = self.find_queue_names( io_list )
if len(sensor_list) != 0:
run_time = self.find_largest_runtime( schedule_run_time, sensor_list )
if run_time < schedule_run_time :
schedule_run_time = run_time
return schedule_run_time
def find_queue_names( self, io_list ):
eto_values = []
for j in io_list:
controller = j["remote"]
bits = j["bits"]
bit = bits[0]
index = 0
for m in self.eto_site_data:
if (m["controller"] == controller) and (m["pin"] == bit):
queue_name = controller+"|"+str(bit)
data = self.redis.hget( "ETO_RESOURCE", queue_name )
eto_values.append( [index, data, queue_name ] )
index = index +1
#print "eto values ",eto_values
return eto_values
def find_largest_runtime( self, run_time, sensor_list ):
runtime = 0
for j in sensor_list:
index = j[0]
deficient = float(j[1])
eto_temp = self.eto_site_data[index]
recharge_eto = float( eto_temp["recharge_eto"] )
recharge_rate = float(eto_temp["recharge_rate"])
if float(deficient) > recharge_eto :
runtime_temp = (deficient /recharge_rate)*60
if runtime_temp > runtime :
runtime = runtime_temp
#print "run time",runtime
return runtime
def update_eto_queue_a( self, run_time, io_list ):
self.eto_site_data = self.app_files.load_file( "eto_site_setup.json" )
manage_eto = self.redis.hget( "CONTROL_VARIABLES","ETO_MANAGE_FLAG" )
if manage_eto == None:
manage_eto = 1
self.redis.hset( "CONTROL_VARIABLES","ETO_MANAGE_FLAG",manage_eto)
manage_eto = int( manage_eto )
if manage_eto == 1:
sensor_list = self.find_queue_names( io_list )
if len(sensor_list) != 0:
self.update_eto_queue(run_time,sensor_list)
def update_eto_queue( self, run_time, sensor_list ):
for l in sensor_list:
j_index = l[0]
queue_name = l[2]
j = self.eto_site_data[ j_index ]
deficient = self.redis.hget("ETO_RESOURCE", queue_name )
if deficient == None:
deficient = 0
else:
deficient = float(deficient)
recharge_rate = float(j["recharge_rate"])
deficient = deficient - (recharge_rate/60)*run_time
if deficient < 0 :
deficient = 0
self.redis.hset( "ETO_RESOURCE", queue_name, deficient )
class SprinklerQueueControl():
def __init__(self,alarm_queue,redis):
self.alarm_queue = alarm_queue
self.redis = redis
#
# This function takes data from the IRRIGATION QUEUE And Transferrs it to the IRRIGATION_CELL_QUEUE
# IRRIGATION_CELL_QUEUE only has one element in it
#
def load_irrigation_cell(self,chainFlowHandle, chainObj, parameters,event ):
#print "load irrigation cell ######################################################################"
## if queue is empty the return
## this is for resuming an operation
length = self.redis.llen("QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE" )
#print "made it here cell ", length
if length > 0:
return "RESET"
length = self.redis.llen("QUEUES:SPRINKLER:IRRIGATION_QUEUE")
#print "length queue ",length
if length == 0:
return "RESET"
if self.redis.hget("CONTROL_VARIABLES","SUSPEND") == "ON":
return "RESET"
compact_data = self.redis.rpop( "QUEUES:SPRINKLER:IRRIGATION_QUEUE" )
json_string = base64.b64decode(compact_data)
json_object = json.loads(json_string)
if json_object["type"] == "RESISTANCE_CHECK":
chainFlowHandle.enable_chain_base( ["resistance_check"])
self.redis.hset("CONTROL_VARIABLES","SUSPEND","ON")
return "RESET"
if json_object["type"] == "CHECK_OFF":
chainFlowHandle.enable_chain_base( ["check_off_chain"])
self.redis.hset("CONTROL_VARIABLES","SUSPEND","ON")
return "RESET"
if json_object["type"] == "CLEAN_FILTER":
chainFlowHandle.enable_chain_base( ["clean_filter_action_chain"])
self.redis.hset("CONTROL_VARIABLES","SUSPEND","ON")
return "RESET"
if json_object["type"] == "IRRIGATION_STEP":
#print "irrigation step"
self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE", compact_data )
'''
if json_object["type"] == "START_SCHEDULE" :
self.redis.set( "schedule_step_number", json_object["step_number"] )
self.store_event_queue( "irrigation_schedule_start", json_object )
if json_object["type"] == "END_SCHEDULE" :
self.store_event_queue( "irrigation_schedule_stop", json_object )
'''
#print "load irrigation cell CONTINUE"
return "DISABLE"
class SprinklerControl():
def __init__(self, irrigation_control,alarm_queue,redis):
self.irrigation_control = irrigation_control
self.alarm_queue = alarm_queue
self.redis = redis
self.commands = {}
self.commands["OFFLINE"] = self.go_offline
self.commands["QUEUE_SCHEDULE"] = self.queue_schedule
self.commands["QUEUE_SCHEDULE_STEP"] = self.queue_schedule_step
self.commands["QUEUE_SCHEDULE_STEP_TIME"] = self.queue_schedule_step_time
self.commands["RESTART_PROGRAM"] = self.restart_program #tested
self.commands["NATIVE_SCHEDULE"] = self.queue_schedule_step_time
self.commands["NATIVE_SPRINKLER"] = self.direct_valve_control
self.commands["CLEAN_FILTER"] = self.clean_filter #tested
self.commands["OPEN_MASTER_VALVE"] = self.open_master_valve #tested
self.commands["CLOSE_MASTER_VALVE"] = self.close_master_valve #tested
self.commands["RESET_SYSTEM"] = self.reset_system #tested
self.commands["CHECK_OFF"] = self.check_off #tested
self.commands["SUSPEND"] = self.suspend #tested
self.commands["RESUME" ] = self.resume #tested
self.commands["SKIP_STATION"] = self.skip_station
self.commands["RESISTANCE_CHECK"] = self.resistance_check
self.app_files = load_files.APP_FILES(redis)
def dispatch_sprinkler_mode(self,chainFlowHandle, chainObj, parameters,event):
#try:
length = self.redis.llen( "QUEUES:SPRINKLER:CTRL")
#print length
if length > 0:
data = self.redis.rpop("QUEUES:SPRINKLER:CTRL")
data = base64.b64decode(data)
object_data = json.loads(data )
#print object_data["command"]
print "object_data",object_data
if self.commands.has_key( object_data["command"] ) :
self.commands[object_data["command"]]( object_data,chainFlowHandle, chainObj, parameters,event )
else:
self.alarm_queue.store_past_action_queue("Bad Irrigation Command","RED",object_data )
raise
#except:
#print "exception in dispatch mode"
#quit()
def suspend( self, *args ):
self.alarm_queue.store_past_action_queue("SUSPEND_OPERATION","YELLOW" )
self.irrigation_control.turn_off_master_valves()
self.irrigation_control.disable_all_sprinklers()
self.redis.hset("CONTROL_VARIABLES","SUSPEND","ON")
def resume( self, *args ):
self.alarm_queue.store_past_action_queue("RESUME_OPERATION","GREEN" )
self.redis.hset("CONTROL_VARIABLES","SUSPEND","OFF")
def skip_station( self, *args ):
self.alarm_queue.store_past_action_queue("SKIP_STATION","YELLOW" ,{"skip: on"} )
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","ON" )
def resistance_check( self, object_data, chainFlowHandle, chainObj, parameters, event ):
json_object = {}
json_object["type"] = "RESISTANCE_CHECK"
json_string = json.dumps( json_object)
compact_data = base64.b64encode(json_string)
self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", compact_data )
alarm_queue.store_past_action_queue( "RESISTANCE_CHECK", "GREEN", { "action":"start" } )
def check_off( self,object_data,chainFlowHandle, chainObj, parameters,event ):
json_object = {}
json_object["type"] = "CHECK_OFF"
json_string = json.dumps( json_object)
compact_data = base64.b64encode(json_string)
self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", compact_data )
alarm_queue.store_past_action_queue( "CHECK_OFF", "GREEN", { "action":"start" } )
def clean_filter( self, object_data,chainFlowHandle, chainObj, parameters,event ):
json_object = {}
json_object["type"] = "CLEAN_FILTER"
json_string = json.dumps( json_object)
compact_data = base64.b64encode(json_string)
self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", compact_data )
alarm_queue.store_past_action_queue( "CLEAN_FILTER", "GREEN", { "action":"start" } )
def go_offline( self, object_data,chainFlowHandle, chainObj, parameters,event ):
self.alarm_queue.store_past_action_queue("OFFLINE","RED" )
self.redis.hset("CONTROL_VARIABLES","sprinkler_ctrl_mode","OFFLINE")
self.irrigation_control.turn_off_master_valves()
self.irrigation_control.disable_all_sprinklers()
self.clear_redis_sprinkler_data()
self.clear_redis_irrigate_queue()
self.redis.hset( "CONTROL_VARIABLES","schedule_name","OFFLINE")
self.redis.hset( "CONTROL_VARIABLES","current_log_object", None )
self.redis.hset( "CONTROL_VARIABLES","flow_log_object", None ) ### not sure of
self.redis.hset( "CONTROL_VARIABLES","SUSPEND","ON")
chainFlowHandle.disable_chain_base( ["monitor_irrigation_job_queue","monitor_irrigation_cell"])
chainFlowHandle.enable_chain_base( ["monitor_irrigation_job_queue"])
def queue_schedule( self, object_data,chainFlowHandle, chainObj, parameters,event ):
self.schedule_name = object_data["schedule_name"]
self.load_auto_schedule(self.schedule_name)
#self.redis.hset("CONTROL_VARIABLES","SUSPEND","OFF")
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","OFF")
self.alarm_queue.store_past_action_queue("QUEUE_SCHEDULE","GREEN",{ "schedule":self.schedule_name } )
def queue_schedule_step( self, object_data,chainFlowHandle, chainObj, parameters,event ):
self.schedule_name = object_data["schedule_name"]
self.schedule_step = object_data["step"]
self.schedule_step = int(self.schedule_step)
self.alarm_queue.store_past_action_queue("QUEUE_SCHEDULE_STEP","GREEN",{ "schedule":self.schedule_name,"step":self.schedule_step } )
#print "queue_schedule",self.schedule_name,self.schedule_step
self.load_step_data( self.schedule_name, self.schedule_step ,None,True )
#self.redis.hset("CONTROL_VARIABLES","SUSPEND","OFF")
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","OFF")
def queue_schedule_step_time( self, object_data,chainFlowHandle, chainObj, parameters,event ):
self.schedule_name = object_data["schedule_name"]
self.schedule_step = object_data["step"]
self.schedule_step_time = object_data["run_time"]
self.alarm_queue.store_past_action_queue("DIAGNOSTICS_SCHEDULE_STEP_TIME","YELLOW" , {"schedule_name":self.schedule_name, "schedule_step":self.schedule_step,"schedule_time":self.schedule_step_time})
self.schedule_step = int(self.schedule_step)
self.schedule_step_time = int(self.schedule_step_time)
self.irrigation_control.turn_off_master_valves()
self.irrigation_control.disable_all_sprinklers()
self.clear_redis_sprinkler_data()
self.clear_redis_irrigate_queue()
self.load_step_data( self.schedule_name, self.schedule_step, self.schedule_step_time,False )
self.redis.hset("CONTROL_VARIABLES","SUSPEND","OFF")
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","OFF")
def direct_valve_control( self, object_data,chainFlowHandle, chainObj, parameters,event ):
remote = object_data["controller"]
pin = object_data["pin"]
schedule_step_time = object_data["run_time"]
pin = int(pin)
schedule_step_time = int(schedule_step_time)
self.alarm_queue.store_past_action_queue("DIRECT_VALVE_CONTROL","YELLOW" ,{"remote":remote,"pin":pin,"time":schedule_step_time })
#print "made it here",object_data
self.irrigation_control.turn_off_master_valves()
self.irrigation_control.disable_all_sprinklers()
self.clear_redis_sprinkler_data()
self.clear_redis_irrigate_queue()
#print "direct_valve_control",remote,pin,schedule_step_time
self.load_native_data( remote,pin,schedule_step_time)
self.redis.hset("CONTROL_VARIABLES","SUSPEND","OFF")
self.redis.hset("CONTROL_VARIABLES","SKIP_STATION","OFF")
def open_master_valve( self, object_data,chainFlowHandle, chainObj, parameters,event ):
self.alarm_queue.store_past_action_queue("OPEN_MASTER_VALVE","YELLOW" )
self.irrigation_control.turn_on_master_valves()
chainFlowHandle.enable_chain_base([ "monitor_master_on_web"])
def close_master_valve( self, object_data,chainFlowHandle, chainObj, parameters,event ):
self.alarm_queue.store_past_action_queue("CLOSE_MASTER_VALVE","GREEN" )
chainFlowHandle.disable_chain_base( ["manual_master_valve_on_chain"])
chainFlowHandle.disable_chain_base( ["monitor_master_on_web"])
self.irrigation_control.turn_off_master_valves()
def reset_system( self, *args ):
self.alarm_queue.store_past_action_queue("REBOOT","RED" )
self.redis.hset( "CONTROL_VARIABLES","sprinkler_ctrl_mode","RESET_SYSTEM")
os.system("reboot")
def restart_program( self, *args ):
self.alarm_queue.store_past_action_queue("RESTART","RED" )
self.redis.hset( "CONTROL_VARIABLES","sprinkler_ctrl_mode","RESTART_PROGRAM")
quit()
def clear_redis_irrigate_queue( self,*args ):
#print "clearing irrigate queue"
self.redis.delete( "QUEUES:SPRINKLER:IRRIGATION_QUEUE" )
self.redis.delete( "QUEUES:SPRINKLER:IRRIGATION_CELL_QUEUE")
def clear_redis_sprinkler_data(self):
self.redis.hset("CONTROL_VARIABLES", "sprinkler_ctrl_mode","OFFLINE")
self.redis.hset( "CONTROL_VARIABLES","schedule_name","offline" )
self.redis.hset("CONTROL_VARIABLES", "schedule_step_number",0 )
self.redis.hset("CONTROL_VARIABLES", "schedule_step",0 )
self.redis.hset("CONTROL_VARIABLES", "schedule_time_count",0 )
self.redis.hset( "CONTROL_VARIABLES","schedule_time_max",0 )
def load_auto_schedule( self, schedule_name):
schedule_control = self.get_json_data( schedule_name )
step_number = len( schedule_control["schedule"] )
###
### load schedule start
###
###
#json_object = {}
#json_object["type"] = "START_SCHEDULE"
#json_object["schedule_name"] = schedule_name
#json_object["step_number"] = step_number
#json_string = json.dumps( json_object)
#self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", json_string )
###
### load step data
###
###
for i in range(1,step_number+1):
self.load_step_data( schedule_name, i ,None,True )
###
### load schedule end
###
###
#json_object = {}
#json_object["type"] = "END_SCHEDULE"
#json_object["schedule_name"] = schedule_name
#json_object["step_number"] = step_number
#json_string = json.dumps( json_object)
#self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", json_string )
# note schedule_step_time can be None then use what is in the schedule
def load_step_data( self, schedule_name, schedule_step, schedule_step_time ,eto_flag ):
#print "load step data schedule name ----------------->",schedule_name, schedule_step, schedule_step_time
temp = self.get_schedule_data( schedule_name, schedule_step)
if temp != None :
schedule_io = temp[0]
schedule_time = temp[1]
if schedule_step_time == None:
schedule_step_time = schedule_time
json_object = {}
json_object["type"] = "IRRIGATION_STEP"
json_object["schedule_name"] = schedule_name
json_object["step"] = schedule_step
json_object["io_setup"] = schedule_io
json_object["run_time"] = schedule_step_time
json_object["elasped_time"] = 0
json_object["eto_enable"] = eto_flag
json_string = json.dumps( json_object)
compact_data = base64.b64encode(json_string)
#print "load step data ===== step data is queued"
self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", compact_data )
else:
self.store_event_queue( "non_existant_schedule", json_object )
raise # non schedule
# this is for loading user specified data
def load_native_data( self, remote,bit,time ):
json_object = {}
json_object["type"] = "IRRIGATION_STEP"
json_object["schedule_name"] = "MANUAL"
json_object["step"] = 1
json_object["io_setup"] = [{ "remote":remote, "bits":[bit] }]
json_object["run_time"] = time
json_object["elasped_time"] = 0
json_object["eto_enable"] = False
json_string = json.dumps( json_object)
compact_data = base64.b64encode(json_string)
#print "native load",json_string
self.redis.lpush( "QUEUES:SPRINKLER:IRRIGATION_QUEUE", compact_data)
#print self.redis.llen("QUEUES:SPRINKLER:IRRIGATION_QUEUE")
def get_schedule_data( self, schedule_name, schedule_step):
schedule_control = self.get_json_data( schedule_name )
if schedule_control != None:
io_control = schedule_control["schedule"][schedule_step -1]
m = io_control[0]
schedule_time = m[2]
# format io_control
new_io_control = []
for i in io_control:
temp = { }
temp["remote"] = i[0]
temp["bits"] = i[1]
new_io_control.append(temp)
return [ new_io_control, schedule_time ]
return None
def get_json_data( self, schedule_name ):
#print("get json data ",schedule_name)
sprinkler_ctrl = self.app_files.load_file("sprinkler_ctrl.json")
for j in sprinkler_ctrl :
if j["name"] == schedule_name:
json_data=open("app_data_files/"+j["link"])
json_data = json.load(json_data)
#print "json data",json_data
return json_data
return None
class Monitor():
#
# Measures current and flow rate every minute
# Up
#
def __init__(self, redis, basic_io_control,counter_devices,analog_devices, gpio_bit_input_devices, alarm_queue, udp_servers ):
self.redis = redis
self.basic_io_control = basic_io_control
self.counter_devices = counter_devices
self.analog_devices = analog_devices
self.gpio_inputs = gpio_bit_input_devices
self.alarm_queue = alarm_queue
self.counter_time_ref = time.time()
self.udp_servers = udp_servers
def log_clean_filter( self,*args):
self.redis.hset
self.alarm_queue.store_past_action_queue("CLEAN_FILTER","GREEN" )
self.redis.hset("CONTROLLER_STATUS","clean_filter",time.time() )
def set_suspend( self, *args):
self.redis.hset("CONTROL_VARIABLES","SUSPEND","ON")
def set_resume( self,*args):
self.redis.hset("CONTROL_VARIABLES","SUSPEND","OFF")
def verify_resume( self, *args):
if self.redis.hget("CONTROL_VARIABLES","SUSPEND") == "OFF":
return "DISABLE"
else:
return "HALT"
def clear_cleaning_sum(self, *args):
redis.hset("CONTROL_VARIABLES","cleaning_sum",0)
def check_to_clean_filter( self, chainFlowHandle, chainObj, parameters,event ):
cleaning_interval = redis.hget("CONTROL_VARIABLES","CLEANING_INTERVAL")
flow_value = float( check_redis_value( "global_flow_sensor_corrected" ) )
cleaning_sum = float( check_redis_value( "cleaning_sum") )
cleaning_sum = cleaning_sum + flow_value
redis.hset("CONTROL_VARIABLES","cleaning_sum",cleaning_sum)
if cleaning_interval == 0 :
return # no cleaning interval active
if cleaning_sum > cleaning_interval :
chainFlowHandle.enable_chain_base(["clean_filter_action_chain"])
def update_modbus_statistics( self, *args ):
servers = []
for i in self.udp_servers:
temp = modbus_control.get_all_counters(i)
if temp[0] == True:
servers.append(i)
data = json.loads(temp[1])
for j in data.keys():
if redis.hexists("MODBUS_STATISTICS:"+i,j) == False:
self.redis.hset("MODBUS_STATISTICS:"+i,j,json.dumps(data[j]))
else:
temp_json = redis.hget("MODBUS_STATISTICS:"+i,j)
temp_value = json.loads(temp_json)
temp_value["address"] = j
temp_value["failures"] = int(temp_value["failures"]) +int(data[j]["failures"])
temp_value["counts"] = int(temp_value["counts"]) + int(data[j]["counts"])
temp_value["total_failures"] = int(temp_value["total_failures"]) +int(data[j]["total_failures"])
temp_json = json.dumps(temp_value)
self.redis.hset("MODBUS_STATISTICS:"+i,j,temp_json)
modbus_control.clear_all_counters(i)
self.redis.set("MODBUS_INTERFACES",json.dumps(servers))
def clear_modbus_statistics( self,*args):
interfaces_json = self.redis.get("MODBUS_INTERFACES")
interfaces_value = json.loads(interfaces_json)
for i in interfaces_value:
self.redis.delete("MODBUS_STATISTICS:"+i)
def update_time_stamp( self, *args):
self.alarm_queue.update_time_stamp()
def measure_input_gpio( self, *args ):
for i in self.gpio_inputs:
self.basic_io_control.get_gpio_bit(i) # need to store values
def measure_flow_rate ( self, *args ):
deltat = time.time()-self.counter_time_ref
self.counter_time_ref = time.time()
for i in counter_devices.keys():
flow_value = self.basic_io_control.measure_counter(deltat,i)
self.redis.lpush("QUEUES:SPRINKLER:FLOW:"+str(i),flow_value )
self.redis.ltrim("QUEUES:SPRINKLER:FLOW:"+str(i),0,800)
if i == "main_sensor":
self.redis.hset("CONTROL_VARIABLES","global_flow_sensor",flow_value )
conversion_rate = counter_devices[i]["conversion_factor"]
self.redis.hset("CONTROL_VARIABLES","global_flow_sensor_corrected",flow_value*conversion_rate )
def measure_current( self, *args ):
for i in analog_devices.keys():
current = self.basic_io_control.get_analog( i )
self.redis.lpush( "QUEUES:SPRINKLER:CURRENT:"+i,current )
self.redis.ltrim( "QUEUES:SPRINKLER:CURRENT:"+i,0,800)
self.redis.hset( "CONTROL_VARIABLES",i, current )
class PLC_WATCH_DOG():
def __init__(self, redis, alarm_queue,watch_dog_interface ):
self.redis = redis
self.alarm_queue = alarm_queue
self.watch_dog_interface = watch_dog_interface
def read_wd_flag( self,*arg ):
return_value = self.watch_dog_interface.read_wd_flag()
#print "read_wd_flag",return_value
return "DISABLE"
def write_wd_flag( self,value,*arg ):
self.watch_dog_interface.write_wd_flag(1)
return "DISABLE"
def read_mode_switch( self,value,*arg ):
return_value = self.watch_dog_interface.read_mode_switch()
#print "read_mode_switch",return_value
return "DISABLE"
def read_mode( self,value,*arg ):
return_value = self.watch_dog_interface.read_mode()
#print "read_mode_switch",return_value
return "DISABLE"
if __name__ == "__main__":
import datetime
import time
import string
import urllib2
import math
import redis
import json
import eto
import py_cf
import os
import base64
import io_control.alarm_queue
import io_control.modbus_UDP_device
import io_control.click
import io_control.basic_io_control
import io_control.irrigation_ctl
import io_control.new_instrument