-
Notifications
You must be signed in to change notification settings - Fork 8
/
airiana-core.py
executable file
·2452 lines (2294 loc) · 112 KB
/
airiana-core.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/python3
# -*- coding: utf-8 -*-
############################
vers = "11.01"
import airdata # noqa
import numpy # noqa
import select # noqa
import threading # noqa
import os # noqa
import traceback # noqa
import time # noqa
import sys # noqa
import signal # noqa
import math # noqa
import pickle # noqa
import socket # noqa
import syslog # noqa
from request import Request # noqa
numpy.seterr('ignore')
#############################
Running = True
savecair = False
mode = "RTU"
holdoff_t = time.time() - 3000 # now - 50 minutes
if "TCP" in sys.argv:
mode = "TCP"
class ControlledExit(Exception):
"""
Exit exception
"""
pass
# Register cleanup
def exit_callback(self, return_code):
global Running
Running = False
print("Graceful shutdown\nexiting on signal", self, return_code)
sys.stdout.flush()
now = device.iter
shutdown = time.time()
os.system("cp ./RAM/data.log ./data.save")
if threading.enumerate()[-1].name == "Timer":
threading.enumerate()[-1].cancel() # noqa this is a threading.Timer, is has cancel()
cmd_socket.close()
os.write(ferr, bytes("Exiting in a safe way\t" + str(time.ctime()) + "\n", encoding='utf8'))
# Sleep until one iteration has passed, or we've been in shutdown for 3 sec.
while time.time() < shutdown + 3:
if device.iter > now: # if main loop completes an iteration, exit.
break
time.sleep(0.5)
syslog.syslog("Controlled shutdown of airiana-core")
raise ControlledExit
signal.signal(signal.SIGTERM, exit_callback) # noqa ignore arg type check
signal.signal(signal.SIGINT, exit_callback) # noqa ignore arg type check
path = ""
try:
path = os.path.abspath(__file__).replace(__file__.split("/")[-1], "")
syslog.syslog("file is " + __file__.split("/")[-1])
syslog.syslog("changing to " + path)
os.chdir(path)
except FileNotFoundError:
syslog.syslog("unable to chdir to:" + path)
exit(22)
# exec util fnctns
os.chdir(path + "/public")
os.system("./ip-replace.sh") # reset ip-addresses on buttons.html
os.chdir(path)
os.system("./http &> /dev/null") # Start web service
listme = []
# cpy saved data to RAM ##
if not os.path.lexists("./data.save"):
os.system("touch data.save")
else:
os.system("cp data.save ./RAM/data.log")
#################################
if not os.path.lexists("./RAM/forecast.txt"):
os.system("touch ./RAM/forecast.txt")
#################################
if "debug" in sys.argv and not os.path.lexists("./sensors"):
os.system("touch sensors")
#################################
starttime = time.time()
# Setup daemon env
if not os.path.isdir("./RAM"):
os.system("mkdir ./RAM")
ferr = os.open("./RAM/err", os.O_WRONLY | os.O_CREAT)
air_out = os.open("./RAM/air.out", os.O_WRONLY | os.O_CREAT)
if "daemon" in sys.argv:
fout = os.open("./RAM/out", os.O_WRONLY | os.O_CREAT)
os.dup2(fout, sys.stdout.fileno())
print("Output redirected to file;")
os.dup2(ferr, sys.stderr.fileno())
os.lseek(ferr, 0, os.SEEK_END)
# Setup serial, RS 485 to machine
if os.path.lexists("/dev/ttyUSB0"):
print("Communication started on device ttyUSB0;")
unit = "/dev/ttyUSB0"
os.write(ferr, bytes("\n\nUsing /dev/ttyUSB0" + "\n", encoding='utf8'))
elif os.path.lexists("/dev/serial0"):
print("Communication started on device Serial0;")
unit = "/dev/serial0"
os.write(ferr, bytes("\n\nUsing /dev/serial0" + "\n", encoding='utf8'))
else:
print("Communication started on device ttyAMA0;")
unit = "/dev/ttyAMA0"
os.write(ferr, bytes("\n\nUsing /dev/ttyAMA0" + "\n", encoding='utf8'))
# Command socket setup
hostname = os.popen("hostname").read()[:-1]
print("Trying to Run on host:", hostname, ", for 60sec;")
cmd_socket = None
while True:
try:
cmd_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
cmd_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
cmd_socket.bind(("0.0.0.0", 9876))
break
except socket.SO_ERROR:
traceback.print_exc(ferr)
os.system("sleep 1")
print("sleeping;")
if time.time() - starttime > 60:
break
# Utility functions, clear screen, count_down etc.
sensor_dict = {}
def count_down(inhibit, target_time):
inhibit = int(target_time - (time.time() - inhibit))
if inhibit > 3600:
hrs = math.floor(inhibit / 3600)
inhibit = int(inhibit - (hrs * 3600))
return str(hrs) + "h " + str(math.floor(inhibit / 60)) + "min " + str(inhibit % 60).zfill(2) + "s"
if inhibit % 60 == 0:
return str(math.floor(inhibit / 60)) + "min"
if inhibit > 60:
return str(math.floor(inhibit / 60)) + "min " + str(inhibit % 60).zfill(2) + "s"
if inhibit < 60:
return str(inhibit).zfill(2) + "s"
# SEND PING TO EPIC HEADMASTER
def report_alive():
global holdoff_t
message = ""
hw_addr = ""
fd = 0
try:
msg = os.popen("/sbin/ifconfig wlan0").readlines()
for each in msg:
if each.find("HWaddr") != -1 or each.find("ether") != -1:
message = each
message += os.popen("hostname -I").read()
hw_addr = str(each.split(" ")[9]).replace(":", "_")
try:
message += "\n###status:" + str(device.status_field) + "\n###<br>"
except ValueError:
message += "\nstatus: initialization " + str(vers) + "\n\n<br>"
try:
fd = os.open("RAM/err", os.O_RDONLY)
stats = os.stat("RAM/err")
size_t = stats.st_size
if size_t > 1024 * 5:
size_t = 1024 * 5
os.lseek(fd, -size_t, os.SEEK_END)
temp = os.read(fd, size_t)
os.close(fd)
if size_t == 5 * 1024 and "keep-log" not in sys.argv:
os.lseek(ferr, 0, os.SEEK_SET)
os.ftruncate(ferr, 0)
os.fsync(ferr)
os.write(ferr, temp)
os.fsync(ferr)
try:
if os.path.lexists("update.log"):
log_file = os.open("update.log", os.O_RDONLY)
log_data = os.read(log_file, 5000)
temp += bytes("\n\n", "utf-8")
temp += log_data
os.close(log_file)
if os.path.lexists("./RAM/request.log"):
with open("./RAM/request.log") as reqlog:
temp += bytes("\n\n", "utf-8")
temp += bytes(reqlog.read(), "utf-8")
except KeyboardInterrupt:
pass
temp = temp.replace(b"\n", b"<br>")
temp = temp.replace(b"\t", b" ")
message += temp.decode("utf-8") + "<br>"
message += os.popen("df |grep RAM").read() + "<br>"
message += os.popen("df |grep var").read() + "<br>"
message += "Source:('" + os.popen("./geoloc.py printIp 2>/dev/null").read() + "\')<br>"
if os.path.lexists("RAM/error_rate"):
message += os.popen("cat RAM/error_rate").read() + "<br>"
except: # noqa do not care if this is failing
os.write(ferr, bytes("Ping error " + str(traceback.print_exc()) + "\n", encoding='utf8'))
try:
os.close(fd)
except FileError:
os.write(ferr, bytes("File Error: " + str(traceback.print_exc()) + "\n", encoding='utf8'))
html = """ <html>[DA]</html>"""
if holdoff_t < (time.time() - 3600): # wait for one hour
stat = open("RAM/" + hw_addr, "w")
stat.write(html.replace(u"[DA]", message))
os.system("curl -s -X DELETE \"https://filebin.net/ehf5e4bfzof8m18m/" + hw_addr + ".html\"")
tmp = "-s -X POST \"https://filebin.net/ehf5e4bfzof8m18m/" + hw_addr + ".html\""
tmp += " -d @RAM/" + hw_addr
# os.write(ferr, "curl " + tmp + "\n")
stat.close()
res = os.popen("curl " + tmp).read()
if res.find("Insufficient storage") != -1:
os.write(ferr, b"Holdoff time in effect, will re-ping in one hour.\n")
holdoff_t = time.time()
# sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
# sock.sendto(message, (socket.gethostbyname("lappy.asuscomm.com"), 59999))
# #sock.close()
except NameError:
os.write(ferr, bytes("unable to ping, network error\t" + time.ctime() + "\n", "utf8"))
traceback.print_exc(ferr)
# READ AVAIL SENSOR DATA
def update_sensors():
try:
with open("sensors", "r") as fd:
for each in fd.readlines():
sensor_unit = each.split(":")
sensor_id = sensor_unit[0]
sensor_unit.pop(0)
tmp = {}
for sensor in sensor_unit:
dat = sensor.split(";")
tmp[dat[0]] = dat[1]
sensor_dict[sensor_id] = tmp
try:
device.sensor_temp = float(sensor_dict["91"]["temperature"])
device.sensor_humid = int(sensor_dict["91"]["humidity"])
device.airdata_inst.humid = float(device.sensor_humid) / 100
except KeyError:
pass
try:
device.inside = float(sensor_dict["92"]["temperature"])
device.inside_humid = int(sensor_dict["92"]["humidity"])
# device.inside_humid += 5 +(75-device.inside_humid)/10 use if sensor has incorrect tuning
except KeyError:
pass # device.msg +="\nerror on sensor 92"
try:
device.sensor_exhaust = float(sensor_dict["94"]["temperature"])
except KeyError:
pass # device.msg +="\nerror on sensor 94"
except IndexError:
device.msg += "\nnew sensor data error"
traceback.print_exc()
# WRITE TO DATA.LOG
def logger():
try:
with open("./RAM/data.log", "a+") as fdo:
# +str(device.extract_humidity*100)\
cmd = "" \
+ str(time.time()) \
+ ":" \
+ str(device.sensor_temp) \
+ ":" \
+ str(round(device.extract_ave, 2)) \
+ ":" \
+ str(round(device.sensor_humid, 2)) \
+ ":" \
+ str(round(device.humidity, 2)) \
+ ":" \
+ str(round(device.inlet_ave, 2)) \
+ ":" \
+ str(round(device.exhaust_ave, 2)) \
+ ":" \
+ str(round(device.supply_ave, 2)) \
+ ":" \
+ str(round(device.local_humidity, 2)) \
+ ":" \
+ str(device.inside) \
+ ":" \
+ str(round(numpy.average(device.cond_data), 1)) \
+ ":" + str(device.inside_humid) \
+ ":" + str(device.moist_in) \
+ ":" + str(device.moist_out) \
+ ":" + str(device.humidity_diff)
fdo.write(cmd + "\n")
except FileError:
traceback.print_exc(ferr)
if "homeAss" in sys.argv:
os.system("./ha-httpsensor.py -n ftx_Indoor -u °C -d temperature -v " + str(
round(device.extract_ave, 1)) + ">/dev/null &")
os.system("./ha-httpsensor.py -n ftx_Outside -u °C -d temperature -v " + str(
round(device.inlet_ave, 1)) + ">/dev/null &")
try:
os.system("./ha-httpsensor.py -n ftx_Efficiency -u % -d calculated -v " + str(
round(numpy.average(device.eff_ave), 2)) + ">/dev/null &")
except: # noqa this section is deprecated
traceback.print_exc(ferr)
os.system(
"./ha-httpsensor.py -n ftx_Humidity -d humidity -u % -v " + str(int(device.humidity)) + ">/dev/null &")
os.system(
"./ha-httpsensor.py -n ftx_ExtractFan -d fanspeed -u rpm -v " + str(int(device.ef_rpm)) + ">/dev/null &")
# PRINT COMM SETTING
def display_settings():
clear_screen()
print(str(req.client).replace(",", "\n"))
# CLEAR WHATS ON SCREEN AND RETURN TO UPPER LEFT
def clear_screen():
if "daemon" in sys.argv:
os.lseek(fout, 0, 0)
os.ftruncate(fout, 0)
os.fsync(fout)
else:
print(chr(27) + "[2J\x1b[H")
##############################################
class FileError(Exception):
"""Custom file exception"""
pass
# ####################################################################
start = time.time() # START TIME
sys.stdout.flush()
# ########### DEVICE CLASS FOR SYSTEMAIR #############################
def check_req(request, test, name):
if request.response != test:
if request.latest_request_mode == "Single":
request.modbusregister(request.latest_request_address,
request.latest_request_decimals)
if request.response != test:
os.write(ferr, bytes(f"Retrieved value for {name}={request.response},"
f" but airiana was set to {test}, data updated."
f"\t{time.ctime(time.time())}\n", "utf-8"))
return False # Return False as second request has been made and test is still false.
return True # Return True as response test is valid after re-read.
return True # Return True as response test is valid.
class Systemair(object):
def __init__(self, request_object):
self.used_energy = None
self.eff = None
self.coef_prev_inlet = None
self.shower_initial = None
self.initial_fanspeed = None
self.req = request_object
self.savecair = False
self.elec_now = 0
self.showerRH = None
self.initial_temp = None
self.fanspeed = -1
self.system_types = {0: "VR400", 1: "VR700", 2: "VR700DK", 3: "VR400DE", 4: "VTC300", 5: "VTC700",
12: "VTR150K", 13: "VTR200B", 14: "VSR300", 15: "VSR500", 16: "VSR150",
17: "VTR300", 18: "VTR500", 19: "VSR300DE", 20: "VTC200", 21: "VTC100"}
self.has_RH_sensor = ["VTR300", "VSR300", "savecair"]
self.rotor_states = {0: "Normal", 1: "Rotor Fault", 2: "Rotor Fault Detected",
3: "Summer Mode transitioning", 4: "Summer Mode",
5: "Leaving Summer Mode", 6: "Manual Summer Mode",
7: "Rotor Cleaning in Summer Mode", 8: "Rotor cleaning in manual summer mode",
9: "Fans off", 10: "Rotor Cleaning during fans off",
11: "Rotor Fault, but conditions normal"}
self.speeds = {0: "Off", 1: "Low", 2: "Normal", 3: "High", 4: "undefined"}
self.AC_energy = 0
self.ac_active = False
self.avg_frame_time = 1
self.coef_new = 0
self.coef_prev_supply = 0
self.coef_fanspeed = 0
self.rawdata = []
self.press_inhibit = 0
self.local_humidity = 0.0
self.eff_ave = [90]
self.diff_ave = [0]
self.total_energy = 0.0
self.average_limit = 1800 # min122
self.cooling_limit = 16
self.sf = 20
self.ef = 20
self.sf_base = 20
self.ef_base = 20
self.ef_rpm = 1500
self.sf_rpm = 1500
self.inlet = []
self.inlet_ave = 0
self.supply = []
self.supply_ave = 0
self.extract = []
self.extract_ave = 0.0
self.electric_power = 1
self.flowOffset = [0, 0]
self.filter_raw = 0
self.house_heat_limit = 8
self.humidity_target = 0
self.exhaust = []
self.exhaust_ave = 0
self.supply_power = 0
self.extract_power = 0
self.extract_combined = 0
self.gain = 0
self.loss = 0
self.register = {}
self.kinetic_compensation = 0
self.starttime = time.time()
self.timer = 0
self.defrost = False
self.current_mode = 0
self.extract_humidity = 0.40 # relative humidity
self.extract_humidity_comp = 0.00 # relative humidity re compensated
self.humidity_diff = 0
self.condensate_compensation = 0
self.filter_remaining = 0
self.cond_eff = 1
self.dur = 1.0
self.extract_dt = 0.0
self.update_airdata_instance()
self.shower = False
self.det_limit = 0
self.dyn_coef = 0
self.msg = ""
self.inside = 0
self.inside_humid = 0
self.exchanger_mode = -1
self.reset_fans = False
self.rotor_state = 0
self.rotor_active = "Yes"
self.inhibit = time.time()
self.integral_forcast = 0
self.system_name = ""
self.sensor_temp = 0
self.sensor_humid = 0
self.modetoken = 0
self.cooling = 0
self.forecast = [-1, -1, -1]
self.dt_hold = 0
self.dt_entries = 0
self.extract_dt_long_time = time.time()
self.iter = 1
self.extract_dt_long = 0
self.cool_mode = False
self.temps = []
self.temp_state = 0
self.condensate = 0
self.coef = 0.17
self.coef_prev_temp = 0
self.new_coef = 0
self.tcomp = 0
self.inlet_coef = 0.1
self.filter = 0
self.filter_limit = 0
self.cond_data = []
self.cond_valid = False
self.cond_dev = 0
self.i_diff = []
self.time = []
self.extract_dt_list = [0]
self.humidity_comp = 0
self.pressure_diff = 0
self.prev_static_temp = 8
self.indoor_dewpoint = 0
self.target = 22
self.tomorrows_low = [0, 0, 0, 0, 0]
self.energy_diff = 0
self.humidity = 40.0
self.moist_in = 0
self.moist_out = 0
self.monitoring = True
self.div = 0
self.set_system_name()
self.RH_valid = 0
self.hum_list = []
self.status_field = [-1, self.exchanger_mode, 0, self.system_name, vers,
os.popen("git log --pretty=format:'%h' -n 1").read(), 0, self.inlet_ave, self.extract_ave,
self.ef, self.humidity, 0, self.cool_mode, self.supply_ave, self.exhaust_ave,
self.pressure_diff, self.det_limit]
self.heater = 0
self.exchanger_speed = 0
self.unit_comp = []
self.coef_dict = {0: {}, 1: {}, 2: {}, 3: {}}
self.coef_test_bool = False
self.coef_inhibit = time.time()
self.sensor_exhaust = -60
self.admin_password = ""
self.electric_power_sum = 0.0
def set_monitoring(self, val):
self.inhibit = 0
self.press_inhibit = 0
self.modetoken = 0
self.monitoring = val
def reset_fanspeed(self, speed):
self.reset_fans = speed
def get_password(self):
self.req.modbusregister(16000, 0)
self.admin_password = "{0}{1}{2}{3}".format(str(self.req.response & 0b1),
str(self.req.response & 0b1000 >> 3),
str(self.req.response & 0b10000000 >> 7),
str(self.req.response & 0b100000000000 >> 11))
def system_setup(self):
try:
if os.path.isfile("coeficients.dat"):
self.coef_dict = pickle.load(open("coeficients.dat", "rb"))
else:
pickle.dump(self.coef_dict, open("coeficients.dat", "wb"))
except EOFError:
traceback.print_exc(ferr)
pickle.dump(self.coef_dict, open("coeficients.dat", "wb"))
if self.savecair:
self.get_password()
self.req.write_register(1400, 16)
self.req.write_register(1401, 16)
self.req.write_register(1402, 20)
self.req.write_register(1403, 20)
self.req.write_register(1404, 50)
self.req.write_register(1405, 50)
self.req.write_register(1406, 90)
self.req.write_register(1407, 90)
self.req.write_register(1408, 100)
self.req.write_register(1409, 100)
else:
self.get_heater()
# make sure the electric heater is oFF
if self.heater != 0:
self.set_heater(0)
# check if there is an RH sensor available even though it's not listed
self.get_RH()
if self.RH_valid and self.system_name not in self.has_RH_sensor:
self.has_RH_sensor.append(self.system_name)
# setup airflow levels
if self.system_name in ("VR400", "VTR300",):
self.ef_base = 40 # base low flow, low pressure reference air flow.
self.sf_base = 40
self.req.modbusregister(137, 0)
if int(self.req.response) == 1:
self.req.write_register(137, 0)
self.req.modbusregister(107, 0)
if int(self.req.response) == 1:
self.req.write_register(107, 0)
# SET BASE FLOW RATES
self.req.write_register(101, self.sf_base)
self.req.write_register(102, self.ef_base)
self.req.write_register(103, 60)
self.req.write_register(104, 60)
self.req.write_register(105, 107)
self.req.write_register(106, 107)
if self.system_name in "VSR300":
self.ef_base = 40 # base low flow, low pressure reference air flow.
self.sf_base = 40
self.req.modbusregister(137, 0)
if int(self.req.response) == 1:
self.req.write_register(137, 0)
self.req.modbusregister(107, 0)
if int(self.req.response) == 1:
self.req.write_register(107, 0)
# SET BASE FLOW RATES
self.req.write_register(101, self.sf_base)
self.req.write_register(102, self.ef_base)
self.req.write_register(103, 60)
self.req.write_register(104, 60)
self.req.write_register(105, 107)
self.req.write_register(106, 107)
if "VTR700" in self.system_name:
self.ef_base = 50 # base low flow, low pressure reference air flow.
self.sf_base = 50
self.req.modbusregister(137, 0)
if int(self.req.response) == 1:
self.req.write_register(137, 0)
self.req.modbusregister(107, 0)
if int(self.req.response) == 1:
self.req.write_register(107, 0)
# SET BASE FLOW RATES
self.req.write_register(101, self.sf_base)
self.req.write_register(102, self.ef_base)
self.req.write_register(103, 100)
self.req.write_register(104, 100)
self.req.write_register(105, 200)
self.req.write_register(106, 200)
# get heater status
def get_heater(self):
if not self.savecair:
self.req.modbusregister(200, 0)
check_req(self.req, self.heater, "electric_heater")
self.heater = int(self.req.response)
else:
self.heater = 0
# set heater status
def set_heater(self, heater):
if not self.savecair:
self.req.write_register(200, heater)
# get and set the Unit System name, from system types dict
def set_system_name(self):
if not self.savecair:
self.req.modbusregister(500, 0)
self.system_name = self.system_types[self.req.response]
# get the coef mode, for dict matching
def get_coef_mode(self):
operating_mode = 0
if self.exchanger_mode == 5 and self.exchanger_speed == 100:
operating_mode += 1
if self.sf != self.ef:
operating_mode += 2
return operating_mode
# calculate a new coef if fanspeed change renders high dt values //UNused
def coef_debug(self):
if self.fanspeed == 3 and not self.coef_test_bool and self.inhibit and not self.shower:
self.press_inhibit = time.time()
self.modetoken = time.time() - 3000
fd = open("coeficients.dat", "rb")
self.coef_dict = pickle.load(fd)
fd.close()
self.coef_test_bool = True
self.coef_prev_temp = 0
for each in self.rawdata:
self.coef_prev_temp += float(each[1]) / 10
self.coef_prev_temp = self.coef_prev_temp / len(self.rawdata)
self.coef_prev_inlet = self.inlet_ave
if (self.inhibit == 0 or self.fanspeed == 2) and self.coef_test_bool:
temp = 0
for each in self.rawdata:
temp += float(each[1]) / 10
temp = temp / len(self.rawdata)
temp_diff = (float((self.rawdata[-1][1]) / 10) - self.coef_prev_inlet)
delta = (self.coef_prev_temp - temp)
new_coef = delta / temp_diff
os.system("echo \"newCoef:" + str(new_coef) + "\nAmbientDiff:" + str(temp_diff) + "\" >> newCoef.txt")
os.system("echo \"delta:" + str(delta) + " list:" + str(self.get_coef_mode()) + "\ntemp:" + str(
temp) + " prev_tmp:" + str(self.coef_prev_temp) + "\n\" >> newCoef.txt")
try:
keys = list(self.coef_dict[self.get_coef_mode()].keys())
except KeyError:
keys = []
if int(temp_diff) not in keys:
self.coef_dict[self.get_coef_mode()][int(temp_diff)] = new_coef
else:
# add 10% of diff from new coef to dict if already tested and rerun
self.coef_dict[self.get_coef_mode()][int(temp_diff)] += (new_coef -
self.coef_dict[self.get_coef_mode()][
int(temp_diff)]) * 0.1
if len(self.coef_dict) != 0:
pickle.dump(self.coef_dict, open("coeficients.dat", "wb"))
self.coef_test_bool = False
self.set_fanspeed(1)
# Get relative humidity from internal sensor, valid units in self.has_RH_sensor tuple
def get_RH(self):
if "noRH" in sys.argv:
self.RH_valid = 0
return 0
if not self.savecair:
self.req.modbusregister(382, 0)
self.RH_valid = int(self.req.response)
if self.RH_valid:
self.req.modbusregister(380, 0)
self.humidity = float(self.req.response)
else:
self.req.modbusregister(12135, 0)
if self.req.response != 0:
self.RH_valid = 1
self.humidity = float(self.req.response)
if self.RH_valid:
self.hum_list.insert(0, self.humidity)
if len(self.hum_list) > self.average_limit:
self.hum_list.pop(-1)
try:
# if an update of the humidity value on the sensor exceeds 2 points reuse last known value
if abs(self.humidity - self.hum_list[1]) > 2:
self.humidity = self.hum_list[1]
self.hum_list[0] = self.humidity
except IndexError:
pass
# get the nr of days used and alarm lvl for filters
def get_filter_status(self):
if not self.savecair:
self.req.modbusregister(600, 0)
self.filter_limit = int(self.req.response) * 31
self.req.modbusregister(601, 0)
self.filter = self.req.response
try:
self.filter_remaining = round(100 * (1 - (float(self.filter) / self.filter_limit)), 1)
except (ValueError, ZeroDivisionError):
traceback.print_exc(ferr)
if self.filter_remaining < 0:
self.filter_remaining = 0
else:
self.req.modbusregister(7000, 0)
self.filter_limit = int(self.req.response) * 30
self.req.modbusregister(7004, 0)
lowend = self.req.response
self.req.modbusregister(7005, 0)
highend = self.req.response << 16
self.filter_raw = lowend + highend
self.filter = self.filter_limit - (lowend + highend) / (3600 * 24)
try:
self.filter_remaining = round(100 * (1 - (float(self.filter) / self.filter_limit)), 1)
except ZeroDivisionError:
traceback.print_exc(ferr)
if self.filter_remaining < 0:
self.filter_remaining = 0
# get status byte for temp probes
def get_temp_status(self):
if not self.savecair:
self.req.modbusregister(218, 0)
self.temp_state = self.req.response
def print_attributes(self):
for each in dir(self):
obj = None
exec(str("obj = self." + each))
if isinstance(obj, (int, float, str, list)) or True:
exec(str("print (each, self." + each + ")"))
if "daemon" not in sys.argv:
input("press enter to resume")
else:
print("break")
os.system("sleep 2")
def get_fanspeed(self):
if not self.savecair:
self.req.modbusregister(100, 0)
check_req(self.req, self.fanspeed, "fanspeed")
self.fanspeed = int(self.req.response)
return self.fanspeed
else:
self.req.modbusregister(1130, 0)
self.req.response -= 1
check_req(self.req, self.fanspeed, "fanspeed")
self.req.modbusregister(1130, 0)
if self.req.response <= 0:
self.fanspeed = 0
else:
self.fanspeed = self.req.response - 1
return self.fanspeed
def update_temps(self):
if not self.savecair:
self.req.modbusregisters(213, 5) # Temp sensors 1 -5
self.time.insert(0, time.time())
if len(self.time) > self.average_limit:
self.time.pop(-1)
# NEGATIVE VAL sign bit twos complement
if self.req.response[4] > 6000:
self.req.response[4] -= 0xFFFF
if self.req.response[2] > 6000:
self.req.response[2] -= 0xFFFF
self.temps = self.req.response[:]
self.rawdata.insert(0, self.temps)
if len(self.rawdata) > self.average_limit:
self.rawdata.pop(-1)
# self.request.response[1] #EXTRACT
# self.request.response[2] #EXHAUST
# self.request.response[0] #Supply pre elec heater
# self.request.response[3] #Supply post electric heater
# self.request.response[4] Inlet
# update [4] with inlet coef
self.req.response[4] -= (self.req.response[1] - self.req.response[
4]) * self.inlet_coef # inlet compensation exchanger OFF/ON
# update [1] with tcomp, after calc of [4]
self.tcomp = 10 * self.get_tcomp(float(self.req.response[1]) / 10, float(self.req.response[4]) / 10)
self.req.response[1] += self.tcomp
self.extract.insert(0, float(self.req.response[1]) / 10)
self.exhaust.insert(0, float(self.req.response[2]) / 10)
self.supply.insert(0, float(self.req.response[3]) / 10)
self.inlet.insert(0, float(self.req.response[4]) / 10)
# limit array size
for each in [self.inlet, self.supply, self.extract, self.exhaust]:
if len(each) > self.average_limit:
each.pop(-1)
else: # self.savecair SECTION
self.time.insert(0, time.time())
# EXTRACT
extract = "no data"
cnt = 0
while extract == "no data" and cnt < 10:
self.req.modbusregister(12543, 1)
extract = self.req.response
try: # replace erroneous data input when temp diff exceeds 1C between samples
if extract - self.rawdata[0][1] > 50 and (extract != 0.0 or self.rawdata[1][1] != 0.0):
os.write(ferr, bytes("temp read error at: " + str(extract) + "C \t" + str(time.ctime()) + "\n",
encoding='utf8'))
extract = self.rawdata[1][1]
except IndexError:
pass
except TypeError:
os.write(ferr, bytes("temp read type error at: " + str(extract) + "C \t" + str(time.ctime()) + "\n",
encoding='utf8'))
traceback.print_exc(ferr)
extract = self.rawdata[1][1]
pass
self.req.modbusregister(12102, 1)
supply = self.req.response
self.req.modbusregister(12101, 1)
inlet = self.req.response
# self.request.response[1] #EXTRACT
# self.request.response[2] #EXHAUST
# self.request.response[0] #Supply pre elec heater
# self.request.response[3] #Supply post electric heater
# self.request.response[4] Inlet
self.rawdata.insert(0, (0, extract * 10, 0, supply * 10, inlet * 10))
if len(self.rawdata) > self.average_limit:
self.rawdata.pop(-1)
self.tcomp = self.get_tcomp(extract, inlet)
self.extract.insert(0, float(extract + self.tcomp))
# SUPPLY
self.supply.insert(0, float(supply))
# INLET
# if self.rotor_active =="No" and self.inlet_coef <0.03:self.inlet_coef+= 0.0001 #OFF
# if self.rotor_active =="Yes" and self.inlet_coef >0.00:self.inlet_coef-= 0.0001 # ON
tweak = 0
try:
inlet_comp = ((float(3200) / self.sf_rpm) - 1) * 0.01
tweak = (extract - inlet) * inlet_comp # inlet compensation exchanger OFF/ON
except ZeroDivisionError:
pass
self.inlet.insert(0, float(inlet - tweak))
if len(self.extract) > self.average_limit:
self.extract.pop(-1)
if len(self.exhaust) > self.average_limit:
self.exhaust.pop(-1)
if len(self.supply) > self.average_limit:
self.supply.pop(-1)
if len(self.inlet) > self.average_limit:
self.inlet.pop(-1)
if len(self.time) > self.average_limit:
self.time.pop(-1)
try:
self.eff = (self.supply_ave - self.inlet_ave) / (self.extract_ave - self.inlet_ave) * 100
except ZeroDivisionError:
self.eff = 100
self.eff_ave.insert(0, self.eff)
if len(self.eff_ave) > self.average_limit:
self.eff_ave.pop(-1)
# Return the Tcomp temperature offset for extraction temps
def get_tcomp(self, extract, inlet):
tcomp = 0
try:
diff = extract - inlet
dyn_coef = 0
try:
if self.fanspeed and len(self.coef_dict[self.get_coef_mode()]) != 0:
dyn_coef = (numpy.median(list(self.coef_dict[self.get_coef_mode()].values()))
* float(1) / self.fanspeed)
# self.dyn_coef #float(7*34)/self.sf
# compensation (heat transfer from duct) + (supply flow component)
if self.fanspeed == 3:
dyn_coef = 0
except KeyError:
if len(self.coef_dict):
dyn_coef = numpy.average(list(self.coef_dict[self.get_coef_mode()].values()))
if numpy.isnan(dyn_coef):
dyn_coef = 0
except ZeroDivisionError:
traceback.print_exc(ferr)
if dyn_coef != self.new_coef:
self.new_coef += 0.0001 * (dyn_coef - self.new_coef)
if abs(dyn_coef - self.new_coef) < 0.001:
self.new_coef = dyn_coef
tcomp = diff * -self.new_coef
except ZeroDivisionError:
pass
if numpy.isnan(tcomp):
return 0
return tcomp
def set_fanspeed(self, target_fanspeed):
self.inhibit = time.time()
self.coef_inhibit = time.time()
if target_fanspeed != self.fanspeed: # add one to bucket
self.status_field[0] += 1
os.write(ferr,
bytes("Changing fanspeed to:" + str(target_fanspeed) + " \t\t"
+ str(time.ctime()) + "\n", encoding = 'utf8'))
# print actual,"->",target
if target_fanspeed >= 4:
target_fanspeed = 0
if target_fanspeed < 0:
target_fanspeed = 0
if not self.savecair:
self.req.write_register(100, target_fanspeed)
self.fanspeed = target_fanspeed
else:
if target_fanspeed == 0:
self.req.write_register(1130, target_fanspeed)
self.fanspeed = target_fanspeed
else:
self.req.write_register(1130, target_fanspeed + 1)
self.fanspeed = target_fanspeed
if self.get_fanspeed() != target_fanspeed:
os.write(ferr,
bytes("Incorrectly set fanspeed " + str(self.get_fanspeed())
+ " to " + str(target_fanspeed) + " \t" + str(time.ctime()) + "\n", encoding='utf8'))
self.update_airflow()
def update_fan_rpm(self):
if not self.savecair:
self.req.modbusregisters(110, 2)
self.sf_rpm, self.ef_rpm = self.req.response[0], self.req.response[1]
try:
if self.system_name in ("VR400"):
self.electric_power = (
self.ef_rpm / (100 / (float(float(self.ef_rpm) / 1381) ** 1.89)) + self.sf_rpm / (
100 / (float(float(self.sf_rpm) / 1381) ** 1.89)))
if self.system_name in ("VSR300"):
self.electric_power = 0.2 * (
self.ef_rpm / (100 / (float(float(self.ef_rpm) / 1381) ** 1.89)) + self.sf_rpm / (
100 / (float(float(self.sf_rpm) / 1381) ** 1.89)))
if self.system_name in ("VTR300"):
self.electric_power = 0.2 * (
self.ef_rpm / (100 / (float(float(self.ef_rpm) / 1381) ** 1.89)) + self.sf_rpm / (
100 / (float(float(self.sf_rpm) / 1381) ** 1.89)))
except ZeroDivisionError:
self.electric_power = 0
if "Yes" in self.rotor_active: self.electric_power += 10 # rotor motor 10Watts
self.electric_power += 5 # controller power
else:
self.req.modbusregister(12400, 0)
self.sf_rpm = self.req.response
self.req.modbusregister(12401, 0)
self.ef_rpm = self.req.response
try:
self.electric_power = 3.404 * math.exp(0.001 * self.ef_rpm) + 3.404 * math.exp(0.001 * self.sf_rpm)
except ZeroDivisionError:
self.electric_power = 0
if "Yes" in self.rotor_active: self.electric_power += 10 # rotor motor 10Watts
self.electric_power += 5 # controller board power
if self.elec_now != 0: # integral of the electric power used by fans and controller
self.electric_power_sum += (self.electric_power * (time.time() - self.elec_now)) / 3600
self.elec_now = time.time()
def update_fanspeed(self):
self.fanspeed = self.get_fanspeed()
def update_airflow(self):
if not self.savecair:
self.req.modbusregisters(101, 6)
sf = [self.req.response[0], self.req.response[2], self.req.response[4]]
ef = [self.req.response[1], self.req.response[3], self.req.response[5]]
tmp = self.fanspeed # self.get_fanspeed()
if tmp <= 0: tmp = 1
self.sf = sf[tmp - 1]
self.ef = ef[tmp - 1]
if self.fanspeed == 0:
self.ef = 0
self.sf = 0
else:
self.req.modbusregister(14000, 0)
self.sf = int(self.req.response)
self.req.modbusregister(14001, 0)
self.ef = int(self.req.response)
def update_airdata_instance(self):
self.airdata_inst = airdata.Energy()