-
Notifications
You must be signed in to change notification settings - Fork 37
/
HWcontrol.py
executable file
·1656 lines (1239 loc) · 42.5 KB
/
HWcontrol.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 -*-
from __future__ import print_function
from __future__ import division
from builtins import str
from builtins import hex
from builtins import range
from past.utils import old_div
import time
import datetime
import threading
from math import sqrt
#import sys,os
#import serial
#import os
import glob
import logging
import subprocess
from GPIOEXPI2Ccontrol import tonumber
logger = logging.getLogger("hydrosys4."+__name__)
global ISRPI
try:
__import__("smbus")
except ImportError:
ISRPI=False
else:
import sys, os
basepath=os.getcwd()
libpath="libraries/BMP/bmp180" # should be without the backslash at the beginning
sys.path.append(os.path.join(basepath, libpath)) # this adds new import paths to add modules
from grove_i2c_barometic_sensor_BMP180 import BMP085
libpath="libraries/BMP/bme280" # should be without the backslash at the beginning
sys.path.append(os.path.join(basepath, libpath)) # this adds new import paths to add modules
import bme280
libpath="libraries/MotorHat" # should be without the backslash at the beginning
sys.path.append(os.path.join(basepath, libpath)) # this adds new import paths to add modules
from stepperDOUBLEmod import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor
import Adafruit_DHT #humidity temperature sensor
#from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor
import spidev
import smbus
import Hygro24_I2C
import hx711_AV
import SlowWire
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
ISRPI=True
HWCONTROLLIST=["tempsensor","humidsensor","pressuresensor","analogdigital","lightsensor","pulse","pinstate","servo","stepper","stepperstatus","photo","mail+info+link","mail+info","returnzero","stoppulse","readinputpin","hbridge","empty","DS18B20","Hygro24_I2C","HX711","SlowWire","InterrFreqCounter","WeatherAPI","BME280_temperature","BME280_humidity","BME280_pressure","BMP180_temperature","RPI_Core_temperature","switchoff","switchon"]
RPIMODBGPIOPINLIST=["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"]
NALIST=["N/A"]
GPIOPLUSLIST=["I2C", "SPI", "SPI2"]
RPIMODBGPIOPINLISTNA=NALIST+RPIMODBGPIOPINLIST
RPIMODBGPIOPINLISTPLUS=RPIMODBGPIOPINLISTNA+GPIOPLUSLIST
ADCCHANNELLIST=["N/A","0","1","2","3","4","5","6","7"] #MCP3008 chip has 8 input channels
# status variables
DHT22_data={}
DHT22_data["default"]={'temperature':None,'humidity':None,'lastupdate':datetime.datetime.utcnow() - datetime.timedelta(seconds=2)}
stepper_data={}
stepper_data["default"]={'busyflag':False}
GPIO_data={}
GPIO_data["default"]={"level":None, "state":None, "threadID":None}
PowerPIN_Status={}
PowerPIN_Status["default"]={"level":0, "state":"off", "pinstate":None}
#" GPIO_data is an array of dictionary, total 40 items in the array
#GPIO_data=[{"level":None, "state":None, "threadID":None} for k in range(40)]
#" PowerPIN_Status is an array of dictionary, total 40 items in the array, the array is used to avoid comflict between tasks using same PIN
# each time the pin is activated the level is increased by 1 unit.
#PowerPIN_Status=[{"level":0, "state":"off", "pinstate":None} for k in range(40)]
MCP3008_busy_flag=False
def toint(thestring, outwhenfail):
try:
f=float(thestring)
n=int(f)
return n
except:
return outwhenfail
def returnmsg(recdata,cmd,msg,successful):
recdata.clear()
print(msg)
recdata.append(cmd)
recdata.append(msg)
recdata.append(successful)
if not successful:
logger.error("Error: %s" ,msg)
return True
def read_status_data(data,element,variable):
#print data
if element in data:
#print " element present"
elementdata=data[element]
if variable in elementdata:
return elementdata[variable]
else:
# variable not in elementdata
return ""
else:
#print " element NOT present"
# element not present in the data use the default
data[element]=data["default"].copy()
elementdata=data[element]
#print data
if variable in elementdata:
return elementdata[variable]
else:
# variable not in elementdata
return ""
def read_status_dict(data,element):
#print data
if element in data:
#print " element present"
elementdata=data[element]
return elementdata
else:
#print " element NOT present"
return {}
def write_status_data(data,element,variable,value):
if element in data:
data[element][variable]=value
else:
data[element]=data["default"].copy()
data[element][variable]=value
def execute_task(cmd, message, recdata):
global DHT22_data
global Servo_data
global stepper_data
global hbridge_data
print(" RASPBERRY HARDWARE CONTROL ")
if cmd==HWCONTROLLIST[0]:
return get_DHT22_temperature(cmd, message, recdata , DHT22_data)
elif cmd==HWCONTROLLIST[1]:
return get_DHT22_humidity(cmd, message, recdata , DHT22_data)
elif cmd==HWCONTROLLIST[2]:
return get_BMP180_data(cmd, message, recdata, "pressure")
elif cmd==HWCONTROLLIST[3]:
retok=get_MCP3008_channel(cmd, message, recdata)
return retok
elif cmd==HWCONTROLLIST[4]:
return get_BH1750_light(cmd, message, recdata)
elif cmd==HWCONTROLLIST[5]: # pulse
return gpio_pulse(cmd, message, recdata)
elif cmd==HWCONTROLLIST[6]: # pinstate
return gpio_pin_level(cmd, message, recdata)
elif cmd==HWCONTROLLIST[7]: # servo
return gpio_set_servo(cmd, message, recdata)
elif cmd==HWCONTROLLIST[8]: #stepper
return gpio_set_stepper(cmd, message, recdata, stepper_data)
elif cmd==HWCONTROLLIST[9]: #stepper status
return get_stepper_status(cmd, message, recdata, stepper_data)
elif cmd==HWCONTROLLIST[13]: #return zero
#print "returnzero"
returndata="0"
returnmsg(recdata,cmd,returndata,1)
return True
elif cmd==HWCONTROLLIST[14]: # stoppulse
return gpio_stoppulse(cmd, message, recdata)
elif cmd==HWCONTROLLIST[15]: # readinputpin
return read_input_pin(cmd, message, recdata)
elif cmd==HWCONTROLLIST[16]: #hbridge
return ""
elif cmd==HWCONTROLLIST[17]: #hbridge status
return ""
elif cmd==HWCONTROLLIST[18]: #DS18B20 temperature sensor
return get_DS18B20_temperature(cmd, message, recdata)
elif cmd==HWCONTROLLIST[19]: #Hygro24_I2C temperature sensor
return get_Hygro24_capacity(cmd, message, recdata)
elif cmd==HWCONTROLLIST[20]: #HX711 cell loads amplifier, for weight sensor
return get_HX711_voltage(cmd, message, recdata)
elif cmd==HWCONTROLLIST[21]: #SlowWire , Digital Hygrometer
return get_SlowWire_reading(cmd, message, recdata)
elif cmd==HWCONTROLLIST[22]: # Interrupt frequency counter
return get_InterruptFrequency_reading(cmd, message, recdata)
elif cmd==HWCONTROLLIST[23]: # weather API counter
return get_WeatherAPI_reading(cmd, message, recdata)
elif cmd==HWCONTROLLIST[24]: # BME280
return get_BME280_data(cmd, message, recdata, "temperature")
elif cmd==HWCONTROLLIST[25]: # BME280
return get_BME280_data(cmd, message, recdata, "humidity")
elif cmd==HWCONTROLLIST[26]: # BME280
return get_BME280_data(cmd, message, recdata, "pressure")
elif cmd==HWCONTROLLIST[27]:
return get_BMP180_data(cmd, message, recdata, "temperature")
elif cmd==HWCONTROLLIST[28]:
return get_RPI_Core_temperature(cmd, message, recdata)
elif cmd==HWCONTROLLIST[29]:
return gpio_switchoff(cmd, message, recdata)
elif cmd==HWCONTROLLIST[30]:
return gpio_switchon(cmd, message, recdata)
else:
returnmsg(recdata,cmd,"Command not found",0)
return False
return False
def execute_task_fake(cmd, message, recdata):
if cmd==HWCONTROLLIST[0]:
get_DHT22_temperature_fake(cmd, message, recdata, DHT22_data)
return True;
elif cmd==HWCONTROLLIST[5]:
gpio_pulse(cmd, message, recdata)
return True;
elif cmd==HWCONTROLLIST[6]:
gpio_pin_level(cmd, message, recdata)
return True;
elif cmd==HWCONTROLLIST[14]:
gpio_stoppulse(cmd, message, recdata)
return True;
else:
returnmsg(recdata,cmd,"Fake command not found",0)
return False
return True
def get_1wire_devices_list():
device_folder_list=[]
outlist=[]
base_dir = '/sys/bus/w1/devices/'
lbs=len(base_dir)
device_folder_list = glob.glob(base_dir+"*")
for item in device_folder_list:
strout=item[lbs:]
if strout[0].isdigit():
outlist.append(strout)
return outlist
def get_I2C_devices_list():
device_list=[]
bus_number = 1 # 1 indicates /dev/i2c-1
bus = smbus.SMBus(bus_number)
timeout=4 #seconds
now = time.time()
for device in range(3, 128):
try:
bus.write_byte(device, 0)
device_list.append("{0}".format(hex(device)))
except:
print("I2C bus not working")
a=1
later = time.time()
difference = int(later - now)
print("I2C address", hex(device) , " Scan Time passed", difference)
if difference>timeout:
logger.warning("Timeout Error, not able to scan the I2C devices")
break
bus.close()
bus = None
return device_list
def get_DHT22_temperature_fake(cmd, message, recdata, DHT22_data):
returnmsg(recdata,cmd,"10.10",1)
return True
def get_DHT22_reading(cmd, message, recdata, DHT22_data):
successflag=0
errormsg=""
msgarray=message.split(":")
pin=int(msgarray[1])
element=msgarray[1]
TemperatureUnit="C"
if len(msgarray)>4:
TemperatureUnit=msgarray[4]
lastupdate=read_status_data(DHT22_data,element,'lastupdate')
deltat=datetime.datetime.utcnow()-lastupdate
if deltat.total_seconds()<0:
logger.warning("last reading DHT sensor was in the past? maybe due to time change, go to reset lastupdate time")
lastupdate=datetime.datetime.utcnow() - datetime.timedelta(seconds=3)
DHT22_data[element]['lastupdate']=lastupdate
deltat=datetime.datetime.utcnow()-lastupdate
if deltat.total_seconds()>3:
humidity=None
temperature=None
readingattempt=3
inde=0
while (inde<readingattempt) and (successflag==0):
inde=inde+1
try:
sensor = Adafruit_DHT.DHT22
humidity, temperature = Adafruit_DHT.read(sensor, pin)
if (TemperatureUnit=="F") and (temperature is not None):
temperature=temperature*1.8+32
except:
print("error reading the DHT sensor (Humidity,Temperature)")
logger.error("error reading the DHT sensor (Humidity,Temperature)")
# if reading OK, update status variable
if (humidity is not None) and (temperature is not None):
# further checks
if (humidity>=0)and(humidity<=100)and(temperature>-20)and(temperature<200):
temperaturestr=('{:3.2f}'.format(temperature))
humiditystr=('{:3.2f}'.format(humidity))
DHT22_data[element]['temperature']=temperaturestr
DHT22_data[element]['humidity']=humiditystr
DHT22_data[element]['lastupdate']=datetime.datetime.utcnow()
successflag=1
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get DHT22 reading')
logger.error("Failed to get DHT22 reading, values in wrong range")
else:
print('Failed to get DHT22 reading')
logger.error("Failed to get DHT22 reading")
time.sleep(1)
if not successflag:
errormsg="Failed 3 attemps to get DHT22 reading"
print(errormsg)
logger.error(errormsg)
temperaturestr=errormsg
humiditystr=errormsg
# data in status variable will not be used in case of failure reading, only in case of reading request less than 10sec
else:
# use the data in memory, reading less than 10 sec ago
temperaturestr=read_status_data(DHT22_data,element,'temperature')
humiditystr=read_status_data(DHT22_data,element,'humidity')
if (humiditystr!="") and (temperaturestr!=""):
successflag=1
else:
errormsg="No DHT22 data in Buffer"
print(errormsg)
logger.error(errormsg)
temperaturestr=errormsg
humiditystr=errormsg
return successflag, temperaturestr, humiditystr
def get_DHT22_temperature(cmd, message, recdata, DHT22_data):
successflag , temperaturestr, humiditystr =get_DHT22_reading(cmd, message, recdata, DHT22_data)
returnmsg(recdata,cmd,temperaturestr,successflag)
return True
def get_DHT22_humidity(cmd, message, recdata, DHT22_data):
successflag , temperaturestr, humiditystr =get_DHT22_reading(cmd, message, recdata, DHT22_data)
returnmsg(recdata,cmd,humiditystr,successflag)
return True
def get_BMP180_data(cmd, message, recdata, datatype):
successflag=0
reading=0
msgarray=message.split(":")
measureUnit=""
if len(msgarray)>4:
measureUnit=msgarray[4]
SensorAddress="0x77"
if len(msgarray)>6:
if msgarray[6]!="":
SensorAddress=msgarray[6]
# Initialise the BMP085 and use STANDARD mode (default value)
# bmp = BMP085(0x77, debug=True)
# bmp = BMP085(0x77, 1)
# To specify a different operating mode, uncomment one of the following:
# bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode
# bmp = BMP085(0x77, 1) # STANDARD Mode
# bmp = BMP085(0x77, 2) # HIRES Mode
Hiresmode=3
bmp = BMP085(int(SensorAddress, 0), Hiresmode) # ULTRAHIRES Mode
#temp = bmp.readTemperature()
try:
if datatype=="pressure":
isok, reading = bmp.readPressure()
if isok:
reading = '{0:0.2f}'.format(reading/100) # the reading is in Hpa
successflag=1
if datatype=="temperature":
isok, reading = bmp.readTemperature()
if isok:
if (measureUnit=="F"):
reading=reading*1.8+32
reading = '{0:0.2f}'.format(reading)
successflag=1
except:
#print " I2C bus reading error, BMP180 , pressure sensor "
msg=" I2C bus reading error, BMP180 sensor " + datatype
returnmsg(recdata,cmd,msg,0)
#pressure is in hecto Pascal
returnmsg(recdata,cmd,reading,successflag)
return True
def get_BME280_data(cmd, message, recdata, datatype):
# datatype can be "temperature", "humidity", "pressure"
successflag=0
Pressure=0
Temperature=0
Humidity=0
msgarray=message.split(":")
measureUnit=""
if len(msgarray)>4:
measureUnit=msgarray[4]
SensorAddress="0x76"
if len(msgarray)>6:
if msgarray[6]!="":
SensorAddress=msgarray[6]
I2C_bus="1"
bme280.bme280_i2c.create_bus(int(SensorAddress, 0),int(I2C_bus))
isok, msg = bme280.setup()
if not isok:
returnmsg(recdata,cmd,msg,0)
return True
data_all = bme280.read_all()
print("here we are with BME :", data_all)
if data_all:
if datatype in data_all:
reading=data_all[datatype]
# convert to farenheit
if datatype=="temperature":
if (measureUnit=="F"):
reading=reading*1.8+32
successflag=1
logger.info("BME280 %s reading: %s", datatype, reading)
print("BME280 ", datatype, " reading: ", reading)
returnmsg(recdata,cmd,reading,successflag)
statusmsg=""
recdata.append(statusmsg)
return True
msg="Generic Error, BME280"
returnmsg(recdata,cmd,msg,0)
return True
def get_BH1750_light(cmd, message, recdata):
successflag=0
msgarray=message.split(":")
measureUnit=""
if len(msgarray)>4:
measureUnit=msgarray[4]
SensorAddress="0x23"
if len(msgarray)>6:
if msgarray[6]!="":
SensorAddress=msgarray[6]
#DEVICE = 0x23 # Default device I2C address
DEVICE = int(SensorAddress,0)
POWER_DOWN = 0x00 # No active state
POWER_ON = 0x01 # Power on
RESET = 0x07 # Reset data register value
# Start measurement at 4lx resolution. Time typically 16ms.
CONTINUOUS_LOW_RES_MODE = 0x13
# Start measurement at 1lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_1 = 0x10
# Start measurement at 0.5lx resolution. Time typically 120ms
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_1 = 0x20
# Start measurement at 0.5lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_HIGH_RES_MODE_2 = 0x21
# Start measurement at 1lx resolution. Time typically 120ms
# Device is automatically set to Power Down after measurement.
ONE_TIME_LOW_RES_MODE = 0x23
bus = smbus.SMBus(1) # Rev 2 Pi uses 1
light=0
try:
data = bus.read_i2c_block_data(DEVICE,ONE_TIME_HIGH_RES_MODE_1)
light = '{0:0.2f}'.format((old_div((data[1] + (256 * data[0])), 1.2)))
successflag=1
except:
#print " I2C bus reading error, BH1750 , light sensor "
msg=" I2C bus reading error, BH1750 , light sensor "
returnmsg(recdata,cmd,msg,0)
return True
returnmsg(recdata,cmd,light,successflag)
return True
def get_RPI_Core_temperature(cmd, message, recdata):
# uses the OS commands to get the SoC core temperature
successflag=0
msgarray=message.split(":")
# needed to provide the temperature in celsius or Farehneit
TemperatureUnit="C"
if len(msgarray)>4:
TemperatureUnit=msgarray[4]
temperature=0
oscmd = ["vcgencmd", "measure_temp"]
wordtofind="temp="
try:
result=subprocess.run(oscmd, capture_output="True", text="True")
scanoutput=result.stdout
except:
msg=" Error reading the RPI internal temperature "
returnmsg(recdata,cmd,msg,0)
return True
for line in scanoutput.split('\n'):
#print " line ",line
strstart=line.find(wordtofind)
if strstart>-1:
substr=line[(strstart+len(wordtofind)):]
lastdigit =[i for i in range(len(substr)) if substr[i].isdigit()].pop()
substr=substr[:lastdigit+1]
print (substr)
try:
temperature=float(substr)
if (TemperatureUnit=="F") and (temperature is not None):
temperature=temperature*1.8+32
temperature=('{:3.2f}'.format(temperature))
successflag=1
except:
msg=" Error reading the RPI internal temperature "
returnmsg(recdata,cmd,msg,0)
return True
returnmsg(recdata,cmd,temperature,successflag)
return True
def get_DS18B20_temperature(cmd, message, recdata):
successflag=0
# this sensors uses the one wire protocol. Multiple sensors can be connected to the same wire and they can be distinguished using an Address which is the mane of the file
# in this algorithm, the message should include the address, if the address field is empty then it gets the first reading available.
msgarray=message.split(":")
TemperatureUnit="C"
if len(msgarray)>4:
TemperatureUnit=msgarray[4]
SensorAddress=""
if len(msgarray)>6:
SensorAddress=msgarray[6]
temperature=0
# These tow lines mount the device:
#os.system('modprobe w1-gpio')
#os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
# Get all the filenames begin with 28 in the path base_dir.
device_folder_list = glob.glob(base_dir + '28*')
SensorAddress=SensorAddress.strip()
isOK=False
if device_folder_list:
device_folder=device_folder_list[0]
if SensorAddress!="":
for item in device_folder_list:
if SensorAddress in item:
device_folder=item
isOK=True
break
else:
isOK=True
if not isOK:
# address of the termometer not found
msg="DS18B20 address not found: " + SensorAddress
returnmsg(recdata,cmd,msg,0)
return True
device_file = device_folder + '/w1_slave'
#below commands reads the DS18B20 rom, which effectively is the address
#name_file=device_folder+'/name'
#f = open(name_file,'r')
#RomReading=f.readline()
f = open(device_file, 'r')
lines = f.readlines()
f.close()
if len(lines)>1:
if ("YES" in lines[0].upper()):
#first row found and OK
# Find the index of 't=' in a string.
equals_pos = lines[1].find('t=')
if equals_pos != -1:
# Read the temperature .
temp_string = lines[1][equals_pos+2:] # takes the right part of the string
try:
temperature = old_div(float(temp_string), 1000.0)
if (TemperatureUnit=="F") and (temperature is not None):
temperature=temperature*1.8+32
temperature=('{:3.2f}'.format(old_div(temperature, 1.)))
successflag=1
except:
#print "error reading the DS18B20"
logger.error("error reading the DS18B20")
returnmsg(recdata,cmd,temperature,successflag)
return True
def get_HX711_voltage(cmd, message, recdata):
#print "starting HX711 reading ****"
successflag=0
# this sensors uses the I2C protocol. Multiple sensors can be connected and can be distinguished using an Address
# in this algorithm, the message should include the address, if the address field is empty then it gets the default address 0x20.
msgarray=message.split(":")
PINDATA_str=""
if len(msgarray)>1:
PINDATA_str=msgarray[1]
measureUnit=""
if len(msgarray)>4:
measureUnit=msgarray[4]
SensorAddress="0x20"
if len(msgarray)>6:
SensorAddress=msgarray[6]
PINCLK_str=""
if len(msgarray)>7:
PINCLK_str=msgarray[7]
PINDATA=toint(PINDATA_str,-1)
PINCLK=toint(PINCLK_str,-1)
if (PINDATA<0)or(PINCLK<0):
msg="HX711 PIN not valid" + SensorAddress
logger.error("HX711 PIN not valid: Pindata = %s Pinclk= %s", PINDATA_str,PINCLK_str)
returnmsg(recdata,cmd,msg,0)
return True
reading=0
bus = 1
HX711_hardware = hx711_AV.HX711(dout_pin=PINDATA, pd_sck_pin=PINCLK)
# start reading multimple sample and making some filtering and average
datatext=""
inde =0
dataarray=[]
#print "Starting sample reading"
samplesnumber=25
for x in range(0, samplesnumber): #number of samples
# read data
isok,data = HX711_hardware.read()
if isok:
dataarray.append(data)
inde=inde+1
datatext=datatext+str(data)+","
#print "HX711 data:",data
if inde==0:
msg="HX711 reading error"
returnmsg(recdata,cmd,msg,0)
return True
successflag=1
logger.info("HX711 Channel: %s", HX711_hardware.get_current_channel())
logger.info("HX711 Channel: %d", HX711_hardware.get_current_gain_A())
averagefiltered, average = normalize_average(dataarray)
print("HX711 data Average: ",average , " Average filtered: ", averagefiltered)
reading=averagefiltered
returnmsg(recdata,cmd,reading,successflag)
return True
def get_SlowWire_reading(cmd, message, recdata):
#print "starting SlowWire reading ****"
successflag=0
# this sensors uses the SlowWire protocol which is similar to one wire but with relaxed times and single Sensor per wire.
# The relaxed timing allow longer cable distances, for application like hygrometers which do not require speed.
msgarray=message.split(":")
PINDATA_str=""
if len(msgarray)>1:
PINDATA_str=msgarray[1]
measureUnit=""
if len(msgarray)>4:
measureUnit=msgarray[4]
PINDATA=toint(PINDATA_str,-1)
if (PINDATA<0):
# address not correct
msg="SlowWire PIN not valid: Pindata = " + PINDATA_str
returnmsg(recdata,cmd,msg,0)
return True
reading=0
Sensor_bus = SlowWire.SlowWire(dout_pin=PINDATA)
# start reading multimple sample and making some filtering and average
#print "Starting sample reading"
ReadingAttempt=3
inde=0
while (ReadingAttempt>0)and(inde==0):
datatext=""
inde=0
dataarray=[]
samplesnumber=1
for x in range(0, samplesnumber): #number of samples
# read data
isok,datalist = Sensor_bus.read_uint()
if isok:
data=datalist[0]
dataarray.append(data)
inde=inde+1
datatext=datatext+str(data)+","
#print "SlowWire data:",data
ReadingAttempt=ReadingAttempt-1
if inde==0:
msg="SlowWire reading error"
returnmsg(recdata,cmd,msg,0)
return True
successflag=1
averagefiltered, average = normalize_average(dataarray)
print("SlowWire data Average: ",average , " Average filtered: ", averagefiltered)
reading=averagefiltered
returnmsg(recdata,cmd,reading,successflag)
return True
def get_Hygro24_capacity(cmd, message, recdata):
#print "starting Hygro24_I2C reading ****"
successflag=0
# this sensors uses the I2C protocol. Multiple sensors can be connected and can be distinguished using an Address
# in this algorithm, the message should include the address, if the address field is empty then it gets the default address 0x20.
msgarray=message.split(":")
measureUnit=""
if len(msgarray)>4:
measureUnit=msgarray[4]
SensorAddress="0x20"
if len(msgarray)>6:
SensorAddress=msgarray[6]
if SensorAddress=="":
SensorAddress="0x20" # try with default address
try:
if SensorAddress.startswith("0x"):
SensorAddressInt = int(SensorAddress, 16)
else:
SensorAddressInt = int(SensorAddress)
except:
msg="Hygro24_I2C address incorrect: " + SensorAddress
returnmsg(recdata,cmd,msg,0)
return True
reading=0
bus = 1
chirp = Hygro24_I2C.ChirpAV(bus, SensorAddressInt)
isOK , reading=chirp.read_capacity()
# need to add control in case there is an error in reading
print("reading ", reading)
if isOK:
successflag=1
else:
msg="Hygro24_I2C reading error"
returnmsg(recdata,cmd,msg,0)
return True
returnmsg(recdata,cmd,reading,successflag)
return True
def get_MCP3008_channel(cmd, message, recdata):
successflag=0
volts=0
msgarray=message.split(":")
messagelen=len(msgarray)
PIN=msgarray[1]
SUBPIN=int(msgarray[2])
channel=SUBPIN
POWERPIN=""
if messagelen>3:
POWERPIN=msgarray[3]
logic="pos"
if messagelen>5:
logic=msgarray[5]
global MCP3008_busy_flag
waitstep=0.1
waittime=0
maxwait=2.5
while (MCP3008_busy_flag==True)and(waittime<maxwait):
time.sleep(waitstep)
waittime=waittime+waitstep
#print "MCP3008 wait time -----> ", waittime
if (waittime>=maxwait):
#something wrog, wait too long, avoid initiate further processing
msg="Wait Time exceeded, not able to read ADCdata Channel: "+str(channel)
returnmsg(recdata,cmd,msg,0)
return True
MCP3008_busy_flag=True
powerPIN_start(POWERPIN,logic,2)
refvoltage=5.0
try:
# Open SPI bus
spi_speed = 1000000 # 1 MHz
spi = spidev.SpiDev()
if PIN == "SPI2":
spi.open(0,1)
else:
spi.open(0,0)
spi.max_speed_hz=spi_speed
# Function to read SPI data from MCP3008 chip
# Channel must be an integer 0-7
datatext=""
inde =0
dataarray=[]
#print "Starting sample reading"