-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathhardwaremod.py
executable file
·2205 lines (1729 loc) · 65.5 KB
/
hardwaremod.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 -*-
"""
selected plan utility
"""
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import range
from past.utils import old_div
import shutil
import logging
import re
import os
import os.path
import sys
import string
import random
from datetime import datetime,date,timedelta
import time
import filestoragemod
import HWcontrol
import MQTTcontrol
import HC12control
import GPIOEXPI2Ccontrol
import photomod
import cameradbmod
import struct
import imghdr
import copy
import statusdataDBmod
# ///////////////// -- GLOBAL VARIABLES AND INIZIALIZATION --- //////////////////////////////////////////
global DATABASEPATH
DATABASEPATH=filestoragemod.DATABASEPATH
global HWDATAFILENAME
HWDATAFILENAME="hwdata.txt"
global DEFHWDATAFILENAME
DEFHWDATAFILENAME="default/defhwdata.txt"
logger = logging.getLogger("hydrosys4."+__name__)
print("logger name ", __name__)
# ///////////////// -- Hawrware data structure Setting -- ///////////////////////////////
#important this data is used almost everywhere
HWdataRECORDKEY=[]
HWdataKEYWORDS={}
# HW_INFO group includes info for the UI and identification of the item
HW_INFO_IOTYPE="IOtype" # info group, needed, specify if input or output
HW_INFO_NAME="name" # info group , mandatory, identifier of the item (shown in the UI)
HW_INFO_MEASUREUNIT="unit" # info group , mandatory, measurement unit of info parameter
HW_INFO_MEASURE="measure" # info group , mandatory, measurement type of info parameter
# HW_CTRL group includes info hardware to speak with HWcontrol module
HW_CTRL_CMD="controllercmd" # HW control group , mandatory, command sent to the HWControl section to specify the function to select -> HW
HW_CTRL_PIN="pin" # HW control group ,optional, specify the PIN board for the HWControl if needed -> gpiopin
HW_CTRL_PIN2="pin2" # HW control group ,optional, specify the PIN board for the HWControl if needed -> gpiopin (new item in rel 1.08)
HW_CTRL_ADCCH="ADCchannel" # HW control group , optional, specify the arg1 board for the HWControl if needed -> "ADCchannel"
HW_CTRL_PWRPIN="powerpin" # HW control group , optional, specify PIN that is set ON before starting tasks relevant to ADC convert, Actuator pulse, then is set OFF when the task is finished -> "ADCpowerpin"
HW_CTRL_LOGIC="logic" # HW control group , optional, in case the relay works in negative logic
#"settingaction", # HW control group , use the controllercmd instead -> to be removed
HW_CTRL_ADDR="address" # HW control group , optional, specify this info for the HWControl if needed -> mailaddress, I2C address
HW_CTRL_TITLE="title" # HW control group , optional, specify this info for the HWControl if needed (mail title) -> "mailtitle"
#servo/stepper/sensors
HW_CTRL_FREQ="frequency" # HW control group , optional, working frequency of the servo
HW_CTRL_MIN="min" # HW control group , optional, minimum of the duty cycle, for sensor this is the min corresponding to zero
HW_CTRL_MAX="max" # HW control group , optional, maximum of the duty cycle, for sensor this is the max corresponding to scale
HW_CTRL_SCALE="scale" # HW control group , optional, for sensor this is the scale (new item in rel 1.08)
HW_CTRL_OFFSET="offset" # HW control group , optional, for sensor not clear how to use TBD (new item in rel 1.08)
HW_CTRL_DIR="direction" # HW control group , optional, invert the data min/max (new item in rel 1.08)
HW_FUNC_USEDFOR="usefor" # function group , optional, description of main usage of the item and the actions associated with the plan "selectedplanmod"
HW_FUNC_SCHEDTYPE="schedulingtype" # function group , optional, between "oneshot" and "periodic"
HW_FUNC_TIME="time" #function group , optional, description of time or interval to activate the item depending on the "schedulingtype" item, in case of interval information the minutes are used for the period, seconds are used for start offset
USAGELIST=["sensorquery", "watercontrol", "fertilizercontrol", "lightcontrol", "temperaturecontrol", "humiditycontrol", "photocontrol", "mailcontrol", "powercontrol", "N/A", "Other"]
MEASURELIST=["Temperature", "Humidity" , "Light" , "Pressure" , "Time", "Quantity", "Moisture","Percentage","Events"]
MEASUREUNITLIST=["C", "%" , "Lum" , "hPa" , "Sec", "Pcs", "Volt","F"]
HWdataKEYWORDS[HW_INFO_IOTYPE]=["input" , "output" ]
HWdataKEYWORDS[HW_INFO_NAME]=[]
HWdataKEYWORDS[HW_INFO_MEASUREUNIT]=MEASUREUNITLIST
HWdataKEYWORDS[HW_INFO_MEASURE]=MEASURELIST
HWdataKEYWORDS[HW_CTRL_CMD]=HWcontrol.HWCONTROLLIST+MQTTcontrol.HWCONTROLLIST+HC12control.HWCONTROLLIST+GPIOEXPI2Ccontrol.HWCONTROLLIST
HWdataKEYWORDS[HW_CTRL_PIN]=HWcontrol.RPIMODBGPIOPINLISTPLUS
HWdataKEYWORDS[HW_CTRL_PIN2]=HWcontrol.RPIMODBGPIOPINLISTPLUS
HWdataKEYWORDS[HW_CTRL_ADCCH]=HWcontrol.ADCCHANNELLIST
HWdataKEYWORDS[HW_CTRL_PWRPIN]=HWcontrol.RPIMODBGPIOPINLISTNA
HWdataKEYWORDS[HW_CTRL_LOGIC]=["pos","neg"]
HWdataKEYWORDS[HW_CTRL_ADDR]=[]
HWdataKEYWORDS[HW_CTRL_TITLE]=[]
HWdataKEYWORDS[HW_FUNC_USEDFOR]=USAGELIST #used for
HWdataKEYWORDS[HW_FUNC_SCHEDTYPE]=["oneshot", "periodic"] #scheduling type
HWdataKEYWORDS[HW_FUNC_TIME]=[] #time in format hh:mm:ss
HWdataKEYWORDS[HW_CTRL_FREQ]=[]
HWdataKEYWORDS[HW_CTRL_MIN]=[]
HWdataKEYWORDS[HW_CTRL_MAX]=[]
HWdataKEYWORDS[HW_CTRL_SCALE]=[]
HWdataKEYWORDS[HW_CTRL_OFFSET]=[]
HWdataKEYWORDS[HW_CTRL_DIR]=["dir","inv"]
# ///////////////// -- Hawrware data structure Setting -- ///////////////////////////////
IOdata=[]
# read IOdata -----
if not filestoragemod.readfiledata(HWDATAFILENAME,IOdata): #read calibration file
print("warning hwdata file not found -------------------------------------------------------")
#read from default file
filestoragemod.readfiledata(DEFHWDATAFILENAME,IOdata)
print("writing default calibration data")
filestoragemod.savefiledata(HWDATAFILENAME,IOdata)
# end read IOdata -----
IOdatatemp=copy.deepcopy(IOdata)
IOdatarow={}
# ///////////////// --- END GLOBAL VARIABLES ------
# ///////////////// -- STATUS VARIABLES UTILITY -- ///////////////////////////////
Servo_Status={}
Servo_Status["default"]={'duty':"3"}
Stepper_Status={}
Stepper_Status["default"]={'position':"0"}
Hbridge_Status={}
Hbridge_Status["default"]={'position':"0"}
Blocking_Status={}
Blocking_Status["default"]={'priority':0} # priority level, the commands are executed only if the command priority is higher or equlal to the blocking status priority
Actuator_Enable_Status={}
Actuator_Enable_Status["default"]={'Enabled':"enable"}
Data_Visible_Status={}
Data_Visible_Status["default"]={'Visible':"True"}
def UpdateCMDcontrol():
global HWdataKEYWORDS
HWdataKEYWORDS[HW_CTRL_CMD]=HWcontrol.HWCONTROLLIST+MQTTcontrol.HWCONTROLLIST+HC12control.HWCONTROLLIST+GPIOEXPI2Ccontrol.HWCONTROLLIST
# ///////////////// --- END STATUS VARIABLES ------
# procedures for the Enable/Disable
# Status variable --> Actuator_Enable_Status
def ReadActuatorEnabled(Target):
return statusdataDBmod.read_status_data(Actuator_Enable_Status,Target,'Enabled',True,"Actuator_Enable_Status")
def WriteActuatorEnabled(Target, status):
global Actuator_Enable_Status
statusdataDBmod.write_status_data(Actuator_Enable_Status,Target,'Enabled',status,True,"Actuator_Enable_Status")
# Status variable --> Data_Visible_Status
def ReadVisibleStatus(Target):
return statusdataDBmod.read_status_data(Data_Visible_Status,Target,'Visible',True,"Data_Visible_Status")
def WriteVisibleStatus(Target, status):
global Data_Visible_Status
statusdataDBmod.write_status_data(Data_Visible_Status,Target,'Visible',status,True,"Data_Visible_Status")
#-- start filestorage utility--------////////////////////////////////////////////////////////////////////////////////////
# filestoragemod.readfiledata(filename,filedata)
# filestoragemod.savefiledata(filename,filedata)
# filestoragemod.appendfiledata(filename,filedata)
# filestoragemod.savechange(filename,searchfield,searchvalue,fieldtochange,newvalue)
# filestoragemod.deletefile(filename)
def readfromfile():
global IOdata
filestoragemod.readfiledata(HWDATAFILENAME,IOdata)
def IOdatatempalign():
global IOdatatemp
IOdatatemp=copy.deepcopy(IOdata)
def IOdatafromtemp():
global IOdata
IOdata=copy.deepcopy(IOdatatemp)
filestoragemod.savefiledata(HWDATAFILENAME,IOdata)
def SaveData():
filestoragemod.savefiledata(HWDATAFILENAME,IOdata)
def checkdata(fieldtocheck,dictdata,temp=True): # check if basic info in the fields are correct
# name is the unique key indicating the row of the list, dictdata contains the datato be verified
# check the "name" field
fieldname=HW_INFO_NAME
if (fieldtocheck==fieldname)or(fieldtocheck==""):
if fieldname in dictdata:
fieldvalue=dictdata[fieldname]
if fieldvalue=="":
message="Name is empty"
return False, message
elif not re.match("^[A-Za-z0-9_-]*$", fieldvalue):
message="Name should not contains alphanumeric caracters or spaces"
return False, message
else:
#check same name already present in IOdatatemp
if searchmatch(fieldname,fieldvalue,temp):
message="Same name is already present"
return False, message
fieldname=HW_FUNC_TIME
correlatedfield=HW_INFO_IOTYPE
if (fieldtocheck==fieldname)or(fieldtocheck==""):
if (correlatedfield in dictdata)and(fieldname in dictdata):
fieldvalue=dictdata[fieldname]
if fieldvalue!="":
#check format is correct
if len(fieldvalue.split(":"))<3:
message="Please enter correct time format hh:mm:ss"
return False, message
else:
if dictdata[correlatedfield]=="input":
message="Time cannot be empty for item belonging to input"
return False, message
# check select field dependencies
#dictdata[HW_INFO_IOTYPE]=["input" , "output" ]
#dictdata[HW_INFO_MEASUREUNIT]=MEASUREUNITLIST
#dictdata[HW_INFO_MEASURE]=MEASURELIST
#dictdata[HW_CTRL_CMD]=HWcontrol.HWCONTROLLIST
# check if the PIN is same when using the "pulse"
fieldname=HW_CTRL_PIN
correlatedfield=HW_CTRL_CMD
if (fieldtocheck==fieldname)or(fieldtocheck==""):
if (correlatedfield in dictdata)and(fieldname in dictdata):
if "pulse"==dictdata[correlatedfield]:
fieldvalue=dictdata[fieldname]
if fieldvalue!="N/A":
listkeyvalue=[{"key":fieldname , "value":fieldvalue},{"key":correlatedfield , "value":dictdata[correlatedfield]}]
if searchmatchN(listkeyvalue,temp):
message="Same PIN already used"
return False, message
# check if the PIN is same when using the "pulse/I2CGPIOEXP"
fieldname=HW_CTRL_PIN
correlatedfield=HW_CTRL_CMD
if (fieldtocheck==fieldname)or(fieldtocheck==""):
correlatedfieldvalue=dictdata.get(correlatedfield)
if "pulse/I2CGPIOEXP"==correlatedfieldvalue:
fieldvalue=dictdata.get(fieldname)
if fieldvalue!="N/A":
listkeyvalue=[{"key":fieldname , "value":fieldvalue},{"key":correlatedfield , "value":correlatedfieldvalue},{"key":HW_CTRL_ADDR , "value":dictdata.get(HW_CTRL_ADDR)}]
if searchmatchN(listkeyvalue,temp):
message="Same PIN already used"
return False, message
#dictdata[HW_CTRL_ADCCH]=HWcontrol.ADCCHANNELLIST
#dictdata[HW_CTRL_PWRPIN]=HWcontrol.RPIMODBGPIOPINLIST
#dictdata[HW_CTRL_LOGIC]=["pos","neg"]
#dictdata[HW_FUNC_USEDFOR]=USAGELIST #used for
#dictdata[HW_FUNC_SCHEDTYPE]=["oneshot", "periodic"] #scheduling type
return True, ""
def sendcommand(cmd,sendstring,recdata,target="", priority=0):
if target!="":
if ReadActuatorEnabled(target)=="enable":
prioritystatus=statusdataDBmod.read_status_data(Blocking_Status,target,'priority')
#print " Target output ", target , "priority status: ", prioritystatus , " Command Priority: ", priority
#check if the actions are blocked
if priority>=prioritystatus:
if cmd in HWcontrol.HWCONTROLLIST:
return HWcontrol.sendcommand(cmd,sendstring,recdata)
elif cmd in MQTTcontrol.HWCONTROLLIST:
return MQTTcontrol.sendcommand(cmd,sendstring,recdata)
elif cmd in HC12control.HWCONTROLLIST:
return HC12control.sendcommand(cmd,sendstring,recdata)
elif cmd in GPIOEXPI2Ccontrol.HWCONTROLLIST:
return GPIOEXPI2Ccontrol.sendcommand(cmd,sendstring,recdata)
else:
successflag=0
recdata.append(cmd)
recdata.append("Device not found")
recdata.append(successflag)
return True
else:
successflag=0
recdata.append(cmd)
recdata.append("blocked")
recdata.append(successflag)
return True
else:
successflag=0
recdata.append(cmd)
recdata.append("Disabled")
recdata.append(successflag)
return True
else:
if cmd in HWcontrol.HWCONTROLLIST:
return HWcontrol.sendcommand(cmd,sendstring,recdata)
elif cmd in MQTTcontrol.HWCONTROLLIST:
return MQTTcontrol.sendcommand(cmd,sendstring,recdata)
elif cmd in HC12control.HWCONTROLLIST:
return HC12control.sendcommand(cmd,sendstring,recdata)
elif cmd in GPIOEXPI2Ccontrol.HWCONTROLLIST:
return GPIOEXPI2Ccontrol.sendcommand(cmd,sendstring,recdata)
def normalizesensordata(reading_str,sensorname):
scaledefault=1
offsetdefault=0
Thereading=reading_str
#print " Sensor " , sensorname , "reading ",Thereading
#print " Sensor value post elaboration"
# get the normalization data
Minimum=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_MIN)) # if not found searchdata return ""
Maximum=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_MAX))
Direction=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_DIR)) # can be two values "inv" , "dir"
Scale=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_SCALE))
Offset=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_OFFSET))
# transform all valuse in numbers
Minvalue=tonumber(Minimum, 0)
Maxvalue=tonumber(Maximum, 0)
Scalevalue=tonumber(Scale, scaledefault)
Offsetvalue=tonumber(Offset, offsetdefault)
readingvalue=tonumber(Thereading, 0)
if abs(Minvalue-Maxvalue)>0.01: # in case values are zero or not consistent, stops here
if Direction!="inv":
den=Maxvalue-Minvalue
readingvalue=old_div((readingvalue-Minvalue),den)
else:
den=Maxvalue-Minvalue
readingvalue=1-old_div((readingvalue-Minvalue),den)
if Scalevalue>0:
readingvalue=readingvalue*Scalevalue
readingvalue=readingvalue+Offsetvalue
# transform to string and adjust the format
Thereading=str('%.2f' % readingvalue)
return Thereading
def getsensordata(sensorname,attemptnumber): #needed
# this procedure was initially built to communicate using the serial interface with a module in charge of HW control (e.g. Arduino)
# To lower the costs, I used the PI hardware itself but I still like the way to communicate with the HWcontrol module that is now a SW module not hardware
isok=False
statusmessage=""
cmd=searchdata(HW_INFO_NAME,sensorname,HW_CTRL_CMD)
Thereading=""
if not cmd=="":
pin=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_PIN))
arg1=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_ADCCH))
arg2=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_PWRPIN))
arg3=str(searchdata(HW_INFO_NAME,sensorname,HW_INFO_MEASUREUNIT))
arg4=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_LOGIC))
arg5=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_ADDR))
arg6=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_PIN2))
arg7=str(searchdata(HW_INFO_NAME,sensorname,HW_CTRL_TITLE))
timestr=searchdata(HW_INFO_NAME,sensorname,HW_FUNC_TIME)
mastertimelist=separatetimestringint(timestr)
timeperiodsec=mastertimelist[0]*3600+mastertimelist[1]*60+mastertimelist[0]
arg8=str(timeperiodsec)
sendstring=sensorname+":"+pin+":"+arg1+":"+arg2+":"+arg3+":"+arg4+":"+arg5+":"+arg6+":"+arg7+":"+arg8
recdata=[]
ack=False
i=0
while (not ack)and(i<attemptnumber): # old check when the serial interface was used, in this case ack only indicates that the trasmission was correct, not the sensor value
ack=sendcommand(cmd,sendstring,recdata,sensorname,0)
i=i+1
if ack:
if recdata[0]==cmd: # this was used to check the response and command consistency when serial comm was used
if recdata[2]>0: # this is the flag that indicates if the measurement is correct
#print " Sensor " , sensorname , "reading ",recdata[1]
isok=True
Thereading=normalizesensordata(recdata[1],sensorname) # output is a string
print(" Sensor " , sensorname , "Normalized reading ",Thereading)
logger.info("Sensor %s reading: %s", sensorname,Thereading)
if len(recdata)>3:
statusmessage=recdata[3]
else:
print("Problem with sensor reading ", sensorname)
logger.error("Problem with sensor reading: %s", sensorname)
statusmessage=recdata[1]
else:
print("Problem with response consistency ", sensorname , " cmd " , cmd)
logger.error("Problem with response consistency : %s", sensorname)
else:
print("no answer from Hardware control module", sensorname)
logger.error("no answer from Hardware control module: %s", sensorname)
else:
print("sensor name not found in list of sensors ", sensorname)
logger.error("sensor name not found in list of sensors : %s", sensorname)
return isok, Thereading, statusmessage
def makepulse(target,duration,addtime=True, priority=0): # pulse in seconds , addtime=True extend the pulse time with new time , addtime=False let the current pulse finish ,
if addtime:
activationmode="ADD"
else:
activationmode="NOADD"
#search the data in IOdata
command=searchdata(HW_INFO_NAME,target,HW_CTRL_CMD)
PIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN)
print( " MakePulse ")
return activatepulse(command,PIN,duration,activationmode,target,priority)
def activatepulse(command,PIN,duration,activationmode,target,priority):
logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC)
POWERPIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PWRPIN)
address=searchdata(HW_INFO_NAME,target,HW_CTRL_ADDR)
title=searchdata(HW_INFO_NAME,target,HW_CTRL_TITLE)
testpulsetime=duration
# normal pulse
sendstring=command+":"+PIN+":"+testpulsetime+":"+logic+":"+POWERPIN+":"+ address +":0"+":"+activationmode+":"+target+":"+title
isok=False
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack = sendcommand(command,sendstring,recdata,target,priority)
#print "returned data " , recdata
# recdata[0]=command (string), recdata[1]=data (string) , recdata[2]=successflag (0,1)
successflag=0
if len(recdata)>2:
successflag=recdata[2]
msg=""
if len(recdata)>1:
msg=recdata[1]
if ack and successflag:
isok=True
recdata.append("Pulse Started")
return "Pulse Started", True
else:
if not successflag:
print ( " Return Status ", msg)
return msg , False
return "Generic error", False
def switchon(target,addtime=True, priority=0): # pulse in seconds , addtime=True extend the pulse time with new time , addtime=False let the current pulse finish ,
print ("### Switch ON ###")
if addtime:
activationmode="ADD"
else:
activationmode="NOADD"
cmd=searchdata(HW_INFO_NAME,target,HW_CTRL_CMD)
cmdlist=cmd.split("/")
command="switchon"
if len(cmdlist)>1:
command=command+"/"+cmdlist[1]
PIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN)
logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC)
POWERPIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PWRPIN)
address=searchdata(HW_INFO_NAME,target,HW_CTRL_ADDR)
title=searchdata(HW_INFO_NAME,target,HW_CTRL_TITLE)
testpulsetime=""
# normal pulse
sendstring=command+":"+PIN+":"+testpulsetime+":"+logic+":"+POWERPIN+":"+ address +":0"+":"+activationmode+":"+target+":"+title
print (sendstring)
isok=False
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack = sendcommand(command,sendstring,recdata,target,priority)
#print "returned data " , recdata
# recdata[0]=command (string), recdata[1]=data (string) , recdata[2]=successflag (0,1)
successflag=0
if len(recdata)>2:
successflag=recdata[2]
msg=""
if len(recdata)>1:
msg=recdata[1]
if ack and successflag:
isok=True
recdata.append("Pulse Started")
return "Pulse Started", True
else:
if not successflag:
print ( " Return Status ", msg)
return msg , False
return "Generic error", False
def stoppulse(target):
#search the data in IOdata
#print "Stop Pulse - ", target
cmd=searchdata(HW_INFO_NAME,target,HW_CTRL_CMD)
cmdlist=cmd.split("/")
stopcmd="stoppulse"
if len(cmdlist)>1:
stopcmd=stopcmd+"/"+cmdlist[1]
PIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN)
logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC)
POWERPIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PWRPIN)
address=searchdata(HW_INFO_NAME,target,HW_CTRL_ADDR)
title=searchdata(HW_INFO_NAME,target,HW_CTRL_TITLE)
# normal pulse
sendstring=stopcmd+":"+PIN+":"+"0"+":"+logic+":"+POWERPIN+":"+address+":0"+":"+target+":"+title
#print "logic " , logic , " sendstring " , sendstring
isok=False
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack= sendcommand(stopcmd,sendstring,recdata,target,5)
#print "returned data " , recdata
if ack and recdata[1]!="e":
#print target, "correctly activated"
isok=True
return "Stopped" , True
return "error" , False
def switchOFF(target):
#search the data in IOdata
print ("### Switch Off ####")
cmd=searchdata(HW_INFO_NAME,target,HW_CTRL_CMD)
cmdlist=cmd.split("/")
cmd="switchoff"
if len(cmdlist)>1:
cmd=cmd+"/"+cmdlist[1]
PIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN)
logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC)
#POWERPIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PWRPIN)
POWERPIN=""
address=searchdata(HW_INFO_NAME,target,HW_CTRL_ADDR)
title=searchdata(HW_INFO_NAME,target,HW_CTRL_TITLE)
# normal pulse
sendstring=cmd+":"+PIN+":"+"0"+":"+logic+":"+POWERPIN+":"+address+":0"+":"+target+":"+title
#print "logic " , logic , " sendstring " , sendstring
isok=False
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack= sendcommand(cmd,sendstring,recdata,target,5)
successflag=0
if len(recdata)>2:
successflag=recdata[2]
msg=""
if len(recdata)>1:
msg=recdata[1]
if ack and successflag:
isok=True
recdata.append("Switch OFF")
return "Pulse Stop", True
else:
if not successflag:
print ( " Return Status ", msg)
return msg , False
return "Generic error", False
def servoangle(target,percentage,delay,priority=0): #percentage go from zeo to 100 and is the percentage between min and max duty cycle
global Servo_Status
#search the data in IOdata
isok=False
print("Move Servo - ", target) #normally is servo1
# check if servo is belonging to servolist
servolist=searchdatalist(HW_CTRL_CMD,"servo",HW_INFO_NAME)
if target in servolist:
PIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN)
try:
FREQ=searchdata(HW_INFO_NAME,target,HW_CTRL_FREQ)
MIN=searchdata(HW_INFO_NAME,target,HW_CTRL_MIN)
MAX=searchdata(HW_INFO_NAME,target,HW_CTRL_MAX)
previousduty=getservoduty(target)
dutycycle= str(int(MIN)+(int(MAX)-int(MIN))*int(percentage)/float(100))
stepsnumber="40" # this should be a string
difference=float(previousduty)-float(dutycycle)
percentagediff=abs(float(100)*difference/(int(MAX)-int(MIN)))
if percentagediff<1: # one percent difference
print(" No difference with prevoius position ", target , " percentage difference ", percentagediff)
return "same" , isok
if 0<=int(percentage)<=100:
print("range OK")
else:
print(" No valid data for Servo ", target , " out of Range")
return "Out of Range" , isok
except ValueError:
print(" No valid data for Servo", target)
return "error" , isok
sendstring="servo:"+PIN+":"+FREQ+":"+dutycycle+":"+str(delay)+":"+previousduty+":"+stepsnumber
print(" sendstring " , sendstring)
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack= sendcommand("servo",sendstring,recdata,target,priority)
print("returned data " , recdata)
if ack and recdata[1]!="e":
print(target, "correctly activated")
# save duty as new status
statusdataDBmod.write_status_data(Servo_Status,target,'duty',dutycycle)
isok=True
return percentage , isok
return "error" , isok
def getservopercentage(target):
percentage="50"
MIN=searchdata(HW_INFO_NAME,target,HW_CTRL_MIN)
MAX=searchdata(HW_INFO_NAME,target,HW_CTRL_MAX)
if (not MIN=="")and(not MAX==""):
#print " MIN ", MIN , " MAX ", MAX
try:
den=(int(MAX)-int(MIN))
percentage_num=int(old_div((100*(float(getservoduty(target))-int(MIN))),den))
if percentage_num<0:
percentage_num=0
if percentage_num>100:
percentage_num=100
percentage=str(percentage_num)
except:
print(" No valid data for Servo", target)
print("servo percntage " , percentage)
return percentage
def getservoduty(element):
return statusdataDBmod.read_status_data(Servo_Status,element,'duty')
# stepper section
def GO_stepper_position(target,position,priority=0):
position=toint(position,0)
prev_position_string=getstepperposition(target)
prev_position=toint(prev_position_string,position)
steps=position-prev_position
isdone=False
if steps>0:
out , isdone=GO_stepper(target,steps,"FORWARD",priority)
else:
steps=abs(steps)
out , isdone=GO_stepper(target,steps,"BACKWARD",priority)
return out , isdone
def get_stepper_busystatus(target):
tempdict , isok=get_stepper_HWstatus(target)
if isok:
if "busyflag" in tempdict:
return tempdict["busyflag"]
return ""
def get_stepper_HWstatus(target):
#search the data in IOdata
isok=False
try:
Interface_Number=searchdata(HW_INFO_NAME,target,HW_CTRL_ADCCH)
except ValueError:
return "error" , isok
sendstring="stepperstatus:"+Interface_Number
print(" sendstring " , sendstring)
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack= sendcommand("stepperstatus",sendstring,recdata,target,0)
print("returned data " , recdata)
if ack:
print(target, "correctly activated")
print("get stepper status : " , recdata[1])
isok=True
return recdata[1], isok
return "Error" , isok
def GO_stepper(target,steps,direction,priority=0):
global Stepper_Status
#search the data in IOdata
isok=False
print("Move Stepper - ", target) #only supported the I2C default address, the module supports 2 stepper interfaces: 1,2
position_string=getstepperposition(target)
print(" position " , position_string)
try:
Interface_Number=searchdata(HW_INFO_NAME,target,HW_CTRL_ADCCH)
FREQ=searchdata(HW_INFO_NAME,target,HW_CTRL_FREQ)
MIN=searchdata(HW_INFO_NAME,target,HW_CTRL_MIN)
MAX=searchdata(HW_INFO_NAME,target,HW_CTRL_MAX)
steps=int(steps)
if steps<=0:
print(" No valid range for Stepper ", target)
return "Out of Range" , isok
# simulate endpoints
position=int(position_string)
if direction=="FORWARD":
position=position+steps
elif direction=="BACKWARD":
position=position-steps
if int(MIN)<=(position)<=int(MAX):
print("range OK")
else:
print(" No valid range for Stepper ", target)
return "Out of Range" , isok
except ValueError:
print(" No valid data for Servo", target)
return "error" , isok
sendstring="stepper:"+Interface_Number+":"+direction+":"+FREQ+":"+str(steps)
print(" sendstring " , sendstring)
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack= sendcommand("stepper",sendstring,recdata,target,priority)
print("returned data " , recdata)
if ack and recdata[1]!="e":
print(target, "correctly activated")
# save position as new status
statusdataDBmod.write_status_data(Stepper_Status,target,'position',str(position),True,"Stepper_Status")
isok=True
return str(position) , isok
return "Error" , isok
def getstepperposition(element):
return statusdataDBmod.read_status_data(Stepper_Status,element,'position',True,"Stepper_Status")
def setstepperposition(element, position):
global Stepper_Status
return statusdataDBmod.write_status_data(Stepper_Status,element,'position',position,True,"Stepper_Status")
# END stepper section
# START hbridge section
def GO_hbridge_position(target,position_str,priority=0):
prev_position_string=gethbridgeposition(target) # in range value
prev_position=toint(prev_position_string,0)
position=toint(position_str,prev_position)
MINstr=searchdata(HW_INFO_NAME,target,HW_CTRL_MIN)
MIN=toint(MINstr,0)
MAXstr=searchdata(HW_INFO_NAME,target,HW_CTRL_MAX)
MAX=toint(MAXstr,0)
zerooffset=0
steps=position-prev_position # in range values
absolutesteps=abs(steps)
if position<=MIN: # the final position is intended to be the minimum
zerooffsetstr=searchdata(HW_INFO_NAME,target,HW_CTRL_OFFSET)
zerooffset=toint(zerooffsetstr,0)
out=""
isdone=False
if steps>0:
out , isdone=GO_hbridge(target,absolutesteps,zerooffset,"FORWARD",priority)
elif steps<0:
out , isdone=GO_hbridge(target,absolutesteps,zerooffset,"BACKWARD",priority)
return out , isdone
def GO_hbridge(target,steps_str,zerooffset,direction,priority=0):
global Hbridge_Status
#search the data in IOdata
isok=False
print("Move Hbridge - ", target)
try:
command=searchdata(HW_INFO_NAME,target,HW_CTRL_CMD)
PIN1=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN)
PIN2=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN2)
logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC)
MIN=searchdata(HW_INFO_NAME,target,HW_CTRL_MIN)
MAX=searchdata(HW_INFO_NAME,target,HW_CTRL_MAX)
address=searchdata(HW_INFO_NAME,target,HW_CTRL_ADDR)
position_string=gethbridgeposition(target)
print(" position " , position_string)
steps=int(steps_str)
print("PIN1 ", PIN1 , "PIN2 ", PIN2 , "steps ", steps , " direction " , direction, " MIN ", MIN , " MAX ", MAX)
if steps<=0:
print(" No valid range (ore Zero) for pulse steps", target)
return "Out of Range" , isok
print(" position " , position_string)
# simulate endpoints
position=int(position_string)
print(" position int " , position)
if direction=="FORWARD":
position=position+steps
elif direction=="BACKWARD":
position=position-steps
print(" position int " , position)
if int(MIN)<=(position)<=int(MAX):
print("range OK")
else:
print(" No valid range for hbridge ", target)
return "Out of Range" , isok
except ValueError:
print(" No valid data for hbridge, please check the HardwareTable parameters ", target)
return "error" , isok
# here apply the offset
steps=steps+zerooffset
sendstring=command+":"+PIN1+":"+PIN2+":"+direction+":"+str(steps)+":"+logic+":"+address
print(" sendstring " , sendstring)
errorcode="error"
i=0
while (not(isok))and(i<2):
i=i+1
recdata=[]
ack= gpio_set_hbridge(command,sendstring,recdata,target,priority)
print("returned data " , recdata)
if ack and recdata[1]!="e":
print(target, "correctly activated")
# save position as new status
sethbridgeposition(target, str(position))
#statusdataDBmod.write_status_data(Hbridge_Status,target,'position',str(position),True,"Hbridge_Status") # save in persistent mode
isok=True
return str(position) , isok
else:
errorcode="error"
if len(recdata)>2:
errorcode=recdata[2]
return errorcode , isok
def gpio_set_hbridge(cmd, message, recdata, target, priority ):
msgarray=message.split(":")
messagelen=len(msgarray)
PIN1=msgarray[1]
PIN2=msgarray[2]
direction=msgarray[3]
durationsecondsstr=msgarray[4]
logic=msgarray[5]
address=msgarray[6]
#print "hbridge ", PIN1, " ", PIN2, " ", direction, " ", durationsecondsstr, " ", logic
# check that both pins are at logic low state, so Hbridge is off
PIN1active=getpinstate(target, address, PIN1, logic)
PIN2active=getpinstate(target, address, PIN2, logic)
hbridgebusy=PIN1active or PIN2active
# Make the command suitable for other devices
cmdlist=cmd.split("/")
basecmd="pulse"
cmd=basecmd
if len(cmdlist)>1:
cmd=basecmd+"/"+cmdlist[1]
if hbridgebusy:
print("hbridge motor busy ")
logger.warning("hbridge motor Busy, not proceeding ")
recdata.append(cmd)
recdata.append("e")
recdata.append("busy")
return False
POWERPIN="N/A"
activationmode="NOADD"