-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheater_control.py
More file actions
executable file
·771 lines (708 loc) · 28.8 KB
/
heater_control.py
File metadata and controls
executable file
·771 lines (708 loc) · 28.8 KB
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
#!/usr/bin/env python3
import minimalmodbus
import time, json, signal, os, logging, traceback, sys, copy
import paho.mqtt.client as mqtt
from pathlib import Path
from dataclasses import dataclass
from dataclasses_json import dataclass_json
from threading import Event, Thread
from typing import *
from ctypes import c_uint16
from enum import Enum, IntEnum, unique
from functools import reduce
@unique
class KP(IntEnum):
ACT = 0x40
UP = 0x1C
LFT = 0x36
ENT = 0x24
RHT = 0X16
DWN = 0x26
BAK = 0x1E
@unique
class DS(Enum):
TEMP = (0x7873, 0x0000)
OCC = (0x3f58, 0x5800)
SAVE = (0x6d77, 0x1c79)
YES = (0x6e79, 0x6d00)
NO = (0x543f, 0x0000)
FYES = (0x716e, 0x796d)
SUCC = (0x6d1c, 0x5858)
ERR = (0x7950, 0x5000)
@unique
class EParams(IntEnum):
temperature = 0
set_point = 1
filter_ratio = 2
hysteresis = 3
start_time = 4
occ_cold_time = 5
occupancy = 6
save = 7
@unique
class RepeatSt(IntEnum):
ButtonRest = 1
ButtonDown = 2
ButtonRepeat = 3
ButtonDownDown = 4
""" set point hacking is named after seconds hacking in watch movements """
@unique
class ParamValSt(IntEnum):
Param = 1
Value = 2
HackSetPoint = 3
Save = 4
@unique
class OccSt(IntEnum):
cold = 0
hot = 1
warm = 2
class ButtonRepeatSM:
def __init__(self, initial_dly = 9, repeat_dly = 2):
self.state = RepeatSt.ButtonRest
self.last_kc = 0
self.time = c_uint16(0)
self.initial_dly = initial_dly
self.repeat_dly = repeat_dly
def run(self, cycle, keycode):
button_down = keycode & KP.ACT
if button_down and keycode != self.last_kc:
logging.debug(f"Key Pressed: {KP(keycode^KP.ACT).name}")
self.last_kc = keycode
""" transitions """
match self.state:
case RepeatSt.ButtonRest:
if (button_down != 0):
self.state = RepeatSt.ButtonDown
self.time = copy.copy(cycle)
case RepeatSt.ButtonDown:
if (button_down == 0):
self.state = RepeatSt.ButtonRest
elif self.last_kc != keycode:
self.state = RepeatSt.ButtonDown
self.time = copy.copy(cycle)
elif c_uint16(cycle.value - self.time.value).value >= self.initial_dly:
self.state = RepeatSt.ButtonRepeat
case RepeatSt.ButtonRepeat:
if button_down == 0:
self.state = RepeatSt.ButtonRest
elif self.last_kc != keycode:
self.state = RepeatSt.ButtonDown
self.time = copy.copy(cycle)
else:
self.state = RepeatSt.ButtonDownDown
self.time = copy.copy(cycle)
case RepeatSt.ButtonDownDown:
if button_down == 0:
self.state = RepeatSt.ButtonRest
elif self.last_kc != keycode:
self.state = RepeatSt.ButtonDown
self.time = copy.copy(cycle)
elif c_uint16(cycle.value - self.time.value).value >= self.repeat_dly:
self.state = RepeatSt.ButtonRepeat
""" output """
if self.state == RepeatSt.ButtonRepeat:
return keycode ^ KP.ACT
return keycode
class OccSm:
def __init__(self, cold_dly = 30):
self.state = OccSt.cold
self.last_state = OccSt.cold
self.time = c_uint16(0)
self.cold_dly = cold_dly
def run(self, cycle, data):
match self.state:
case OccSt.cold:
""" higher threshold to mark the space occupied """
if sum(data.values()) > 1:
self.state = OccSt.hot
case OccSt.hot:
if sum(data.values()) < 1:
self.state = OccSt.warm
self.time = copy.copy(cycle)
case OccSt.warm:
""" mark the space cold if no motion recorded for a while """
if sum(data.values()) > 0:
self.state = OccSt.warm
self.time = copy.copy(cycle)
elif c_uint16(cycle.value - self.time.value).value >= self.cold_dly * 600:
self.state = OccSt.cold
if self.state != self.last_state:
logging.info(f"Space occupancy is now {self.state.name}")
self.last_state = self.state
if self.state == OccSt.cold:
return False
return True
@dataclass_json
@dataclass
class Temp_Item:
name7seg: Tuple[int, int]
val: int
decimal: int
hi_lim: int
lo_lim: int
change_by: int = 1
@dataclass_json
@dataclass
class MQTT:
data_sources: List[str]
temp_source: str
broker: str
port: int
timeout: int
@dataclass_json
@dataclass
class Modbus:
ena: bool
port: str
sid: int
timeout: float
baud: int
@dataclass_json
@dataclass
class BUTTON:
initial_dly: int
repeat_dly: int
@dataclass_json
@dataclass
class DISPLAY:
sp_time: int
sav_time: int
@dataclass_json
@dataclass
class UI:
button: BUTTON
display: DISPLAY
class HC(mqtt.Client):
long_name = "heater_control"
cfg_file_name = "hc_config"
@dataclass_json
@dataclass
class Config:
name: str
comment: str
secret: str
report_overrun: bool
temp: Dict[str, Temp_Item]
"""
must contain:
- set_point
- filter_ratio
- hysteresis
- start_time
- occ_cold_time
"""
ui: UI
mqtt: MQTT
modbus: Modbus
loglevel: Optional[str] = None
exit_evt = Event()
connect_evt = Event()
CHAR_LUT = [
0x3f, 0x06, 0x5b, 0x4f,
0x66, 0x6d, 0x7d, 0x07,
0x7f, 0x6f, 0x77, 0x7c,
0x39, 0x5e, 0x79, 0x71
]
DIGITS = 4
class Temp_IIR:
first_sample_done = False
y = 0.0
a = 0.0
def __init__(self, initial, alpha):
self.first_sample_done = False
self.y = initial
self.a = alpha
def filt(self, x):
self.y = self.a*x + (1.0-self.a)*self.y if self.first_sample_done else x
self.first_sample_done = True
return self.y
class ParamValueSM:
def __init__(self, sp_time = 10, sav_time = 30):
self.state = ParamValSt.Value
self.last_state = ParamValSt.Value
self.param = EParams.temperature
self.last_param = EParams.temperature
self.last_kc = 0
self.time = c_uint16(0)
self.sp_time = sp_time
self.sav_time = sav_time
def run(self, main_cycle, keycode):
fc = 0
""" simplify keycodes """
if (keycode & KP.ACT) and (keycode != self.last_kc):
fc = keycode
fc ^= KP.ACT # since the KP.ACT bit is expected, we can always cancel it
if (fc == KP.RHT):
fc = KP.ENT
elif (fc == KP.LFT):
fc = KP.BAK
# fcs for up and down are omitted
# fcs for enter and back are also omitted
self.last_kc = keycode
""" transitions """
match self.state:
case ParamValSt.Param:
if fc == KP.UP:
if (self.param == 0):
self.param = len(EParams) - 1
else:
self.param -= 1
if fc == KP.DWN:
self.param += 1
if (self.param >= len(EParams)):
self.param = 0
if fc == KP.ENT:
if self.param != EParams.save:
self.state = ParamValSt.Value
else:
self.state = ParamValSt.Save
self.time = copy.copy(main_cycle)
if fc == KP.BAK:
self.param = EParams.temperature
case ParamValSt.Value:
if fc == KP.BAK:
self.state = ParamValSt.Param
if self.param == EParams.temperature and (fc == KP.UP or fc == KP.DWN):
self.state = ParamValSt.HackSetPoint
self.time = copy.copy(main_cycle)
case ParamValSt.HackSetPoint:
if fc == KP.BAK:
self.state = ParamValSt.Param
if fc == KP.UP or fc==KP.DWN:
self.time = copy.copy(main_cycle)
if c_uint16(main_cycle.value - self.time.value).value > self.sp_time:
self.state = ParamValSt.Value
case ParamValSt.Save:
if c_uint16(main_cycle.value - self.time.value).value > self.sav_time:
self.state = ParamValSt.Param
""" debug display """
if self.last_state != self.state:
logging.debug(f"Scrolling {self.state.name}")
self.last_state = self.state
if self.last_param != self.param:
logging.debug(f"Param on {EParams(self.param).name}")
self.last_param = self.param
""" output """
match self.state:
case ParamValSt.Param:
return (self.param, False)
case ParamValSt.Value:
return (self.param, True)
case ParamValSt.HackSetPoint:
return (EParams.set_point, True)
case ParamValSt.Save:
return (self.param, True)
def process_temp(self, editing = False):
hysteresis = self.config.temp["hysteresis"].val
"""Determine heater on/off command"""
if (self.start_cycle == True):
self.low_point = self.config.temp["set_point"].val - hysteresis // 2
else:
self.low_point = self.config.temp["set_point"].val - hysteresis
self.high_point = self.config.temp["set_point"].val
""" The filtered value is expressed as whole degrees """
""" The measured temperature is expressed as thousandths of a degree"""
if self.fil.y > (self.high_point / 10.0):
self.heater_on = 0
elif (self.meas_temp // 100) < self.low_point:
self.heater_on = 1
if not editing:
"""Build our response message"""
final_heater_on = int(self.heater_on and (self.focc or self.occ))
self.checkup_msg.update({"HeaterControl Fil Temp": int(round(self.fil.y * 1000.0)),
"HeaterControl Set High": self.high_point * 100,
"HeaterControl Set Low": self.low_point * 100,
"HeaterControl Start Cycle": int(self.start_cycle),
"HeaterControl Temp On": self.heater_on,
"HeaterControl F Occu": int(self.focc),
"HeaterControl Occu": int(self.occ),
"HeaterControl On": final_heater_on})
self.last_final_heater_on = final_heater_on
self.checkup_pub = True
def signal_handler(self, signum, _):
"""signal handling helper function"""
logging.critical(f"Caught a deadly signal: {signal.Signals(signum).name}")
self.exit_evt.set()
def __init__(self):
files = []
my_path = os.path.dirname(os.path.abspath(__file__))
logging.debug(f"Program installed at {my_path}")
if my_path.startswith("/usr"):
new_path = f"/etc/{HC.long_name}"
files = [new_path, f"{Path.home()}{os.sep}.config{os.sep}{HC.long_name}"]
else:
paths = [f"{Path.home()}{os.sep}.config{os.sep}{HC.long_name}", my_path]
for path in paths:
file = f"{path}{os.sep}{HC.cfg_file_name}.json"
logging.debug(f"Attempting to read {file}")
if not Path(file).is_file():
continue
with open(file, "r") as configFile:
logging.info(f"Reading Config File")
self.config = HC.Config.from_json(configFile.read())
self.active_config_file = file
logging.debug(f"{self.config}")
break
else:
raise FileNotFoundError("Not able to locate configuration file.")
""" check if temp has the right items """
assert reduce(lambda a, b : a and (b in self.config.temp),
["set_point", "filter_ratio", "hysteresis", "start_time", "occ_cold_time"],
True)
""" log levels """
try:
if type(logging.getLevelName(self.config.loglevel.upper())) is int:
logging.basicConfig(level=self.config.loglevel.upper())
else:
logging.warning("Log level not configured. Defaulting to WARNING.")
except (KeyError, AttributeError) as e:
logging.warning("Log level not configured. Defaulting to WARNING. Caught: " + str(e))
logging.info("Starting MQTT")
super().__init__(mqtt.CallbackAPIVersion.VERSION2, self.config.name)
def on_log(self, client, userdata, level, buf):
if level == mqtt.MQTT_LOG_DEBUG:
logging.debug("PAHO MQTT DEBUG: " + buff)
elif level == mqtt.MQTT_LOG_INFO:
logging.info("PAHO MQTT INFO: " + buff)
elif level == mqtt.MQTT_LOG_NOTICE:
logging.info("PAHO MQTT NOTICE: " + buff)
elif level == mqtt.MQTT_LOG_WARNING:
logging.warning("PAHO MQTT WARN: " + buff)
else:
logging.error("PAHO MQTT ERROR: " + buff)
def on_connect(self, client, userdata, flags, rc, properties):
"""subscribes to the relevant channels"""
if rc.is_failure:
logging.warning(f"Temporarily failed to connect: {rc}.")
else:
logging.info(f"Connected: {str(rc)}")
for src in self.config.mqtt.data_sources:
self.subscribe(src)
self.connect_evt.set()
try:
self.dct.join()
except:
pass
def on_disconnect(self, client, userdata, flags, rc, properties):
""" handles mqtt disconnects """
self.connect_evt.clear()
if rc.is_failure:
logging.warning("Unexpected disconnection. Starting disconnect timer.")
self.dct = Thread(target=self.disconnect_thread)
self.dct.start()
else:
logging.debug("Disconnected gracefully")
# else graceful disconnection, do nothing
def disconnect_thread(self):
""" Sets the exit event if the timeout is not set in time """
logging.debug("Disconnect timer started.")
if not self.connect_evt.wait(self.config.mqtt.timeout*3):
logging.critical("Disconnect timer triggering program exit.")
self.exit_evt.set()
logging.debug("Disconnect timer ended.")
def on_message(self, client, userdata, message):
if message.topic in self.config.mqtt.data_sources:
if (message.topic.endswith("checkup") or message.topic.endswith("event")):
try:
decoded = message.payload.decode('utf-8')
logging.debug(f"Received Message: {decoded}")
has_motion = False
data = json.loads(decoded)
for (key, val) in data.items():
if not key.endswith("Motion"):
continue
has_motion = True
if (not key in self.motion) or val == 1:
self.motion[key] = val
if has_motion:
logging.info(f"Motion Status: {self.motion}")
self.occ = self.occ_sm.run(self.main_cycle, self.motion)
if self.config.mqtt.temp_source in data:
logging.debug(f"Received temperature: {data[self.config.mqtt.temp_source]}")
self.meas_temp = int(data[self.config.mqtt.temp_source])
self.fil.filt(self.meas_temp / 1000.0)
self.process_temp()
except Exception as err:
tb = traceback.format_exc()
logging.warning(f"L {sys._getframe().f_back.f_lineno} Caught exception: {err}\nTraceback:\n{tb}")
elif (message.topic.endswith("checkup_req")):
""" process motion monitoring """
""" yes, there is a state machine in here """
logging.debug("Received checkup req.")
self.occ = self.occ_sm.run(self.main_cycle, self.motion)
self.motion = {}
def handle_modbus(self, fn, *params, **kwparams):
tries = 5
retval = None
while tries > 0:
tries -= 1
try:
retval = fn(*params, **kwparams)
break
except Exception as err:
tb = traceback.format_exc()
logging.warning(f"L {sys._getframe().f_back.f_lineno} Caught exception: {err}\nTraceback:\n{tb}")
self.instr.serial.flush()
self.instr.serial.reset_input_buffer()
if tries <= 0:
raise
return retval
def str27seg(self, s, dig):
rv = [0, 0]
s = s[::-1]
i = self.DIGITS
while i != 0:
""" The rest of this code expects the index to be one less than how
it began. This index is used to calculate the return vector """
i -= 1
""" Calculate inverse index """
inv = self.DIGITS-1 - i
num = 0
try:
""" Use the inverse index to look up the digit at that pos """
num = int(s[inv])
except IndexError:
""" Print digit anyway because it is after or at the
decimal point """
if inv <= dig:
pass
else:
break
""" Compute the 7 segment vector for the display...
There are two digits contained in each rv.
The digit is looked up using the LUT and decimaled if appropriate
then it is shifted into place. """
rv[i // 2] |= ((self.CHAR_LUT[num] | (0x80 if inv == dig else 0))
<< (0 if i % 2 else 8))
return rv
def numedit(self, c_param, c_val, keycode):
""" this function is where the parameters are actually edited """
""" make sure the keycode is current """
if c_val and (self.last_button != keycode) and (keycode & KP.ACT):
""" hacky way to use the KP_ACT as an 'and' mask """
button_code = keycode & (KP.ACT - 1)
""" numerical parameters """
if c_param > EParams.temperature and c_param < EParams.occupancy:
param_name = EParams(c_param).name
item = self.config.temp[param_name]
if button_code == KP.UP:
item.val += item.change_by
if (item.val > item.hi_lim):
item.val = item.hi_lim
logging.info(f"{param_name} inc to {item.val / (10.0 ** item.decimal)}")
elif button_code == KP.DWN:
item.val -= item.change_by
if (item.val < item.lo_lim):
item.val = item.lo_lim
logging.info(f"{param_name} dec to {item.val / (10.0 ** item.decimal)}")
""" temperature processing related params """
if c_param <= EParams.occ_cold_time:
self.start_cycle = True
self.process_temp(True)
else:
self.occ_sm.cold_dly = self.config.temp["occ_cold_time"].val
elif c_param == EParams.occupancy:
""" either button press directions inverts the forced occupancy """
if button_code == KP.UP or button_code == KP.DWN:
self.focc = not self.focc
self.last_button = keycode
"""
The parameter display function takes a parameter index and a boolean.
The boolean value `i_val` when `false` displays the parameter name and
when `true` displays the value.
The parameters are as follows:
0 - temperature
1 - set point
2 - filter ratio
3 - hysteresis
4 - start time
5 - occupancy
6 - save
"""
def param_scroll(self, auto = True, i_param = 1, i_val = True):
rv = [0, 0]
val = True
param = 1
p_n = [0, 0]
p_v = [0, 0]
DIG_PARAM = len(self.config.temp.keys()) + 1
if auto:
param = self.main_cycle.value >> 4
val = bool(param & 0x1)
param >>= 1
param %= DIG_PARAM + 1 # the save is not a regularly displayed parameter
else:
param = i_param
val = i_val
if param <= EParams.temperature:
""" temperature """
p_n = list(DS.TEMP.value)
p_v = (str(self.meas_temp // 10), 2)
elif param < DIG_PARAM:
postParam = param - 1
configKey = list(self.config.temp.keys())[postParam]
configItem = self.config.temp[configKey]
""" set point """
""" filter ratio """
""" hysteresis """
""" start time """
""" occupied cold delay """
p_n = list(configItem.name7seg)
p_v = [str(configItem.val), configItem.decimal]
else:
postParam = param - DIG_PARAM # + 1 - 1
match postParam:
case 0:
""" occupancy """
p_n = list(DS.OCC.value)
""" occupancy display, forced occupancy takes precedence """
if self.focc:
p_v = list(DS.FYES.value)
else:
p_v = list(DS.YES.value) if self.occ else list(DS.NO.value)
case 1:
""" save """
p_n = list(DS.SAVE.value)
p_v = list(DS.SUCC.value) if self.save_success else list(DS.ERR.value)
""" Display either the parameter name or the value """
if val == False:
rv = p_n
else:
if (param < DIG_PARAM):
rv = self.str27seg(*p_v)
else:
rv = p_v
return rv;
def main(self):
"""this is the main function and most of the work in this script"""
nextWait = 0.250;
start = time.monotonic()
last_cycle_overrun = 0
self.main_cycle = c_uint16(0)
""" set signal handlers """
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
""" modbus """
self.instr = minimalmodbus.Instrument(self.config.modbus.port, self.config.modbus.sid)
self.instr.serial.baudrate = self.config.modbus.baud
self.instr.serial.timeout = self.config.modbus.timeout
self.instr.serial.clear_buffers_before_each_transaction = False
""" temperature-based heater control """
self.fil = HC.Temp_IIR(self.config.temp["set_point"].val / 10.0, self.config.temp["filter_ratio"].val / 1000.0)
self.meas_temp = self.config.temp["set_point"].val * 100
self.start_cycle = True
self.start_cycle_timer = copy.copy(self.main_cycle)
self.heater_on = 0
""" occupancy """
self.focc = False
self.occ = False
self.occ_sm = OccSm(self.config.temp["occ_cold_time"].val)
self.motion = {}
""" final heater control """
self.last_final_heater_on = 0
""" checkup info """
self.checkup_pub = False
self.checkup_msg = {}
""" user interface """
button = 0
self.last_button = 0
disp = []
last_disp = []
param = 0
last_value = True
value = True
buttoncfg = self.config.ui.button
dispcfg = self.config.ui.display
buttonrepeatsm = ButtonRepeatSM(buttoncfg.initial_dly, buttoncfg.repeat_dly)
paramvaluesm = HC.ParamValueSM(dispcfg.sp_time, dispcfg.sav_time)
self.save_success = False
""" start MQTT """
self.connect(host=self.config.mqtt.broker, port=self.config.mqtt.port,
keepalive=self.config.mqtt.timeout)
self.loop_start()
start = time.monotonic()
while not self.exit_evt.wait(nextWait):
self.main_cycle.value += 1
"""get button press here"""
button = self.handle_modbus(self.instr.read_register, 0, functioncode = 4)
""" run button repeat SM """
button = buttonrepeatsm.run(self.main_cycle, button)
""" run param / value SM """
last_value = value
param, value = paramvaluesm.run(self.main_cycle, button)
""" insert the number editor here """
self.numedit(param, value, button)
"""process on off and start timer here"""
final_heater_on = int(self.heater_on and (self.focc or self.occ))
self.handle_modbus(self.instr.write_bit, 0, final_heater_on)
if (self.last_final_heater_on != final_heater_on):
self.checkup_msg["HeaterControl On"] = final_heater_on
self.last_final_heater_on = final_heater_on
"""Publish checkup or event on mqtt"""
if self.checkup_msg != {}:
self.checkup_msg["time"] = time.time()
self.publish(f"{self.config.name}/checkup" if self.checkup_pub
else f"{self.config.name}/event", json.dumps(self.checkup_msg))
self.checkup_pub = False
logging.info(f"MQTT Publishing: {self.checkup_msg}")
self.checkup_msg = {}
"""process control cycle kick"""
if (self.heater_on != 0):
if (self.start_cycle == True):
logging.debug("Control cycle start deactivated")
self.checkup_msg["HeaterControl Start Cycle"] = 0
self.start_cycle = False
self.start_cycle_timer = copy.copy(self.main_cycle)
else:
st_val = self.config.temp["start_time"].val * 600
if c_uint16(self.main_cycle.value - self.start_cycle_timer.value).value > st_val:
if (self.start_cycle == False):
logging.debug("Control cycle start activated")
self.checkup_msg["HeaterControl Start Cycle"] = 1
self.start_cycle = True
""" do not allow the timer value to overflow """
self.start_cycle_timer.value = c_uint16(self.main_cycle.value - st_val - 1).value
""" process saving """
if param == EParams.save and last_value != True and value == True:
logging.debug("Attempting to save")
try:
with open(self.active_config_file, "w") as configFile:
configFile.write(self.config.to_json(indent=4))
logging.info("Save successful")
self.save_success = True
except Exception as err:
tb = traceback.format_exc()
logging.error(f"L {sys._getframe().f_back.f_lineno} Save attempt exception: {err}\nTraceback:\n{tb}")
self.save_success = False
"""output display here"""
last_disp = disp
disp = self.param_scroll(False, param, value)
even_odd = self.main_cycle.value % 2
self.handle_modbus(self.instr.write_register, even_odd, disp[even_odd])
""" Main Loop Execution Rate Handling """
curTime = time.monotonic()
nextWait = 0.100
nextWait -= curTime - start
if nextWait < 0.0:
""" Main loop overrun is only reported once """
if last_cycle_overrun == 0 and self.config.report_overrun:
logging.debug("Main loop overrun")
if last_cycle_overrun >= 20:
last_cycle_overrun = 0
start = curTime + nextWait
nextWait = 0.0
last_cycle_overrun += 1
else:
start = curTime
last_cycle_overrun = 0
self.disconnect()
self.loop_stop()
"""
The default function in this script reads the configuration file found at
where the source script exists.
"""
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
heaterControl = HC()
heaterControl.main()