-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.py
951 lines (864 loc) · 31.2 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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Name: IP Weather Station plugin
# Version: 0.0.1
# Author: Martin Saidl based on original Xorfor plugin - https://github.com/Xorfor/Domoticz-PWS-Plugin
#
"""
<plugin key="ip_ws" name="IP Weather Station" author="Martin Saidl" version="0.0.1" wikilink="https://github.com/saidlm/Domticz-IPWweatherStation-plugin">
<params>
<param field="Port" label="Port" width="40px" required="true" default="5000"/>
<param field="Username" label="ID" width="100px" required="true"/>
<param field="Password" label="Password" width="100px" required="true"/>
<param field="Mode1" label="Update timeout" width="20px" default="10" />
<param field="Mode2" label="Always update" width="80px">
<options>
<option label="On" value="On" />
<option label="Off" value="Off" default="true" />
</options>
</param>
<param field="Mode6" label="Debug" width="80px">
<options>
<option label="True" value="Debug"/>
<option label="False" value="Normal" default="true" />
</options>
</param>
</params>
</plugin>
"""
import Domoticz
from enum import IntEnum, unique # , auto
from datetime import datetime
import time
@unique
class unit(IntEnum):
"""
Device Unit numbers
Define here your units numbers. These can be used to update your devices.
Be sure the these have a unique number!
"""
TEMP_IND = 1
THB = 2
HUMIDITY = 3
WIND1 = 4
TEMP_HUM = 5
RAIN = 6
SOLAR = 7
UVI = 8
DEWPOINT = 9
WIND2 = 10
CHILL = 11
WINDSPEED = 12
GUST = 13
TEMP = 14
HUMIDITY_IND = 15
UV_ALERT = 16
WIND_DIRECTION = 17
STATION = 20
BARO_REL = 21
BARO_ABS = 22
RAIN_RATE = 23
HEAT_INDEX = 24
@unique
class used(IntEnum):
"""
Constants which can be used to create the devices. Look at onStart where
the devices are created.
used.NO, the user has to add this device manually
used.YES, the device will be directly available
"""
NO = 0
YES = 1
class BasePlugin:
#
# Devices
__UNITS = [
# id, name, type, subtype, options, used
[unit.TEMP_IND, "Temperature (indoor)", 80, 5, {}, used.YES],
[unit.TEMP, "Temperature", 80, 5, {}, used.YES],
[unit.DEWPOINT, "Dew point", 80, 5, {}, used.YES],
[unit.CHILL, "Chill", 80, 5, {}, used.YES],
[unit.HUMIDITY, "Humidity", 81, 1, {}, used.YES],
[unit.HUMIDITY_IND, "Humidity (indoor)", 81, 1, {}, used.YES],
[unit.TEMP_HUM, "Temp + Hum", 82, 1, {}, used.YES],
[unit.THB, "THB", 84, 1, {}, used.YES],
[unit.RAIN, "Rain", 85, 1, {}, used.YES],
[unit.WIND1, "Wind", 86, 1, {}, used.YES],
[unit.WIND2, "Wind", 86, 4, {}, used.YES],
[unit.UVI, "UVI", 87, 1, {}, used.YES],
[unit.UV_ALERT, "UV Alert", 243, 22, {}, used.YES],
[unit.SOLAR, "Solar radiation", 243, 2, {}, used.YES],
[unit.WINDSPEED, "Wind speed", 243, 31, {"Custom": "0;m/s"}, used.YES],
[unit.WIND_DIRECTION, "Wind direction", 243, 31, {"Custom": "0;°"}, used.YES],
[unit.GUST, "Gust", 243, 31, {"Custom": "0;m/s"}, used.YES],
[unit.STATION, "Station", 243, 19, {}, used.YES],
[unit.BARO_REL, "Barometer (relative)", 243, 26, {}, used.YES],
[unit.BARO_ABS, "Barometer (absolute)", 243, 26, {}, used.YES],
[unit.RAIN_RATE, "Rain rate", 243, 31, {"Custom": "0;mm/h"}, used.YES],
[unit.HEAT_INDEX, "Heat index", 80, 5, {}, used.YES],
]
def __init__(self):
self.enabled = False
self.httpServerConn = None
self.httpServerConns = {}
self.raincounter = None
self.prev_dailyrainin = None
self.lastContactTime = time.time()
self.maxUpdateInteval = None
self.alwaysUpdate = False
def onConnect(self, Connection, Status, Description):
Domoticz.Debug(
"onConnect {}={}:{} {}-{}".format(
Connection.Name,
Connection.Address,
Connection.Port,
Status,
Description,
)
)
Domoticz.Debug(str(Connection))
self.httpServerConns[Connection.Name] = Connection
def onDisconnect(self, Connection):
Domoticz.Debug(
"onDisconnect {}={}:{}".format(
Connection.Name, Connection.Address, Connection.Port
)
)
if Connection.Name in self.httpServerConns:
del self.httpServerConns[Connection.Name]
def onHeartbeat(self):
Domoticz.Debug("onHeartbeat")
sensorTimeout = Settings["SensorTimeout"]
actualTime = time.time()
diffTime = (actualTime - self.lastContactTime)/60
Domoticz.Debug(str(diffTime))
if (diffTime > int(sensorTimeout)):
for unit in self.__UNITS:
Unit=unit[0]
UpdateDevice(Unit, Devices[Unit].nValue, Devices[Unit].sValue, TimedOut=1)
def onMessage(self, Connection, Data):
Domoticz.Debug(
"onMessage {}={}:{}".format(
Connection.Name, Connection.Address, Connection.Port
)
)
DumpHTTPResponseToLog(Data)
dataIsValid = False
# Incoming Requests
if "Verb" in Data:
strVerb = Data["Verb"]
strURL = Data["URL"]
Domoticz.Debug("Request {}".format(strVerb))
if strVerb == "GET":
protocol = "Wunderground"
strData = strURL.split("?")[1]
Domoticz.Debug("strData: {}".format(strData))
# Convert URL parameters to dict for generic update of the devices
data = dict(item.split("=") for item in strData.split("&"))
Domoticz.Debug("data: {}".format(data))
if len(data) > 0:
if not (data.get("ID") == Parameters["Username"] and data.get("PASSWORD") == Parameters["Password"]):
Domoticz.Error("Authentication faild")
dataIsValid = True
# Get data
temp = temperature_f2iso(float_or_none(data.get("tempf")))
tempin = temperature_f2iso(float_or_none(data.get("indoortempf")))
humidity = int_or_none(data.get("humidity"))
humidityin = int_or_none(data.get("indoorhumidity"))
windspeedms = speed_mph2iso(float_or_none(data.get("windspeedmph")))
windgustms = speed_mph2iso(float_or_none(data.get("windgustmph")))
winddir = int_or_none(data.get("winddir"))
solarradiation = float_or_none(data.get("solarradiation"))
uv = float_or_none(data.get("UV"))
softwaretype = data.get("softwaretype")
baromrel = pressure_inches2iso(float_or_none(data.get("baromin")))
baromabs = pressure_inches2iso(
float_or_none(data.get("absbaromin"))
)
rainmm = distance_inch2iso(float_or_none(data.get("rainin")))
if rainmm is not None:
rainmm = 10 * rainmm
dailyrainmm = distance_inch2iso(
float_or_none(data.get("dailyrainin"))
)
if dailyrainmm is not None:
dailyrainmm = 10.0 * dailyrainmm
dewpt = (
dew_point(temp, humidity)
if data.get("dewptf") is None
else temperature_f2iso(float_or_none(data.get("dewptf")))
)
windchill = (
wind_chill(temp, windspeedms)
if data.get("windchillf") is None
else temperature_f2iso(float_or_none(data.get("windchillf")))
)
else:
Domoticz.Error("Unknown protocol")
dataIsValid = False
if dataIsValid:
self.lastContactTime = time.time()
Domoticz.Debug("Protocol: {}".format(protocol))
# Reset counters
if self.raincounter is None: # Domoticz (re)started.
# Try to get the original counter
old_values = Devices[unit.RAIN].sValue.split(";")
# Set Domoticz counter to 0
UpdateDevice(unit.RAIN, 0, "{};{}".format(0, 0))
if len(old_values[0]) == 0:
# Hardware first time
self.raincounter = 0
else:
# Hardware exists so get old value
self.raincounter = float(old_values[1]) - dailyrainmm
self.prev_dailyrainin = dailyrainmm
if dailyrainmm < self.prev_dailyrainin:
self.raincounter += self.prev_dailyrainin
self.prev_dailyrainin = dailyrainmm
# Calculate statuses
humiditystatus = humidity2status_outdoor(humidity)
indoorhumiditystatus = humidity2status_indoor(humidityin, tempin)
pressurestatus = pressure2status(baromrel)
# Round calculated values for presentation
temp = round(temp, 1) if temp is not None else None
tempin = round(tempin, 1) if tempin is not None else None
windspeedms = round(windspeedms, 1) if windspeedms is not None else None
dewpt = round(dewpt, 1) if dewpt is not None else None
windchill = round(windchill, 1) if windchill is not None else None
windgustms = round(windgustms, 1) if windgustms is not None else None
baromrel = round(baromrel) if baromrel is not None else None
baromabs = round(baromabs) if baromabs is not None else None
rainmm = round(rainmm, 2) if rainmm is not None else None
dailyrainmm = round(dailyrainmm, 2) if dailyrainmm is not None else None
solarradiation = (
round(solarradiation, 1) if solarradiation is not None else None
)
# Get wind unit from Domoticz settings
windunit = int(Settings["WindUnit"])
Domoticz.Debug("WindUnit: {}".format(windunit))
# Update devices
UpdateDevice(
unit.TEMP_IND,
0,
"{}".format(
tempin
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.TEMP,
0,
"{}".format(
temp
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.HUMIDITY,
int(humidity) if humidity is not None else 0,
"{}".format(
humiditystatus
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.HUMIDITY_IND,
int(humidityin) if humidityin is not None else 0,
"{}".format(
indoorhumiditystatus
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.DEWPOINT,
0,
"{}".format(
dewpt
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.CHILL,
0,
"{}".format(
windchill
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.TEMP_HUM,
0,
"{};{};{}".format(
temp, humidity, humiditystatus
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.WIND1,
0,
"{};{};{};{};{};{}".format(
winddir,
bearing2status(winddir) if winddir is not None else None,
windspeedms * 10 if windspeedms is not None else None,
windgustms * 10 if windgustms is not None else None,
temp,
windchill,
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.WIND2,
0,
"{};{};{};{};{};{}".format(
winddir,
bearing2status(winddir) if winddir is not None else None,
windspeedms * 10 if windspeedms is not None else None,
windgustms * 10 if windgustms is not None else None,
temp,
windchill,
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
# Custom device, so we have to handle the alternative windspeed units
UpdateDeviceOptions(
unit.WINDSPEED,
Options=speed2options(windunit)
)
UpdateDevice(
unit.WINDSPEED,
0,
"{}".format(
speed2unit(windspeedms, windunit)
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
# Custom device, so we have to handle the alternative windspeed units
UpdateDeviceOptions(
unit.GUST,
Options=speed2options(windunit)
)
UpdateDevice(
unit.GUST,
0,
"{}".format(
speed2unit(windgustms, windunit)
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.WIND_DIRECTION,
0,
"{}".format(
winddir
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.SOLAR,
int(solarradiation) if solarradiation is not None else 0,
"{}".format(
solarradiation
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.UVI,
int(uv) if uv is not None else 0,
"{};{}".format(
uv, temp
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.UV_ALERT,
uv2status(uv) if uv is not None else 0,
"{} UVI".format(
uv
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.STATION,
0,
"{} ({}): {}".format(
Connection.Address, softwaretype, protocol
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.THB,
0,
"{};{};{};{};{}".format(
temp, humidity, humiditystatus, baromrel, pressurestatus
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.BARO_REL,
0,
"{};{}".format(
baromrel, pressurestatus
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.BARO_ABS,
0,
"{};{}".format(
baromabs, pressure2status(baromabs)
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
if rainmm is not None:
UpdateDevice(
unit.RAIN,
0,
"{};{}".format(
rainmm * 100, round(self.raincounter + dailyrainmm, 3)
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.RAIN_RATE,
0,
"{}".format(
rainmm
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
UpdateDevice(
unit.HEAT_INDEX,
0,
"{}".format(
heat_index(temp, humidity)
),
AlwaysUpdate = self.alwaysUpdate,
MaxUpdateInterval = self.maxUpdateInterval
)
def onStart(self):
if Parameters["Mode6"] == "Debug":
Domoticz.Debugging(1)
else:
Domoticz.Debugging(0)
Domoticz.Debug("onStart")
# Configuration
try:
if 1 <=int(Parameters["Mode1"]) <= 1440:
self.maxUpdateInterval = int(Parameters["Mode1"])
else:
self.maxUpdateInterval = 10
except:
self.maxUpdateInterval = 10
Domoticz.Debug("Maximum update interval is set to: {} minutes".format(str(self.maxUpdateInterval)))
try:
if Parameters["Mode2"] == "On":
self.alwaysUpdate = True
else:
self.alwaysUpdate = False
except:
self.alwaysUpdate = False
Domoticz.Debug("Always update is: {}".format(str(self.alwaysUpdate)))
# Devices
for unit in self.__UNITS:
if unit[0] not in Devices:
Domoticz.Device(
Unit=unit[0],
Name=unit[1],
Type=unit[2],
Subtype=unit[3],
Options=unit[4],
Used=unit[5],
).Create()
# Connections
self.httpServerConn = Domoticz.Connection(
Name="Server",
Transport="TCP/IP",
Protocol="HTTP",
Port=Parameters["Port"],
)
self.httpServerConn.Listen()
Domoticz.Debug("Listening to port: {}".format(Parameters["Port"]))
global _plugin
_plugin = BasePlugin()
def onStart():
global _plugin
_plugin.onStart()
def onConnect(Connection, Status, Description):
global _plugin
_plugin.onConnect(Connection, Status, Description)
def onMessage(Connection, Data):
global _plugin
_plugin.onMessage(Connection, Data)
def onDisconnect(Connection):
global _plugin
_plugin.onDisconnect(Connection)
def onHeartbeat():
global _plugin
_plugin.onHeartbeat()
################################################################################
# Generic helper functions
################################################################################
def DumpConfigToLog():
for x in Parameters:
if Parameters[x] != "":
Domoticz.Debug("'" + x + "':'" + str(Parameters[x]) + "'")
Domoticz.Debug("Device count: {}".format(len(Devices)))
for x in Devices:
Domoticz.Debug("Device: {} - {}".format(x, Devices[x]))
Domoticz.Debug("Device ID: {}".format(Devices[x].ID))
Domoticz.Debug("Device Name: '{}'".format(Devices[x].Name))
Domoticz.Debug("Device nValue: {}".format(Devices[x].nValue))
Domoticz.Debug("Device sValue: '{}'".format(Devices[x].sValue))
Domoticz.Debug("Device LastLevel: {}".format(Devices[x].LastLevel))
def DumpHTTPResponseToLog(httpDict):
if isinstance(httpDict, dict):
Domoticz.Debug("HTTP Details ({}):".format(len(httpDict)))
for x in httpDict:
if isinstance(httpDict[x], dict):
Domoticz.Debug(" '{}' ({}):".format(x, len(httpDict[x])))
for y in httpDict[x]:
Domoticz.Debug(" '{}': '{}'".format(y, httpDict[x][y]))
else:
Domoticz.Debug(" '{}: '{}'".format(x, httpDict[x]))
def UpdateDevice(Unit, nValue, sValue, TimedOut=0, MaxUpdateInterval=10, AlwaysUpdate=False):
# Make sure that the Domoticz device still exists (they can be deleted) before updating it
if Unit in Devices:
# try/catch due to http://bugs.python.org/issue27400
try:
timeDiff = datetime.now() - datetime.strptime(Devices[Unit].LastUpdate,'%Y-%m-%d %H:%M:%S')
except TypeError:
timeDiff = datetime.now() - datetime(*(time.strptime(Devices[Unit].LastUpdate,'%Y-%m-%d %H:%M:%S')[0:6]))
if (
Devices[Unit].nValue != nValue
or Devices[Unit].sValue != sValue
or Devices[Unit].TimedOut != TimedOut
or (timeDiff.seconds/60)%60 > MaxUpdateInterval
or AlwaysUpdate
):
Devices[Unit].Update(nValue=nValue, sValue=str(sValue), TimedOut=TimedOut)
Domoticz.Debug(
"Update {}: {} - {} - {}".format(
Devices[Unit].Name, nValue, sValue, TimedOut
)
)
def UpdateDeviceOptions(Unit, Options={}):
if Unit in Devices:
if Devices[Unit].Options != Options:
Devices[Unit].Update(
nValue=Devices[Unit].nValue,
sValue=Devices[Unit].sValue,
Options=Options,
)
Domoticz.Debug(
"Device Options update: {}={}".format(Devices[Unit].Name, Options)
)
################################################################################
# Plugin functions
################################################################################
HUMIDITY_NORMAL = 0
HUMIDITY_COMFORTABLE = 1
HUMIDITY_DRY = 2
HUMIDITY_WET = 3
# Based on Mollier diagram (simplified)
def humidity2status_indoor(hlevel, temperature):
if hlevel is None or temperature is None:
return None
if hlevel <= 30:
return HUMIDITY_DRY
if 35 <= hlevel <= 65 and 18 <= temperature <= 22:
return HUMIDITY_COMFORTABLE
if hlevel >= 70:
return HUMIDITY_WET
return HUMIDITY_NORMAL
def humidity2status_outdoor(value):
if value is None:
return None
if value < 25:
return HUMIDITY_DRY
if 25 <= value <= 60:
return HUMIDITY_COMFORTABLE
if value > 60:
return HUMIDITY_WET
return HUMIDITY_NORMAL
def temperature_f2iso(value):
"""Temperature conversion from Fahrenheit to ISO (Celsius)
Args:
value (float): temperature in Fahrenheit
Returns:
temperature in Celsius
"""
if value is None:
return None
else:
return (value - 32) / 1.8
def speed_mph2iso(value):
"""Speed conversion from mp/h to ISO (m/s)
Args:
value (float): speed in mp/h
Returns:
speed in m/s
"""
if value is None:
return None
else:
return value * 0.44704
def bearing2status(d):
"""
Based on https://gist.github.com/RobertSudwarts/acf8df23a16afdb5837f
"""
dirs = (
"N",
"NNE",
"NE",
"ENE",
"E",
"ESE",
"SE",
"SSE",
"S",
"SSW",
"SW",
"WSW",
"W",
"WNW",
"NW",
"NNW",
)
count = len(dirs) # Number of entries in list
step = 360 / count # Wind direction is in steps of 22.5 degrees (360/16)
ix = int((d + (step / 2)) / step) # Calculate index in the list
return dirs[ix % count]
BARO_FORECAST_NOINFO = 0
BARO_FORECAST_SUNNY = 1
BARO_FORECAST_PARTLYCLOUDY = 2
BARO_FORECAST_CLOUDY = 3
BARO_FORECAST_RAIN = 4
BARO_FORECAST_UNKNOWN = 5
BARO_FORECASTS = {
BARO_FORECAST_NOINFO,
BARO_FORECAST_SUNNY,
BARO_FORECAST_PARTLYCLOUDY,
BARO_FORECAST_CLOUDY,
BARO_FORECAST_RAIN,
}
def pressure2status(value):
if value is None:
return None
if value < 1000:
return BARO_FORECAST_RAIN
elif value < 1020:
return BARO_FORECAST_CLOUDY
elif value < 1030:
return BARO_FORECAST_PARTLYCLOUDY
else:
return BARO_FORECAST_SUNNY
def uv2status(value):
if value is None:
return None
if value < 3:
return 0
elif value < 6:
return 1
elif value < 8:
return 2
elif value < 11:
return 3
else:
return 4
def pressure_inches2iso(value):
"""Pressure conversion from inches Hg to ISO (hPa)
Args:
value (float): pressure in inches Hg
Returns:
pressure in hPa
"""
if value is None:
return None
else:
return value * 33.86
def distance_inch2iso(value):
"""Distance conversion from inches to ISO (cm)
Args:
value (float): Distance in inches
Returns:
Distance in cm
"""
if value is None:
return None
else:
return value * 2.54
def dew_point(t, h):
"""Calculate dewpoint
Args:
t (float): temperature in °C
h (float): relative humidity in %
Returns:
calculated dewpoint in °C
Ref:
https://www.ajdesigner.com/phphumidity/dewpoint_equation_dewpoint_temperature.php
"""
return round((h / 100) ** (1 / 8) * (112 + 0.9 * t) + 0.1 * t - 112, 2)
def wind_chill(t, v):
"""Windchill temperature is defined only for temperatures at or below 10 °C
and wind speeds above 4.8 kilometres per hour.
Args:
t: temperature in °C
v: wind speed in m/s
Returns:
calculated windchill temperature in °C
Ref:
https://en.wikipedia.org/wiki/Wind_chill
"""
# Calculation expects km/h instead of m/s, so
v = v * 3.6
if t < 10 and v > 4.8:
v = v ** 0.16
return round(13.12 + 0.6215 * t - 11.37 * v + 0.3965 * t * v, 1)
else:
return t
WIND_SPEED_MS = 0
WIND_SPEED_KMH = 1
WIND_SPEED_MPH = 2
WIND_SPEED_KNOTS = 3
WIND_SPEED_BEAUFORT = 4
WIND_SPEED_ISO = WIND_SPEED_MS
WIND_SPEEDS = {
WIND_SPEED_MS,
WIND_SPEED_KMH,
WIND_SPEED_MPH,
WIND_SPEED_KNOTS,
WIND_SPEED_BEAUFORT,
}
def speed2unit(speed, unit):
"""Convert the windspeed (in m/s) to the given unit
Args:
speed: windspeed in m/s
unit: the new unit for windspeed
Returns:
calculated windspeed for the given unit
"""
if unit in WIND_SPEEDS:
if unit == WIND_SPEED_ISO:
return speed
elif unit == WIND_SPEED_KMH:
return round(speed * 3.60000000, 1)
elif unit == WIND_SPEED_MPH:
return round(speed * 2.23693629, 1)
elif unit == WIND_SPEED_KNOTS:
return round(speed * 1.94384449, 1)
elif unit == WIND_SPEED_BEAUFORT:
if 0 <= speed < 0.3:
return 0
elif 0.3 <= speed < 1.6:
return 1
elif 1.6 <= speed < 3.4:
return 2
elif 3.4 <= speed < 5.5:
return 3
elif 5.5 <= speed < 8.0:
return 4
elif 8.0 <= speed < 10.8:
return 5
elif 10.8 <= speed < 13.9:
return 6
elif 13.9 <= speed < 17.2:
return 7
elif 17.2 <= speed < 20.8:
return 8
elif 20.8 <= speed < 24.5:
return 9
elif 24.5 <= speed < 28.5:
return 10
elif 28.5 <= speed < 32.7:
return 11
elif 32.7 <= speed:
return 12
else:
return None
else:
return None
def speed2options(unit):
if unit in WIND_SPEEDS:
if unit == WIND_SPEED_ISO:
return {"Custom": "0;m/s"}
elif unit == WIND_SPEED_KMH:
return {"Custom": "0;km/h"}
elif unit == WIND_SPEED_MPH:
return {"Custom": "0;mph"}
elif unit == WIND_SPEED_KNOTS:
return {"Custom": "0;kn"}
elif unit == WIND_SPEED_BEAUFORT:
return {"Custom": "0;bf"}
else:
return {}
else:
return {}
def heat_index(temp, humidity):
"""Calculate heat index (in C)
Formula can be found at https://en.wikipedia.org/wiki/Heat_index
Args:
temp : temperature in C
humidity: in %
Returns:
calculated heat index
"""
Domoticz.Debug("temp: {}".format(temp))
Domoticz.Debug("humidity: {}".format(humidity))
if 0 <= humidity <= 100 and temp >= 26:
c1 = -8.78469475556
c2 = 1.61139411
c3 = 2.33854883889
c4 = -0.14611605
c5 = -0.012308094
c6 = -0.0164248277778
c7 = 0.002211732
c8 = 0.00072546
c9 = -0.000003582
tempp = temp ** 2
humidityp = humidity ** 2
hi = (
c1
+ c2 * temp
+ c3 * humidity
+ c4 * temp * humidity
+ c5 * tempp
+ c6 * humidityp
+ c7 * tempp * humidity
+ c8 * temp * humidityp
+ c9 * tempp * humidityp
)
else:
hi = temp
return round(hi, 1)
def float_or_none(value):
try:
return float(value)
except:
return None
def int_or_none(value):
try:
return int(value)
except:
return None