-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.py
executable file
·818 lines (701 loc) · 34.1 KB
/
plugin.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
# OpenTherm Weather Dependent Heating Control
#
# Author: akamming
#
"""
<plugin key="OpenThermWDHC" name="OpenTherm Weather Dependent Heating Control" author="akamming" version="1.0.0" wikilink="https://github.com/akamming/Domoticz_Thermostate_Plugin#readme" externallink="https://github.com/akamming/esp_domoticz_opentherm_handler/">
<description>
<h2>Weather Dependent Heating Control</h2><br/>
Use Domoticz to control your OpenTherm Boiler<br/>
<br/>
This plugin will make domoticz act as a OpenTherm Weather Dependent Thermostate. So a heating curve will determine boiler water temperatures, to get the right amount of heating ins all rooms of your building. If you want to know what a heating curve is, please look at articles like http://tech-controllers.com/blog/heating-curve---what-is-it-and-how-to-set-it<br/><br/>
The description on how to use this plugin, can be found on <a href="https://github.com/akamming/Domoticz_Thermostate_Plugin#readme">the github page</a><br/>
<h3>Configuration</h3>
Please fill the following coordinates to make this plugin work<br/>
<ul style="list-style-type:square">
<li>Domticz IP adress and port (the default should work on a standard domoticz config)</li>
<li>the IDX values of your outdoor and indoor temperature devices</li>
<li>The number of minutes the "Daytime Extension" button should be active when pressed</li>
</ul>
</description>
<params>
<param field="Address" label="Domoticz IP Address" width="200px" required="true" default="localhost"/>
<param field="Port" label="Domoticz Port" width="40px" required="true" default="8080"/>
<param field="Username" label="Domoticz Username" width="200px" required="false" default=""/>
<param field="Password" label="Domoticz Password" width="200px" required="false" default=""/>
<param field="Mode2" label="comma seperated idx numers for Insidetemperature, OutsideTemperature, HeatingActive, CoolingActive, HotWaterActive, EnableHeating, EnableCooling, BoilerSetpoint" default="1,2,3,4,5,6,7" width="200px" required="true" />
<param field="Mode3" label="P,I and D value (comma separated)" default="30,0.01,2.5" width="100px" required="true" />
<param field="Mode4" label="Daytime Extension Time in minutes" default="120" required="true" />
</params>
</plugin>
"""
import Domoticz
import requests
import json
import datetime
import time
import urllib.parse as parse
import urllib.request as request
import base64
import math
import os
#Constants
RequiredInterface=2
SwitchOffHeatingDelta=1 #Switch off heating is current temp is more than this number of agrees above setpoint
#Config
KP = 30 #Proportaional gain: This is the Multiplier of the error (e.g. KP=30: 1 degree error will result in 30 degrees change of the pid value)
KI = 0.01 #Integral Gain: This is the multiplier of the error (e.g. KI=0.01: a 1 degree difference for 10 seconds will result in 0.1 degree change of the integral error (KI*error*duration))
KD = 2.5 #Derative Gain: Correction per every Delta K per Hour (e.g. KD=2.5: if the temp rises with 1 K per Hour, the PID will be lowered with 2.5 degrees)
InsideTemperatureIDX=0;
OutsideTemperatureIDX=0;
HeatingActiveIDX=0;
CoolingActiveIDX=0;
HotWaterActiveIDX=0;
EnableHeatingIDX=0;
EnableCoolingIDX=0;
BoilerSetpointIDX=0;
#UnitID's
BOILERTEMPATPLUS20=15
BOILERTEMPATMIN10=16
MAXBOILERTEMP=17
MINBOILERTEMP=18
SWITCHHEATINGOFFAT=19
PROGRAMSWITCH=20
CURVATURESWITCH=21
SETPOINT=22
FROSTPROTECTIONSETPOINT=24
REFERENCEROOMCOMPENSATION=25
CURRENTHEATINGCOOLINGSTATE=26
HOLIDAY=27
THERMOSTATTEMPERATURE=29
FPWD=35
MINTEMPDIFF=36
#Global vars
Hostname=""
Debugging=False
Simulation=False
#Vars for thermostat function
DeltaKPH=0 # Calculate change in temperature in Kelvin per hour
LastPIDCalcTimestamp=0 #remember last PID Calculation
ierr = 0 #Remember Integral Error
InsideTempAt=[] #Remember the inside temp the last hour
#Values to remember (in Domoticz)
CurrentInsideTemperature=0
CurrentOutsideTemperature=0
CurrentHeatingActive=False
CurrentCoolingActive=False
CurrentHotWaterActive=False
CurrentBoilerSetpoint=0
def getInt(s):
try:
int(s)
return s
except ValueError:
return 0
def Debug(text):
global Debug
if (Debugging):
Domoticz.Log("DEBUG: "+text)
def Log(text):
Domoticz.Log(text)
def UpdateCustomSensor(SensorName,UnitID,Value):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Custom", Used=1).Create()
if Devices[UnitID].sValue=="" or float(Devices[UnitID].sValue)!=float(Value):
Devices[UnitID].Update(nValue=0, sValue=str(Value))
Domoticz.Log("Custom ("+Devices[UnitID].Name+")")
def UpdatePercentageSensor(SensorName,UnitID,Value):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Percentage", Used=1).Create()
if Devices[UnitID].sValue=="" or float(Devices[UnitID].sValue)!=Value:
Devices[UnitID].Update(nValue=int(Value), sValue=str(Value))
Domoticz.Log("Percentage ("+Devices[UnitID].Name+")")
def UpdateOnOffSensor(SensorName,UnitID,Value):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Switch", Used=1).Create()
newValue=0
if (Value.lower()=="on" or Value.lower()=="yes"):
newValue=1
if newValue!=Devices[UnitID].nValue:
Devices[UnitID].Update(nValue=newValue, sValue=str(Value))
Domoticz.Log("Switch ("+Devices[UnitID].Name+")")
def UpdateDimmer(SensorName,UnitID,nValue,sValue):
#Creating devices in case they aren't there...
Debug("UpdateDimmer("+SensorName+","+str(UnitID)+","+str(nValue)+","+str(sValue)+")")
newValue=0
if (nValue.lower()=="on" or nValue.lower()=="yes"):
newValue=1
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, Type=244,Subtype=62,Switchtype=7,Used=1).Create()
Devices[UnitID].Update(nValue=newValue,sValue=str(sValue),Type=244,Subtype=62,Switchtype=7)
Domoticz.Log("Dimmer ("+Devices[UnitID].Name+")")
def UpdateSetpoint(SensorName,UnitID,Value):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, Type=242, Subtype=1, Used=1, Image=15).Create()
if Devices[UnitID].sValue=="" or float(Devices[UnitID].sValue)!=Value:
Devices[UnitID].Update(nValue=int(Value), sValue=str(Value))
Domoticz.Log("Setpoint ("+Devices[UnitID].Name+")")
def UpdateTemperatureSensor(SensorName,UnitID,Value):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Temperature", Used=1).Create()
if Devices[UnitID].sValue=="" or float(Devices[UnitID].sValue)!=Value:
Devices[UnitID].Update(nValue=int(Value), sValue=str(Value))
Domoticz.Log("Temperature ("+Devices[UnitID].Name+")")
def UpdatePressureSensor(SensorName,UnitID,Value):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Pressure", Used=1).Create()
if Devices[UnitID].sValue=="" or float(Devices[UnitID].sValue)!=float(Value):
Devices[UnitID].Update(nValue=int(Value), sValue=str(Value))
Domoticz.Log("Pressure ("+Devices[UnitID].Name+")")
def CreateSetPoint(SensorName,UnitID,DefaultValue):
if not (UnitID in Devices):
Debug("Creating setpoint "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, Type=242, Subtype=1, Used=1, Image=15).Create()
Devices[UnitID].Update(nValue=int(DefaultValue), sValue=str(DefaultValue))
def CreateOnOffDevice(SensorName,UnitID,DefaultValue):
if not (UnitID in Devices):
Debug("Creating on/off device "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Switch", Used=1).Create()
nv=0
if DefaultValue.lower()=="on":
nv=1
Devices[UnitID].Update(nValue=nv, sValue=str(DefaultValue))
def CreateCurvatureSwitch():
if not (CURVATURESWITCH in Devices):
Debug("Creating Curvature selector switch")
Options = {"LevelActions": "|| ||",
"LevelNames": "None|Small|Medium|Large",
"LevelOffHidden": "false",
"SelectorStyle": "0"}
Domoticz.Device(Name="Curvature", Unit=CURVATURESWITCH, TypeName="Selector Switch", Options=Options, Used=1).Create()
def CreateProgramSwitch():
if not (PROGRAMSWITCH in Devices):
Debug("Creating program switch")
Options = {"LevelActions": "|| ||",
"LevelNames": "Off|Heating|Cooling|Auto",
"LevelOffHidden": "false",
"SelectorStyle": "0"}
Domoticz.Device(Name="Program", Unit=PROGRAMSWITCH, TypeName="Selector Switch", Options=Options, Used=1).Create()
def CreateHeatingCoolingSwitch():
if not (CURRENTHEATINGCOOLINGSTATE in Devices):
Debug("Creating Heating Cooling switch")
Options = {"LevelActions": "|| ||",
"LevelNames": "Off|Heating|Cooling",
"LevelOffHidden": "false",
"SelectorStyle": "0"}
Domoticz.Device(Name="Heating Cooling State", Unit=CURRENTHEATINGCOOLINGSTATE, TypeName="Selector Switch", Options=Options, Used=1).Create()
def CreateOnOffSwitch(SensorName,UnitID):
#Creating devices in case they aren't there...
if not (UnitID in Devices):
Debug("Creating switch "+SensorName)
Domoticz.Device(Name=SensorName, Unit=UnitID, TypeName="Switch", Used=1).Create()
def CreateParameters():
CreateSetPoint("Boiler Temp at +20",BOILERTEMPATPLUS20,20)
CreateSetPoint("Boiler Temp at -10",BOILERTEMPATMIN10,70)
CreateSetPoint("Maximum Boiler Temperature",MAXBOILERTEMP,90)
CreateSetPoint("Minimum Boiler Temperature",MINBOILERTEMP,20)
CreateSetPoint("SwitchHeatingOffAt",SWITCHHEATINGOFFAT,17)
CreateProgramSwitch()
CreateHeatingCoolingSwitch()
CreateCurvatureSwitch()
CreateSetPoint("Day Setpoint",SETPOINT,20)
CreateSetPoint("Frost Protection Setpoint",FROSTPROTECTIONSETPOINT,7)
CreateSetPoint("Reference Room Temperature Compensation",REFERENCEROOMCOMPENSATION,3)
CreateSetPoint("Minimum Temperature Difference",MINTEMPDIFF,3)
CreateOnOffSwitch("Holiday",HOLIDAY)
CreateOnOffSwitch("FirePlace/Weather Dependent Control",FPWD)
def GetDeviceValues():
global CurrentInsideTemperature
global CurrentOutsideTemperature
global CurrentCoolingActive
global CurrentHeatingActive
global CurrentHotWaterActive
global CurrentBoilerSetpoint
global CurrentSetpoint
ReturnValue=True
#check to which target to get
if (Devices[PROGRAMSWITCH].nValue>0 and Devices[HOLIDAY].nValue==0):
Debug("Heating/Cooling is switched on, using day setpoint")
CurrentSetpoint=float(Devices[SETPOINT].sValue)
else:
Debug("Heating/Cooling is switched off")
CurrentSetpoint=float(Devices[FROSTPROTECTIONSETPOINT].sValue)
#Get Outside Temperature
Succes,CurrentOutsideTemperature=GetTemperature(OutsideTemperatureIDX)
if not Succes:
Log("Failed to get outside temperature")
ReturnValue=False
#Get Inside Temperature
Succes,CurrentInsideTemperature=GetTemperature(InsideTemperatureIDX)
if not Succes:
Log("Failed to get inside temperature")
ReturnValue=False
#Get BoilerSetpoint
Succes,CurrentBoilerSetpoint=GetSetpoint(BoilerSetpointIDX)
if not Succes:
Log("Failed to get Current Boiler Setpoint value")
ReturnValue=False
#Get HeatingActive
Succes,CurrentHeatingActive=GetSwitchState(HeatingActiveIDX)
if not Succes:
Log("Failed to get Current HeatingActive value")
ReturnValue=False
#Get CoolingActive
Succes,CurrentCoolingActive=GetSwitchState(CoolingActiveIDX)
if not Succes:
Log("Failed to get Current CoolingActive value")
ReturnValue=False
#Get HotWaterActive
Succes,CurrentHotWaterActive=GetSwitchState(HotWaterActiveIDX)
if not Succes:
Log("Failed to get Current HotWaterActive value")
ReturnValue=False
if ReturnValue: #Update Heating Cooling State if we have everything
level=0
if CurrentHeatingActive:
level=10
elif CurrentCoolingActive:
level=20
else:
Debug("Heating Cooling set to 0, Centralheating is "+str(CurrentHeatingActive)+", Cooling is "+str(CurrentCoolingActive))
Options = {"LevelActions": "|| ||",
"LevelNames": "Off|Heating|Cooling",
"LevelOffHidden": "false",
"SelectorStyle": "0"}
if Devices[CURRENTHEATINGCOOLINGSTATE].nValue==level:
Debug("Not updateing HEating cooling state, already at level "+str(level))
else:
Devices[CURRENTHEATINGCOOLINGSTATE].Update(nValue=int(level), sValue=str(level), TypeName="Selector Switch", Options=Options)
Debug("HeatingCoolingState was updated to "+str(level))
return ReturnValue
def CalculateBoilerSetPoint():
global CurrentInsideTemperature,CurrentOutsideTemperature,TargetTemperature
#Check if we are in thermostat or Weather dependent mode
if Devices[FPWD].nValue==0:
Debug("Calculate temperature using Thermostat (PID) mode")
TargetTemperature = GetPidValue(CurrentSetpoint, CurrentInsideTemperature)
#Return Correct Values
return True,TargetTemperature
else:
Debug("Calculate Boiler temp using FPWD (based on outside temop) mode")
MaxYDelta=Devices[BOILERTEMPATMIN10].nValue-Devices[BOILERTEMPATPLUS20].nValue #boilertemp at -10 minus boilertemp at +20
MaxXDelta=30 # 20 - (-10)=30
#Calculate curve based on root function
#Curvature=Devices[CURVATURESWITCH].nValue/20+1
#MaxToReach=MaxYDelta**Curvature
#TargetTemperature=((20-CurrentOutsideTemperature)/MaxXDelta*(MaxToReach))**(1/Curvature)+Devices[BOILERTEMPATPLUS20].nValue
#curve Calculation based on sine curve
TargetTemperatureWithoutCurvature=(20-CurrentOutsideTemperature)/MaxXDelta*MaxYDelta+Devices[BOILERTEMPATPLUS20].nValue
Curvature=math.sin(math.pi*(20-CurrentOutsideTemperature)/MaxXDelta)*Devices[CURVATURESWITCH].nValue*MaxYDelta/100
TargetTemperature=Curvature+TargetTemperatureWithoutCurvature
Debug("Temp calculated at "+str(TargetTemperature))
#Apply reference room compensation
Compensation=Devices[REFERENCEROOMCOMPENSATION].nValue
if Compensation>0:
Debug("applying reference room temperature compensation: "+str((CurrentSetpoint-CurrentInsideTemperature)*Compensation))
TargetTemperature+=(CurrentSetpoint-CurrentInsideTemperature)*Compensation
# Make sure target temp remains within set boundaries
if TargetTemperature>Devices[MAXBOILERTEMP].nValue:
Debug("Calculated temp above max temp, correcting")
TargetTemperature=Devices[MAXBOILERTEMP].nValue
if TargetTemperature<Devices[MINBOILERTEMP].nValue:
Debug("Calculated temp below min temp, correcting")
TargetTemperature=Devices[MINBOILERTEMP].nValue
#Return values
return True,TargetTemperature
def DomoticzAPI(APICall):
resultJson = None
url = "http://{}:{}/json.htm?{}".format(Parameters["Address"], Parameters["Port"], parse.quote(APICall, safe="&="))
Debug("URL "+url)
try:
req = request.Request(url)
if Parameters["Username"] != "":
#Domoticz.Debug("Add authentification for user {}".format(Parameters["Username"]))
credentials = ('%s:%s' % (Parameters["Username"], Parameters["Password"]))
encoded_credentials = base64.b64encode(credentials.encode('ascii'))
req.add_header('Authorization', 'Basic %s' % encoded_credentials.decode("ascii"))
response = request.urlopen(req)
if response.status == 200:
resultJson = json.loads(response.read().decode('utf-8'))
if resultJson["status"] != "OK":
Domoticz.Error("Domoticz API returned an error: status = {}".format(resultJson["status"]))
resultJson = None
else:
Domoticz.Error("Domoticz API: http error = {}".format(response.status))
except Exception as e:
Domoticz.Error("Error calling '{}'".format(url))
Domoticz.Error("Exception :{}".format(e))
return resultJson
def GetTemperature(TemperatureDeviceIDX):
data = DomoticzAPI("type=command¶m=getdevices&rid="+str(TemperatureDeviceIDX))
try:
CurrentTemperature=data["result"][0]["Temp"]
Debug ("Sensor "+data["result"][0]["Name"]+" has temperature "+str(CurrentTemperature))
return True,CurrentTemperature
except:
#Domoticz Error
Log("error getting temperature from domoticz device with idx "+str(TemperatureDeviceIDX))
return False,0
def GetSetpoint(SetpointDeviceIDX):
data = DomoticzAPI("type=command¶m=getdevices&rid="+str(SetpointDeviceIDX))
try:
CurrentSetpoint=float(data["result"][0]["Data"])
Debug ("Sensor "+data["result"][0]["Name"]+" has temperature "+str(CurrentSetpoint))
return True,CurrentSetpoint
except Exception as e:
#Domoticz Error
Log("error getting data from domoticz setpoint device with idx "+str(SetpointDeviceIDX)+": "+str(e))
return False,0
def GetSwitchState(SwitchDeviceIDX):
data = DomoticzAPI("type=command¶m=getdevices&rid="+str(SwitchDeviceIDX))
try:
CurrentSwitchState=True
if data["result"][0]["Status"]=="Off":
CurrentSwitchState=False
Debug ("switch "+data["result"][0]["Name"]+" is set to "+data["result"][0]["Status"])
return True,CurrentSwitchState
except:
#Domoticz Error
Log("error getting data from domoticz setpoint device with idx "+str(SwitchDeviceIDX))
return False,0
def SetSwitchState(SwitchDeviceIDX,Value):
data=DomoticzAPI("type=command¶m=switchlight&idx="+str(SwitchDeviceIDX)+"&switchcmd="+str(Value))
try:
if data["status"]=="OK":
return True
else:
Debug(data)
return False
except:
#Domoticz Error
Log("error getting data from domoticz setpoint device with idx"+str(SwitchDeviceIDX))
return False,0
def SetSetpoint(SetpointDeviceIDX,Value):
data=DomoticzAPI("type=command¶m=setsetpoint&idx="+str(SetpointDeviceIDX)+"&setpoint="+str(Value))
try:
if data["status"]=="OK":
return True
else:
Debug(data)
return False
except:
#Domoticz Error
Log("error getting data from domoticz setpoint device with idx"+str(SwitchDeviceIDX))
return False,0
def SetHeatingCoolingState(Heating,Cooling,Setpoint):
if Simulation:
Debug("Simulation mode, Heating is set to "+str(Heating)+", Cooling is set to "+str(Cooling)+", Setpoint is set to "+str(Setpoint))
else:
Debug("Simulation is off, Setting Heating to "+str(Heating)+", Cooling to "+str(Cooling)+", Setpoint to "+str(Setpoint))
#Set Enable Heating
if Heating:
SetSwitchState(EnableHeatingIDX,"On")
else:
SetSwitchState(EnableHeatingIDX,"Off")
#Set Enable Cooling
if Cooling:
SetSwitchState(EnableCoolingIDX,"On")
else:
SetSwitchState(EnableCoolingIDX,"Off")
#Set Setpoint
SetSetpoint(BoilerSetpointIDX,Setpoint)
def GetPidValue(sp, pv):
global ierr
global DeltaKPH #Delta in Kelvin Per Hour
global LastPIDCalcTimestamp
#calculate duration. Limit to max 10 secs (which might be the case if the program was suspended)
dt=time.time()-LastPIDCalcTimestamp
if dt>10:
dt=10
Debug("Elapsed time since last PID Calc = "+str(dt))
LastPIDCalcTimestamp=time.time() # reset timestamp
# upper and lower bounds on heater level
ophi = Devices[MAXBOILERTEMP].nValue
oplo = Devices[MINBOILERTEMP].nValue
# calculate the error
error = sp - pv;
# calculate the measurement derivative
#dpv = (pv - pv_last) / dt
# calculate the PID output
P = KP * error #proportional contribution
I = float(ierr) + float(KI) * float(error) * float(dt) #integral contribution
D = -KD*DeltaKPH #deritive contribution
#D = -KD*dpv #deritive contribution
op = P + I + D
if op<oplo:
op=oplo
if error<0:
I = I - KI * error * dt
if op>ophi:
op=ophi
if error>0:
I = I - KI * error * dt
if Devices[PROGRAMSWITCH].nValue==10:
Debug("Heating is on")
Debug(str(op)+"<"+str(CurrentBoilerSetpoint)+"<"+str(CurrentInsideTemperature))
if op<CurrentBoilerSetpoint and CurrentBoilerSetpoint<pv: #if op is dropping and and setpoint already below inside temperature
Debug("Not updating I Value: Boiler setpoint goes down during heating, while setpoint already below current inside temperature")
else:
Debug("Udating I")
ierr = I
elif Devices[PROGRAMSWITCH].nValue==20:
Debug("Cooling is on")
if op>CurrentBoilerSetpoint and CurrentBoilerSetpoint>pv: #if op is rising and and setpoint already above inside temperature
Debug("Not updating I Value: Boiler setpoint goes up during cooling, while setpoint already above current inside temperature")
else:
ierr = I
elif Devices[PROGRAMSWITCH].nValue==30:
Debug("Auto is on")
ierr = I
else:
Debug("Frost Protection is on")
Debug("Import;sp(setpoint)=" + str(sp) + ";pv(current value)=" + str(pv) + ";dt(delta time)=" + str(dt) + ";op(PID)=" + str(op) + ";P=" + str(P) + ";I=" + str(I) + ";D=" + str(D))
return op
def CheckDebug():
global Debugging
#Check if we have to switch on debug mode
if os.path.exists(str(Parameters["HomeFolder"])+"DEBUG"):
Debugging=True
Log("File "+str(Parameters["HomeFolder"])+"DEBUG"+" exists, switched on Debug mode")
else:
Debug("File "+str(Parameters["HomeFolder"])+"DEBUG"+" does not exist, switching off Debug mode")
Debugging=False #True/False
def CheckSimulation():
global Simulation
#Check if we have to switch on debug mode
if os.path.exists(str(Parameters["HomeFolder"])+"SIM"):
Simulation=True
Log("File "+str(Parameters["HomeFolder"])+"SIM"+" exists, switched on Simulation mode (no commands sent to control actual heating/cooling")
else:
Debug("File "+str(Parameters["HomeFolder"])+"SIM"+" does not exist, switching off Simulation mode")
Simulation=False #True/False
def HandleProgram():
if CurrentHotWaterActive:
Debug("Hot Water System is Active, suspending Central Heating Program")
else:
Succes,TargetTemperature=CalculateBoilerSetPoint()
if Succes:
Debug("Current Setpoint is "+str(CurrentSetpoint))
#Program Active, try to get outside temperature
if CurrentOutsideTemperature>(Devices[SWITCHHEATINGOFFAT].nValue) and Devices[FPWD].nValue==1:
Debug("Weather dependant and outside temp aboven day treshold, leave or switch off heating")
#We are at the temperature at which we can switchoff heating
SetHeatingCoolingState(False,False,0)
else:
if (Devices[PROGRAMSWITCH].nValue>0 and Devices[HOLIDAY].nValue==0):
Debug("Handling program")
if Devices[PROGRAMSWITCH].nValue==10: #HEATING
if TargetTemperature>CurrentInsideTemperature+float(Devices[MINTEMPDIFF].sValue):
Debug("HEATING: Setting boiler temp to "+str(TargetTemperature))
SetHeatingCoolingState(True,False,TargetTemperature)
else:
Debug("HEATING: Switching off heating ")
SetHeatingCoolingState(False,False,TargetTemperature)
elif Devices[PROGRAMSWITCH].nValue==20: #COOLING
if TargetTemperature<CurrentInsideTemperature-float(Devices[MINTEMPDIFF].sValue):
Debug("COOLING: Setting water temp to "+str(TargetTemperature))
SetHeatingCoolingState(False,True,TargetTemperature)
else:
Debug("COOLING: Switching off Cooling")
SetHeatingCoolingState(False,False,TargetTemperature)
elif Devices[PROGRAMSWITCH].nValue==30: #AUTO
if TargetTemperature>CurrentInsideTemperature+float(Devices[MINTEMPDIFF].sValue):
Debug("AUTO: HEATING: Setting boiler temp to "+str(TargetTemperature))
SetHeatingCoolingState(True,False,TargetTemperature)
elif TargetTemperature<CurrentInsideTemperature-float(Devices[MINTEMPDIFF].sValue):
Debug("AUTO: COOLING: Setting water temp to "+str(TargetTemperature))
SetHeatingCoolingState(False,True,TargetTemperature)
else:
Debug("AUTO: Switching off heating/cooling"+str(TargetTemperature))
SetHeatingCoolingState(False,False,TargetTemperature)
else:
Debug("Weird: This code should not be reached, Programswitch set to "+str(Devices[PROGRAMSWITCH].nValue))
else:
if Devices[HOLIDAY].nValue==1:
Debug("Holiday program active")
Debug("Handling Frost protection program")
#Manage Heating
if CurrentInsideTemperature<=Devices[FROSTPROTECTIONSETPOINT].nValue:
Debug("temperature "+str(CurrentInsideTemperature)+" below frostprotection setpoint "+str(Devices[FROSTPROTECTIONSETPOINT].nValue)+", make sure there is heating")
SetHeatingCoolingState(True,False,TargetTemperature)
else:
Debug("temperature above frost protection setpoint, switch off heating")
SetHeatingCoolingState(False,False,TargetTemperature)
else:
Log("No temperatures returned from calculateboilersetpoint, could not execute program, updating sensors")
def getConfig():
global KP,KI,KD
global InsideTemperatureIDX,OutsideTemperatureIDX,HeatingActiveIDX,CoolingActiveIDX,HotWaterActiveIDX,EnableHeatingIDX,EnableCoolingIDX,BoilerSetpointIDX
try:
# PID Parameters
PID=Parameters["Mode3"].split(",")
KP=float(PID[0])
KI=float(PID[1])
KD=float(PID[2])
#IDX numbers
IDX=Parameters["Mode2"].split(",")
InsideTemperatureIDX=int(IDX[0])
OutsideTemperatureIDX=int(IDX[1])
HeatingActiveIDX=int(IDX[2])
CoolingActiveIDX=int(IDX[3])
HotWaterActiveIDX=int(IDX[4])
EnableHeatingIDX=int(IDX[5])
EnableCoolingIDX=int(IDX[6])
BoilerSetpointIDX=int(IDX[7])
except Exception as e:
Domoticz.Error("Exception :{}".format(e))
class BasePlugin:
enabled = False
def __init__(self):
#self.var = 123
return
def onStart(self):
global Hostname
global OutsideTemperatureIdx
global InsideTemperatureIdx
global ierr
global InsideTempAt
CheckDebug() #Check if we have to enable debugging
CheckSimulation() #Check if we have to enable simulation
#Get Pid parameters
getConfig()
Debug("P set to "+str(KP))
Debug("I set to "+str(KI))
Debug("D set to "+str(KD))
# Read config
#for x in Parameters:
# Debug("Paramater "+x+" is "+str(Parameters[x]))
Hostname="http://"+Parameters["Mode1"]+"/"
#Create parameters if they don;t exist
CreateParameters()
#Read Domoticz Devices
GetDeviceValues()
#Initialise ierr
ierr=CurrentInsideTemperature
#initialise InsideTempAt array
InsideTempAt = [CurrentInsideTemperature for i in range(60)]
def onStop(self):
Debug("onStop called")
def onConnect(self, Connection, Status, Description):
Debug("onConnect called")
def onMessage(self, Connection, Data):
Debug("onMessage called")
def onCommand(self, Unit, Command, Level, Hue):
global ierr
global LastPIDCalcTimestamp
Debug("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level))
if Unit in {CURVATURESWITCH,MINBOILERTEMP,MAXBOILERTEMP,BOILERTEMPATMIN10,BOILERTEMPATPLUS20,SWITCHHEATINGOFFAT,
SETPOINT,FROSTPROTECTIONSETPOINT,REFERENCEROOMCOMPENSATION,MINTEMPDIFF}:
if Devices[Unit].sValue=="" or float(Devices[Unit].sValue)!=float(Level):
Devices[Unit].Update(nValue=int(Level), sValue=str(Level))
elif Unit==PROGRAMSWITCH:
#Update the switch ;-)
Options = {"LevelActions": "|| ||",
"LevelNames": "Off|Heating|Cooling|Auto",
"LevelOffHidden": "false",
"SelectorStyle": "0"}
Devices[Unit].Update(nValue=int(Level), sValue=str(Level), Options=Options)
#Switch off heating and cooling in case progam was shut down
if Devices[Unit].nValue==0:
SetHeatingCoolingState(False,False,0)
#Reset Thermostat Global Values to give fresh start to new program mode
Succes,CurrentInsideTemperature=GetTemperature(InsideTemperatureIDX)
if Succes:
ierr=CurrentInsideTemperature #Better starting point for ierr
elif Unit in {HOLIDAY,FPWD}:
#Handle Switch
NewValue=0
if Command=="On":
NewValue=1
Devices[Unit].Update(nValue=NewValue, sValue=Command)
#If FirePlace/WeatherDependent switch was set: reset thermostat vars
if (Unit==FPWD and Command=="Off"):
#Reset Thermostat Values
Succes,CurrentInsideTemperature=GetTemperature(InsideTemperatureIDX)
if Succes:
ierr=CurrentInsideTemperature #Better starting point for ierr
else:
Log("Unhandled command")
#handle program if needed
if Devices[PROGRAMSWITCH].nValue!=0:
#Handling the program
HandleProgram()
def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile):
Debug("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile)
def onDisconnect(self, Connection):
Debug("onDisconnect called")
def onHeartbeat(self):
global CurrentInsideTemperature
global InsideTempAt
global DeltaKPH
CheckDebug() #Check if we have to enable debug logging
CheckSimulation() #Check if we have to enable debug logging
#Make sure all params are there so the user can control the program..
CreateParameters()
if (GetDeviceValues()):
Debug("Current Inside Temperature is "+str(CurrentInsideTemperature))
#Update History
CurrentMin=int((time.time() % 3600) / 60)
InsideTempAt[CurrentMin]=CurrentInsideTemperature
Debug("Updated InsideTemp At "+str(CurrentMin)+" with "+str(InsideTempAt[CurrentMin]))
DeltaKPH = (CurrentInsideTemperature-InsideTempAt[(CurrentMin+45)%60])*4 #tempchange the last 15 mins mutltiplied by 4
Debug("DeltaKPH = "+str(DeltaKPH))
#Handle Program
HandleProgram()
else:
Debug("Do nothing: Unable to get temperatures")
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onStop():
global _plugin
_plugin.onStop()
def onConnect(Connection, Status, Description):
global _plugin
_plugin.onConnect(Connection, Status, Description)
def onMessage(Connection, Data):
global _plugin
_plugin.onMessage(Connection, Data)
def onCommand(Unit, Command, Level, Hue):
global _plugin
_plugin.onCommand(Unit, Command, Level, Hue)
def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile):
global _plugin
_plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
# Generic helper functions
def DumpConfigToLog():
for x in Settings:
Debug("Setting "+str(x)+" is "+str(Settings[x]))
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug( "'" + x + "':'" + str(Parameters[x]) + "'")
Domoticz.Debug("Device count: " + str(len(Devices)))
for x in Devices:
Domoticz.Debug("Device: " + str(x) + " - " + str(Devices[x]))
Domoticz.Debug("Device ID: '" + str(Devices[x].ID) + "'")
Domoticz.Debug("Device Name: '" + Devices[x].Name + "'")
Domoticz.Debug("Device nValue: " + str(Devices[x].nValue))
Domoticz.Debug("Device sValue: '" + Devices[x].sValue + "'")
Domoticz.Debug("Device LastLevel: " + str(Devices[x].LastLevel))
return