-
Notifications
You must be signed in to change notification settings - Fork 2
/
bcMeter.py
executable file
·1365 lines (1133 loc) · 45.7 KB
/
bcMeter.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
#!/usr/bin/env python3
import subprocess, sys
import RPi.GPIO as GPIO
import smbus
import os
import json
from datetime import datetime
import re
from bcMeter_shared import load_config_from_json, check_connection, update_interface_status, show_display, config, i2c, setup_logging
bcMeter_version = "0.9.930 2024-10-16"
logger = setup_logging('bcMeter')
logger.debug(config)
bus = smbus.SMBus(1) # 1 indicates /dev/i2c-1
# Set variables with defaults
disable_pump_control = config.get('disable_pump_control', False)
compair_upload = config.get('compair_upload', False)
get_location = config.get('get_location', False)
heating = config.get('heating', False)
pump_pwm_freq = int(config.get('pwm_freq', 20))
af_sensor_type = int(config.get('af_sensor_type', 1))
use_rgb_led = config.get('use_rgb_led', 0)
use_display = config.get('use_display', False)
led_brightness = int(config.get('led_brightness', 100))
airflow_sensor = config.get('airflow_sensor', False)
pump_dutycycle = int(config.get('pump_dutycycle', 20))
reverse_dutycycle = config.get('reverse_dutycycle', False)
sample_spot_diameter = float(str(config.get('sample_spot_diameter', 0.5)).replace(',', '.'))
is_ebcMeter = config.get('is_ebcMeter', False)
mail_logs_to = config.get('mail_logs_to', "")
send_log_by_mail = config.get('send_log_by_mail', False)
filter_status_mail = config.get('filter_status_mail', False)
sender_password = config.get('email_service_password', 'email_service_password')
disable_led = config.get('disable_led', False)
cooling = False
temperature_to_keep = 35 if cooling is False else 0
override_airflow = False
sigma_air_880nm = 0.0000000777
run_once = "false"
#pwm for pump:
#GPIO.setup(12,GPIO.OUT) # initialize as an output.
airflow_debug = False
debug = False
sht40_i2c = None
online = False
output_to_terminal = False
zero_airflow = 0
show_display(f"Initializing bcMeter", False, 0)
show_display(f"bcMeter {bcMeter_version}", False, 1)
import traceback, numpy, os, csv, typing, glob, signal, socket, importlib, smtplib
from tabulate import tabulate
from pathlib import Path
from time import sleep, strftime, time
from threading import Thread, Event
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
GPIO.setmode(GPIO.BCM)
devicename = socket.gethostname()
sample_spot_areasize=numpy.pi*(float(sample_spot_diameter)/2)**2 #area of spot in cm2 from bcmeter, diameter 0.50cm
os.chdir('/home/pi')
debug = True if (len(sys.argv) > 1) and (sys.argv[1] == "debug") else False
calibration = True if (len(sys.argv) > 1) and (sys.argv[1] == "cal") else False
airflow_debug = True if (len(sys.argv) > 1) and (sys.argv[1] == "airflow") else False
GPIO.setmode(GPIO.BCM)
MONOLED_PIN=1
GPIO.setup(MONOLED_PIN, GPIO.OUT)
if (use_rgb_led == 1):
# Set up GPIO pins
R_PIN = 6
G_PIN = 7
B_PIN = 8
GPIO.setup(R_PIN, GPIO.OUT)
GPIO.setup(G_PIN, GPIO.OUT)
GPIO.setup(B_PIN, GPIO.OUT)
GPIO.output(R_PIN, 1)
GPIO.output(G_PIN, 1)
GPIO.output(B_PIN, 1)
infrared_led_control = 26
# /RDY bit definition
MCP342X_CONF_RDY = 0x80
# Conversion mode definitions
MCP342X_CONF_MODE_ONESHOT = 0x00
MCP342X_CONF_MODE_CONTINUOUS = 0x10
# Channel definitions
MCP342X_CONF_CHANNEL_1 = 0x00
MCP342X_CHANNEL_2 = 0x20
MCP342X_CHANNEL_3 = 0x40
MCP342X_CHANNEL_4 = 0x60
# Sample size definitions - these also affect the sampling rate
MCP342X_CONF_SIZE_12BIT = 0x00
MCP342X_CONF_SIZE_14BIT = 0x04
MCP342X_CONF_SIZE_16BIT = 0x08
# Programmable Gain definitions
MCP342X_CONF_GAIN_1X = 0x00
MCP342X_CONF_GAIN_2X = 0x01
MCP342X_CONF_GAIN_4X = 0x02
MCP342X_CONF_GAIN_8X = 0x03
ready = MCP342X_CONF_RDY
channel1 = MCP342X_CONF_CHANNEL_1
channel2 = MCP342X_CHANNEL_2
channel3 = MCP342X_CHANNEL_3
channel4 = MCP342X_CHANNEL_4
mode = MCP342X_CONF_MODE_CONTINUOUS
rate_12bit = MCP342X_CONF_SIZE_12BIT
rate_14bit = MCP342X_CONF_SIZE_14BIT
rate_16bit = MCP342X_CONF_SIZE_16BIT
gain = MCP342X_CONF_GAIN_1X
rate = rate_14bit
VRef = 2.048
airflow_only = True if (len(sys.argv) > 1) and (sys.argv[1] == "airflow") else False
airflow_channel = channel1 if airflow_only is True and sys.argv[1] == "1" else channel3
sampling_thread = housekeeping_thread = set_PWM_dutycycle_thread = None
stop_event = Event()
change_blinking_pattern = Event()
def shutdown(reason):
global reverse_dutycycle, housekeeping_thread, set_PWM_dutycycle_thread
update_interface_status(0)
print(f"Quitting: {reason}")
show_display("Goodbye",0,True)
if reason == "SIGINT":
show_display("Turn off bcMeter",1,True)
else:
show_display(f"{reason}",1,True)
show_display("",2,True)
logger.debug(reason)
try:
if (reverse_dutycycle is False):
pi.set_PWM_dutycycle(12, 0)
sleep(0.5)
else:
pi.set_PWM_dutycycle(12, pump_PWM_range)
sleep(0.5)
if (airflow_only is False):
#subprocess.Popen(["sudo", "killall", "pigpiod"]).communicate
GPIO.output(infrared_led_control, False)
GPIO.output(1,False)
GPIO.output(23,False)
#pump_duty.ChangeDutyCycle(0)
if (use_rgb_led == 1):
# Turn off the LED
GPIO.output(R_PIN, 1)
GPIO.output(G_PIN, 1)
GPIO.output(B_PIN, 1)
GPIO.cleanup()
except:
pass
stop_event.set()
change_blinking_pattern.set()
sleep(0.5)
os.kill(os.getpid(), 15)
sys.exit(1)
cmd = ['ps aux | grep bcMeter.py | grep -Fv grep | grep -Fv www-data | grep -Fv sudo | grep -Fiv screen | grep python3']
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
my_pid, err = process.communicate()
if len(my_pid.splitlines()) > 1:
sys.stdout.write("bcMeter Script already running.\n" + str(my_pid.splitlines())+"\n")
shutdown("Already running")
update_interface_status(0)
files = os.listdir("/home/pi")
for file in files:
file_path = os.path.join("/home/pi", file)
#os.chmod(file_path, 0o777) #dont try this at home
online = check_connection()
if (online):
logger.debug("bcMeter is online!")
else:
logger.debug("bcMeter is offline!")
try:
import adafruit_sht4x
except ImportError:
logger.debug("need to be online to install sht library first!")
shutdown("Update needed for sht4x")
if (airflow_only is False):
try:
import pigpio
except ImportError:
logger.error("need to be online to install pigpio first!")
shutdown("Update needed for pigpiod")
try:
subprocess.Popen(["sudo", "killall", "pigpiod"]).communicate
sleep(0.5)
subprocess.Popen(["sudo", "pigpiod","-l", "-s","2","-b","200","-f"]).communicate
sleep(5)
pi = pigpio.pi()
pump_PWM_range=255
pi.set_PWM_range(12, pump_PWM_range)
pi.set_PWM_frequency(12, pump_pwm_freq)
pi.set_PWM_range(infrared_led_control,255)
pi.set_PWM_frequency(infrared_led_control, 1000)
sleep(0.1)
logger.debug("pigpiod started")
except Exception as e:
logger.error("pigpiod Error: %s ", e)
try:
from scipy.ndimage import median_filter
except ImportError:
logger.error("Update bcMeter!")
shutdown("Update needed for scipy")
try:
sht = adafruit_sht4x.SHT4x(i2c)
sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
temperature, relative_humidity = sht.measurements
logger.debug("Temperature: %0.1f C" % temperature)
logger.debug("Humidity: %0.1f %%" % relative_humidity)
sht40_i2c = True
ds18b20 = False
except Exception as e:
sht40_i2c = False
logger.error("Error: %s", e)
if sht40_i2c is False:
class TemperatureSensor:
RETRY_INTERVAL = 0.5
RETRY_COUNT = 10
device_file_name = None
def __init__(self, channel: int):
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(1,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
#def __del__(self):
#GPIO.cleanup()
@staticmethod
def read_device() -> typing.List[str]:
device_file_name = None
try:
device_file_name = glob.glob('/sys/bus/w1/devices/28*')[0] + '/w1_slave'
except Exception as e:
logger.error(f"Temperature Sensor Error {e}")
if device_file_name is not None:
with open(device_file_name, 'r') as fp:
return [line.strip() for line in fp.readlines()]
def get_temperature_in_milli_celsius(self) -> int:
"""
$ cat /sys/bus/w1/devices/28-*/w1_slave
c1 01 55 05 7f 7e 81 66 c8 : crc=c8 YES
c1 01 55 05 7f 7e 81 66 c8 t=28062
"""
for i in range(self.RETRY_COUNT):
lines = self.read_device()
try:
if len(lines) >= 2 and lines[0].endswith('YES'):
match = re.search(r't=(\d{1,6})', lines[1])
if match:
return int(match.group(1), 10)
sleep(self.RETRY_INTERVAL)
except:
pass
logger.error(f"Cannot read temperature (tried {self.RETRY_COUNT} times with an interval of {self.RETRY_INTERVAL})")
try:
temperature_current = round(TemperatureSensor(channel=5).get_temperature_in_milli_celsius()/1000,2) #read once to decide if we use ds18b20
if temperature_current is not None:
ds18b20 = True
if debug:
print("using ds18b20")
logger.debug("Usind ds18b20 as temperature sensor")
logger.debug("Temperature: %0.1f C" % temperature_current)
except:
print("no temperature sensor detected!")
ds18b20 = False
def startUp():
global MCP342X_DEFAULT_ADDRESS, debug, airflow_sensor_bias
airflow_sensor_bias = -1
read_airflow_sensor_bias = read_adc(MCP342X_DEFAULT_ADDRESS,1)
if (debug):
print("now pump should start")
if (airflow_only is False):
try:
pi.set_PWM_dutycycle(infrared_led_control, led_brightness)
except Exception as e:
logger.error(f"{e}")
print(e)
shutdown("pigpiod error on startup")
GPIO.setup(infrared_led_control, GPIO.OUT)
GPIO.setup(1,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
def handle_signal(signum, frame):
if signum == signal.SIGUSR1:
signal_handler()
elif signum == signal.SIGINT:
shutdown("SIGINT")
#Signalhandler
signal.signal(signal.SIGUSR1, handle_signal)
signal.signal(signal.SIGINT, handle_signal)
def signal_handler():
file_path = '/tmp/bcMeter_signalhandler'
if os.path.isfile(file_path):
with open(file_path, 'r+') as file:
content = file.read().strip()
logger.debug("signal handler: %s", content)
if content == 'pump_test':
pump_test()
if content == 'identify':
led_communication()
file.seek(0)
file.truncate()
def initialise(channel, rate):
config = (ready|channel|mode|rate|gain)
bus.write_byte(MCP342X_DEFAULT_ADDRESS, config)
def update_config_entry(config, key, value, description, value_type, parameter):
if key not in config:
config[key] = {} # Ensure config[key] is a dictionary
config[key] = {
"value": value,
"description": description,
"type": value_type,
"parameter": parameter
}
def calibrate_sens_ref():
global MCP342X_DEFAULT_ADDRESS
calibration_data = read_adc(MCP342X_DEFAULT_ADDRESS, 10)
raw_sens = calibration_data[0]
raw_ref = calibration_data[1]
print(f"sens={raw_sens}, ref={raw_ref}")
if raw_sens < raw_ref:
ref_correction = 1
sens_correction = raw_ref / raw_sens
else:
sens_correction = 1
ref_correction = raw_sens / raw_ref
# Load existing configuration or create a new one if it doesn't exist
try:
with open("bcMeter_config.json", "r") as f:
config = json.load(f)
except FileNotFoundError:
config = convert_config_to_json()
# Update or create entries for correction factors
config["sens_correction"] = sens_correction
config["ref_correction"] = ref_correction
update_config_entry(config, "sens_correction", sens_correction, "Sensor Correction Factor", "float", "administration")
update_config_entry(config, "ref_correction", ref_correction, "Reference Correction Factor", "float", "administration")
# Store the updated configuration back to the file
with open("bcMeter_config.json", "w") as f:
json.dump(config, f, indent=4)
print(f"correction factor sens: {sens_correction} and ref: {ref_correction} ")
def find_mcp_adress():
global MCP342X_DEFAULT_ADDRESS
for device in range(128):
try:
adc = bus.read_byte(device)
if (hex(device) == "0x68"):
MCP342X_DEFAULT_ADDRESS = 0x68
elif (hex(device) == "0x6a"):
MCP342X_DEFAULT_ADDRESS = 0x6a
elif (hex(device) == "0x6b"):
MCP342X_DEFAULT_ADDRESS = 0x6b
elif (hex(device) == "0x6c"):
MCP342X_DEFAULT_ADDRESS = 0x6c
elif (hex(device) == "0x6d"):
MCP342X_DEFAULT_ADDRESS = 0x6d
except:
pass
try:
logger.debug("ADC found at Address: %s", hex(MCP342X_DEFAULT_ADDRESS))
return(MCP342X_DEFAULT_ADDRESS)
except:
shutdown("NO ADC")
def getconvert(channel, rate):
if rate == rate_12bit:
N = 12
mcp_sps = 1/240
elif rate == rate_14bit:
N = 14
mcp_sps = 1/60
elif rate == rate_16bit:
N = 16
mcp_sps = 1/15
sleep(mcp_sps*1.4) #better sleep more than less else buffer can be clogged and we get same values for different channels
try:
data = bus.read_i2c_block_data(MCP342X_DEFAULT_ADDRESS, channel, 2)
except Exception as e:
logger.error(f"Error reading ADC ({e})")
shutdown(f"Error reading ADC ({e})")
voltage = ((data[0] << 8) | data[1])
if voltage >= 32768:
voltage = 65536 - voltage
voltage = (2 * VRef * voltage) / (2 ** N)
return round(voltage,5)
def read_adc(mcp_i2c_address, sample_time):
global MCP342X_DEFAULT_ADDRESS, airflow_only, airflow_sensor, airflow_channel, airflow_sensor_bias, calibration
MCP342X_DEFAULT_ADDRESS = mcp_i2c_address
airflow_sample_voltage = voltage_channel1 = voltage_channel3 = voltage_channel2 = sum_channel1 = sum_channel2 = sum_channel3 = 0
average_channel1 = average_channel2 = average_channel3 = airflow_avg = 0
airflow_sample_index = 1
skipsampling = False
i=j=0
start = time()
last_check_time = time()
airflow_samples_to_take = 5 if sample_time < 20 else 20
airflow_samples_to_take = 200 if airflow_only is True else airflow_samples_to_take
check_interval = 1
try:
if (airflow_sensor_bias == -1):
sens_bias_samples_to_take = 100
initialise(airflow_channel, rate_12bit)
airflow_sample_sum = 0
while airflow_sample_index<=sens_bias_samples_to_take:
airflow_sample_voltage = getconvert(airflow_channel, rate_12bit)
airflow_sample_sum += airflow_sample_voltage
airflow_sample_index+=1
average_channel3 = airflow_sample_sum / sens_bias_samples_to_take
airflow_sensor_bias = 0.5-average_channel3
#airflow_sensor_bias=0
print(f"airflow_sensor_bias is set to {airflow_sensor_bias}")
logger.debug(f"airflow_sensor_bias is set to {airflow_sensor_bias}")
skipsampling = True
except NameError:
pass
while ((time()-start)<sample_time-0.25) and (skipsampling is False):
if (airflow_only is False):
x=time()
initialise(channel1, rate)
voltage_channel1 = getconvert(channel1, rate)
sum_channel1 += voltage_channel1
x=time()
initialise(channel2, rate)
voltage_channel2 = getconvert(channel2, rate)
sum_channel2 += voltage_channel2
x=time()
if (debug):
try:
atn_current=round((numpy.log(voltage_channel1/voltage_channel2)*-100),5)
except:
pass
if ((airflow_sensor is True) or (airflow_only is True)) and (i % 5 == 0) and (calibration is False):
initialise(airflow_channel, rate_12bit)
airflow_sample_sum = 0
while airflow_sample_index<=airflow_samples_to_take:
airflow_sample_voltage = getconvert(airflow_channel, rate_12bit)
if (airflow_sample_voltage)==2.047:
airflow_sample_voltage=5 #overweigh for reduction
airflow_sample_sum += airflow_sample_voltage
airflow_sample_index+=1
average_channel3 = airflow_sample_sum / airflow_samples_to_take
if (average_channel3 >= 2.047):
logger.debug("airflow over sensor limit")
sum_channel3+=average_channel3
current_airflow=round(airflow_by_voltage(average_channel3, af_sensor_type),4)
#blink_led(235)
if (airflow_sensor is True):
check_airflow(current_airflow)
pass
airflow_sample_index=1
j+=1
if airflow_only:
cycle = (j%20)+1
if cycle == 1:
airflow_avg = 0
airflow_avg += current_airflow
print(f"{current_airflow} lpm, avg {round(airflow_avg/cycle,4)} lpm")
i+=1
if (debug is True):
print(f"{i}, {round(sum_channel1/i,3)}, {round(sum_channel2/i,3)}, {round(average_channel3,3)}, current: {round(voltage_channel1,3)}, {round(voltage_channel2,3)}, {round(voltage_channel3,3)} ")
pass
if (skipsampling is False):
average_channel3 = (sum_channel3 / j) if (airflow_sensor is True) and (calibration is False) else 0
#'''
average_channel1 = sum_channel1 / i
average_channel2 = sum_channel2 / i
#average_channel3 = sum_channel3 / i
#logger.debug(round(airflow_by_voltage(average_channel3, af_sensor_type),4),j)
end=time()-start
#logger.debug(i, "SEN: ", round(average_channel1,2), ", REF: ", round(average_channel2,4), ", AIRFLOW/VOLTAGE", round(airflow_by_voltage(average_channel3,af_sensor_type),4),"/",round(average_channel3,1))
return average_channel1, average_channel2, average_channel3
def airflow_by_voltage(voltage,sensor_type):
global airflow_sensor_bias
pump_type=2
if (airflow_only is True) or (debug is True):
#print("\033c", end="", flush=True)
#print(voltage, airflow_sensor_bias)
pass
# Define the table data (replace with your actual table) # valid for OMRON D6F P0001A1 with 100ml; due to limitations of ADC only 77ml max
if (sensor_type == 0):
table = {
0.5: 0.000,
2.5: 0.100
}
#if pump type == 1
'''
if (sensor_type == 1) :
# Define the table data (replace with your actual table) # valid for OMRON D6F P0010A2 with 1000ml; due to limitations of ADC only 473ml max
table = {
0.50:0,
0.72:0.05,
0.82:0.077,
1.08:0.155,
1.16:0.22,
1.77:0.5,
1.90:0.6
}
'''
if (sensor_type == 1) :
# Define the table data (replace with your actual table) # valid for OMRON D6F P0010A2 with 1000ml; due to limitations of ADC only 473ml max
table = {
0.50:0,
0.511:0.010,
0.8:0.055,
0.9:0.09,
1.34:0.19,
1.855:0.39,
1.96:0.46,
2.0:0.487,
2.024:0.504
}
# Check if the voltage is in the table
if voltage in table:
return table[voltage]
else:
# Interpolate the value if voltage is between two table entries
voltages = sorted(table.keys())
if voltage < voltages[0]:
return 0
if voltage > voltages[-1]:
return 2.1 # Voltage is outside the range of the table
lower_voltage = max(v for v in voltages if v <= voltage)
upper_voltage = min(v for v in voltages if v >= voltage)
# Linear interpolation formula
lower_value = table[lower_voltage]
upper_value = table[upper_voltage]
interpolated_value = lower_value + (voltage - lower_voltage) * (upper_value - lower_value) / (upper_voltage - lower_voltage)
#if ((airflow_sensor == 1) and (interpolated_value > 0.47)) or ((airflow_sensor == 0 and interpolated_value>0.075)):
# interpolated_value = 9999
return interpolated_value#-airflow_sensor_bias
def get_sensor_values(MCP342X_DEFAULT_ADDRESS,sample_time):
main_sensor_value = reference_sensor_value = airflow_sensor_value = 0
sensor_values = read_adc(MCP342X_DEFAULT_ADDRESS, sample_time)
main_sensor_value = sensor_values[0]
reference_sensor_value = sensor_values[1]
airflow_sensor_value = sensor_values[2]
return main_sensor_value, reference_sensor_value, airflow_sensor_value
def set_pwm_dutycycle(pump_dutycycle, stop_event):
global config
reverse_dutycycle = config.get('reverse_dutycycle', False)
try:
pi.set_PWM_dutycycle(12, pump_dutycycle)
except:
if (debug):
print("exception in pwm thread")
if reverse_dutycycle is False:
pi.set_PWM_dutycycle(12, 0)
else:
pi.set_PWM_dutycycle(12, pump_PWM_range)
if (stop_event.is_set()):
if (debug):
print("exiting pwm thread")
if reverse_dutycycle is False:
pi.set_PWM_dutycycle(12, 0)
else:
pi.set_PWM_dutycycle(12, pump_PWM_range)
def check_airflow(current_mlpm):
global pump_dutycycle, reverse_dutycycle, zero_airflow, airflow_only, airflow_debug, config, temperature_current, temperature_to_keep, disable_pump_control, override_airflow, desired_airflow_in_lpm
if override_airflow is False:
desired_airflow_in_lpm = float(str(config.get('airflow_per_minute', 0.1)).replace(',', '.'))
if airflow_only is True:
disable_pump_control = True
if disable_pump_control is False:
if current_mlpm < 0.002 and desired_airflow_in_lpm > 0:
zero_airflow += 1
if zero_airflow == 50:
logger.debug("resetting pump... no airflow measured")
pump_test()
sleep(1)
zero_airflow = 0
return
if current_mlpm < desired_airflow_in_lpm and airflow_debug is False:
if reverse_dutycycle is True:
if pump_dutycycle <= 0:
#logger.error("cannot reach desired airflow. please lower it")
adjust_airflow(current_mlpm)
pump_dutycycle=pump_pwm_freq
else:
pump_dutycycle -= 1
else:
if pump_dutycycle >= pump_PWM_range:
#logger.error("cannot reach desired airflow. please lower it")
adjust_airflow(current_mlpm)
pump_dutycycle = 0
else:
pump_dutycycle += 1
if current_mlpm > desired_airflow_in_lpm and airflow_debug is False:
if reverse_dutycycle is True:
pump_dutycycle += 1
else:
pump_dutycycle -= 1
pump_dutycycle = max(0, min(pump_dutycycle, pump_PWM_range))
set_PWM_dutycycle_thread = Thread(target=set_pwm_dutycycle, args=(pump_dutycycle, stop_event,))
set_PWM_dutycycle_thread.start()
show_display(f"{round(current_mlpm*1000)} ml/min", 2, False)
else:
set_PWM_dutycycle_thread = Thread(target=set_pwm_dutycycle, args=(pump_dutycycle, stop_event,))
set_PWM_dutycycle_thread.start()
if debug is True:
os.system('clear')
print(f"{round(current_mlpm*1000, 2)} ml/min, desired: {round(desired_airflow_in_lpm*1000, 2)} ml/min, pump_dutycycle: {pump_dutycycle}")
def adjust_airflow(current_mlpm):
global pump_dutycycle, override_airflow, desired_airflow_in_lpm
print(current_mlpm, desired_airflow_in_lpm)
if current_mlpm < desired_airflow_in_lpm:
override_airflow = True
desired_airflow_in_lpm -= 0.01
logger.debug(f"Cannot reach airflow. Adjusting to {round(desired_airflow_in_lpm,3)}")
print(f"Adjusting airflow to {desired_airflow_in_lpm}")
sleep(1)
if desired_airflow_in_lpm <= 0.06:
logger.error("Minimum airflow of 60 ml not reached. Stopping the script.")
print("Minimum airflow of 60 ml not reached. Stopping the script.")
shutdown("NOMAXAIRFLOW")
return
def pump_test():
logger.debug("Init Pump")
if (reverse_dutycycle is True):
for cyclepart in range(1,11):
pi.set_PWM_dutycycle(12, pump_PWM_range/cyclepart)
sleep(0.12)
pi.set_PWM_dutycycle(12, pump_PWM_range)
else:
for cyclepart in range(1,11):
try:
pi.set_PWM_dutycycle(12, cyclepart*10*(pump_PWM_range/100))
sleep(0.12)
except Exception as e:
logger.error(e)
pi.set_PWM_dutycycle(12, 0)
''' pi.set_PWM_dutycycle(12, 0)
sleep(5)
pi.set_PWM_dutycycle(12, pump_PWM_range/2)
sleep(5)
'''
def button_pressed():
input_state = GPIO.input(16)
if input_state == False:
print(yo)
pass
def createLog(log,header):
Path("/home/pi/logs").mkdir(parents=True, exist_ok=True)
if os.path.isfile("/home/pi/logs/log_current.csv"):
os.remove("/home/pi/logs/log_current.csv")
if os.path.isfile("/home/pi/logs/compair_offline_log.log"):
os.remove("/home/pi/logs/compair_offline_log.log")
with open("/home/pi/logs/" + log, "a") as logfileArchive: #save this logfile for archive
logfileArchive.write(header + "\n\n")
os.chmod("/home/pi/logs/" + log, 0o777)
with open("/home/pi/logs/log_current.csv", "a") as temporary_log: # temporary current logfile for web interface
temporary_log.write(header + "\n\n")
with open("/home/pi/logs/compair_offline_log.log", "w") as compair_offline_log: #save this logfile for archive
compair_offline_log.write("timestamp;bcngm3;atn;bcmsen;bcmref;bcmtemperature;location;filter_status" + "\n\n")
os.chmod("/home/pi/logs/compair_offline_log.log", 0o777)
def filter_values(log, kernel):
file_path = output_file_path = log
delimiter = ';'
with open(file_path, 'r') as file:
reader = csv.DictReader(file, delimiter=delimiter)
data = list(reader)
# Extract 'BCngm3' values
bcngm3_values = []
for row in data:
try:
value = float(row['BCngm3_unfiltered'])
except ValueError:
value = float('nan')
bcngm3_values.append(value)
# Apply median filter with a kernel size
filtered_bcngm3_values = median_filter(bcngm3_values, size=kernel)
# Update the 'BCngm3' values with the filtered values
for i, row in enumerate(data):
if not float('nan') == filtered_bcngm3_values[i]:
row['BCngm3'] = str(int(filtered_bcngm3_values[i])) # Convert back to string for writing to CSV
# Write the modified data back to the CSV file
with open(output_file_path, 'w', newline='') as output_file:
fieldnames = reader.fieldnames
writer = csv.DictWriter(output_file, fieldnames=fieldnames, delimiter=delimiter)
writer.writeheader()
writer.writerows(data)
def send_email(payload):
# Email configuration
smtp_server = "live.smtp.mailtrap.io"
sender_email = f"{devicename} Status <[email protected]>"
receiver_email = f"{mail_logs_to}"
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
email_receiver_list = receiver_email.split(",")
subject_prefix ="bcMeter Status Mail: "
if (payload == "Filter"):
logger.debug("Filter Change Mail sent")
subject = subject_prefix + "Change filter!"
body = "Hello dear human, please consider changing the filter paper the next time you're around, thank you!"
if (payload == "Log"):
logger.debug("Log Mail sent")
subject =subject_prefix + "Log file"
body = "Hello dear human, please find attached the log file"
# Attach the file
file_path = "/home/pi/logs/log_current.csv"
current_time = datetime.now().strftime("%y%m%d_%H%M")
send_file_as = f"{devicename}_{current_time}.csv"
with open(file_path, "rb") as file:
attachment = MIMEApplication(file.read(), Name=send_file_as)
# Add header for the attachment
attachment["Content-Disposition"] = f"attachment; filename={send_file_as}"
message.attach(attachment)
if (payload == "Pump"):
logger.error("Error mail (Pump Malfcuntion) sent")
subject =subject_prefix + "Pump Malfunction"
body = "I do not register any airflow. Please check the connections and if the pump is working"
# Attach the file
file_path = "/home/pi/logs/log_current.csv"
current_time = datetime.now().strftime("%y%m%d_%H%M")
send_file_as = f"{devicename}_{current_time}.csv"
with open(file_path, "rb") as file:
attachment = MIMEApplication(file.read(), Name=send_file_as)
# Add header for the attachment
attachment["Content-Disposition"] = f"attachment; filename={send_file_as}"
message.attach(attachment)
# Email content
message["Subject"] = subject
message.attach(MIMEText(body, "plain"))
# Establish a connection to the SMTP server
for receiver in email_receiver_list:
try:
with smtplib.SMTP(smtp_server, 587) as server:
server.starttls()
server.login("api", sender_password)
# Send the email
server.sendmail(sender_email, receiver, message.as_string())
logger.debug("Email to %s sent successfully!", receiver)
except Exception as e:
logger.error("Email alert: %s", e)
def apply_temperature_correction(BCngm3_unfiltered, temperature_current):
# Constants obtained from polynomial regression; EXPERIMENTAL
intercept = -15358.619
temperature_coefficient = 1918.009
temperature_squared_coefficient = -54.284
# Calculate the correction factor based on temperature
correction_factor = intercept + temperature_current * temperature_coefficient + temperature_current**2 * temperature_squared_coefficient
# Apply the correction factor to BCngm3_unfiltered
corrected_BCngm3_unfiltered = BCngm3_unfiltered * correction_factor
return corrected_BCngm3_unfiltered
def bcmeter_main(stop_event):
global housekeeping_thread, airflow_sensor, temperature_to_keep, airflow_sensor_bias, session_running_since, sender_password, ds18b20, config, temperature_current
compair_offline_logging = False
if (airflow_only is True):
get_sensor_values(MCP342X_DEFAULT_ADDRESS, 86400*31)
return
last_email_time = time()
first_value = True
reference_sensor_value_last_run=filter_status = samples_taken = sht_humidity=delay=airflow_sensor_value=reference_sensor_value=reference_sensor_bias=main_sensor_bias=bcmRefFallback=bcmSenRef=reference_sensor_value_current=main_sensor_value_current=main_sensor_value_last_run=attenuation_last_run=BCngm3_unfiltered=BCngm3_unfilteredpos=carbonRollAvg01=carbonRollAvg02=carbonRollAvg03=temperature_current=bcm_temperature_last_run=attenuation_coeff=absorption_coeff=0
notice = devicename
volume_air_per_sample = absorb = main_sensor_value = attenuation = attenuation_current = 0.0000
today = str(datetime.now().strftime("%y-%m-%d"))
session_running_since = datetime.now()
now = str(datetime.now().strftime("%H:%M:%S"))
logFileName =(str(today) + "_" + str(now) + ".csv").replace(':','')
header="bcmDate;bcmTime;bcmRef;bcmSen;bcmATN;relativeLoad;BCngm3_unfiltered;BCngm3;Temperature;notice;main_sensor_bias;reference_sensor_bias;sampleDuration;sht_humidity;airflow"
compair_offline_log_header="timestamp,bcngm3,atn,bcmsen,bcmref,bcmtemperature, location, filter_status"
new_log_message="Started log " + str(today) + " " + str(now) + " " + str(bcMeter_version) + " " + str(logFileName)
print(new_log_message)
logger.debug(new_log_message)
createLog(logFileName,header)
update_interface_status(1)
logString = str(datetime.now().strftime("%d-%m-%y")) + ";" + str(datetime.now().strftime("%H:%M:%S")) +";" +str(reference_sensor_value_current) +";" +str(main_sensor_value_current) +";" +str(attenuation_current) + ";"+ str(attenuation_coeff) +";"+ str(BCngm3_unfiltered) + ";"+ str(BCngm3_unfiltered) + ";" + str(temperature_current) + ";" + str(notice) + ";" + str(main_sensor_bias) + ";" + str(reference_sensor_bias) + ";" + str(round(delay,1)) + ";" + str(sht_humidity) + ";" + str(volume_air_per_sample)
online = check_connection()
if (compair_upload is True):
import compair_frost_upload
if debug is True:
#print("Airflow Sensor bias: ", airflow_sensor_bias)
pass
if airflow_only is False:
#pump_test()
housekeeping_thread = Thread(target=housekeeping, args=(stop_event,))
housekeeping_thread.start()
y = 0
while(True):
get_location = config.get('get_location', False)
location = config.get('location', [0,0])
device_specific_correction_factor = float(str(config.get('device_specific_correction_factor', 1)).replace(',', '.'))
filter_scattering_factor = float(str(config.get('filter_scattering_factor', 1.39)).replace(',', '.'))
mail_sending_interval = int(config.get('mail_sending_interval', 6))
filter_status_mail = config.get('filter_status_mail', False)
send_log_by_mail = config.get('send_log_by_mail', False)
email_service_password = config.get('email_service_password', 'email_service_password')
led_brightness = int(config.get('led_brightness', 100))
sample_time = int(config.get('sample_time', 300))
if (is_ebcMeter and sample_time>30):
sample_time=30
sens_correction = float(str(config.get('sens_correction', 1)).replace(',', '.'))
ref_correction = float(str(config.get('ref_correction', 1)).replace(',', '.'))
sample_spot_diameter = float(str(config.get('sample_spot_diameter', 0.5)).replace(',', '.'))
pi.set_PWM_dutycycle(infrared_led_control, led_brightness)
start = time()
if (samples_taken < 3) and (sample_time >60):
sample_time=60
samples_taken+=1
reference_sensor_value_last_run=reference_sensor_value
sensor_values=get_sensor_values(MCP342X_DEFAULT_ADDRESS, sample_time)
main_sensor_value = sensor_values[0]*sens_correction
reference_sensor_value = sensor_values[1]*ref_correction
#test small compansation:
#env_change = reference_sensor_value_last_run - reference_sensor_value
#if env_change !=0:
# main_sensor_value = main_sensor_value * (1 - (numpy.log10(abs(env_change) + 1) * -1 * (1 + abs(env_change))))
if (airflow_sensor is True):
airflow_sensor_value = sensor_values[2]
airflow_per_minute = round(airflow_by_voltage(airflow_sensor_value,af_sensor_type),4)
if (af_sensor_type==0) and (airflow_per_minute>0.075):
logger.error("To high airflow!")
if (af_sensor_type==1) and (airflow_per_minute>450):
logger.error("To high airflow!")
delay = time() - start
#logger.debug("measurement took ", delay)
volume_air_per_sample=(delay/60)*airflow_per_minute #liters of air between samples
else:
airflow_per_minute = float(config.get('airflow_per_minute', 0.100).replace(',', '.'))
volume_air_per_sample=(sample_time/60)*airflow_per_minute #liters of air between samples
main_sensor_value_current=main_sensor_value#-main_sensor_bias
reference_sensor_value_current=reference_sensor_value#-reference_sensor_bias
try:
temperature_current = get_temperature()
except:
temperature_current = 1
if (reference_sensor_value_current == 0): reference_sensor_value_current = 1 #avoid later divide by 0; just for debug
if (main_sensor_value_current == 0): main_sensor_value_current = 1#avoid later divide by 0; just for debug#
filter_status_quotient = main_sensor_value_current/reference_sensor_value_current
filter_status = (
5 if filter_status_quotient > 0.8 else