forked from lgkahn/hubitat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecowittsensor.groovy
1801 lines (1400 loc) · 64.4 KB
/
ecowittsensor.groovy
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
/**
* Driver: Ecowitt RF Sensor
* Author: Mirco Caramori
* Repository: https://github.com/mircolino/ecowitt
* Import URL: https://raw.githubusercontent.com/mircolino/ecowitt/master/ecowitt_sensor.groovy
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*
* Change Log: shared with ecowitt_gateway.groovy
* lgk add debugging with auto turn off so we can see if it is getting temp because it wont show an update event in hubitat logs if the same as last temp.
* lgk add lastTemperatuer and lastHumidity attributes so we can easily write rules to trigger if the temp or humidity is going up or down.
* I use this to alert when the hot tub will be at max in xx amount of time etc.
*
* lgk add code for capablity Air Quality using aqi
*
*/
metadata {
definition(name: "Ecowitt RF Sensor", namespace: "mircolino", author: "Mirco Caramori", importUrl: "https://raw.githubusercontent.com/mircolino/ecowitt/master/ecowitt_sensor.groovy") {
capability "Sensor";
capability "Battery";
capability "Temperature Measurement";
capability "Relative Humidity Measurement";
capability "Pressure Measurement";
capability "Ultraviolet Index";
capability "Illuminance Measurement";
capability "Water Sensor";
capability "CarbonDioxide Measurement";
capability "Air Quality";
// attribute "battery", "number"; // 0-100%
attribute "batteryIcon", "number"; // 0, 20, 40, 60, 80, 100
attribute "batteryOrg", "number"; // original/un-translated battery value returned by the sensor
attribute "batteryTemp", "number"; //
attribute "batteryTempIcon", "number"; // Only created/used when a WH32 is bundled in a PWS
attribute "batteryTempOrg", "number"; //
attribute "batteryRain", "number"; //
attribute "batteryRainIcon", "number"; // Only created/used when a WH40 is bundled in a PWS
attribute "batteryRainOrg", "number"; //
attribute "batteryWind", "number"; //
attribute "batteryWindIcon", "number"; // Only created/used when a WH68/WH80 is bundled in a PWS
attribute "batteryWindOrg", "number"; //
// attribute "temperature", "number"; // °F
// attribute "humidity", "number"; // 0-100%
attribute "humidityAbs", "number"; // oz/yd³ or g/m³
attribute "dewPoint", "number"; // °F - calculated using outdoor "temperature" & "humidity"
attribute "heatIndex", "number"; // °F - calculated using outdoor "temperature" & "humidity"
attribute "heatDanger", "string"; // Heat index danger level
attribute "heatColor", "string"; // Heat index HTML color
attribute "simmerIndex", "number"; // °F - calculated using outdoor "temperature" & "humidity"
attribute "simmerDanger", "string"; // Summer simmmer index danger level
attribute "simmerColor", "string"; // Summer simmer index HTML color
// attribute "pressure", "number"; // inHg - relative pressure corrected to sea-level
attribute "pressureAbs", "number"; // inHg - absolute pressure
attribute "rainRate", "number"; // in/h - rainfall rate
attribute "rainEvent", "number"; // in - rainfall in the current event
attribute "rainHourly", "number"; // in - rainfall in the current hour
attribute "rainDaily", "number"; // in - rainfall in the current day
attribute "rainWeekly", "number"; // in - rainfall in the current week
attribute "rainMonthly", "number"; // in - rainfall in the current month
attribute "rainYearly", "number"; // in - rainfall in the current year
attribute "rainTotal", "number"; // in - rainfall total since sensor installation
attribute "pm25", "number"; // µg/m³ - PM2.5 particle reading - current
attribute "pm25_avg_24h", "number"; // µg/m³ - PM2.5 particle reading - average over the last 24 hours
attribute "pm10", "number"; // µg/m³ - PM10 particle reading - current
attribute "pm10_avg_24h", "number"; // µg/m³ - PM10 particle reading - average over the last 24 hours
// attribute "co2", "number"; // ppm - CO2 concetration - current
attribute "carbonDioxide_avg_24h", "number"; // ppm - CO2 concetration - average over the last 24 hours
attribute "aqi", "number"; // AQI (0-500)
attribute "aqiDanger", "string"; // AQI danger level
attribute "aqiColor", "string"; // AQI HTML color
attribute "aqi_avg_24h", "number"; // AQI (0-500) - average over the last 24 hours
attribute "aqiDanger_avg_24h", "string"; // AQI danger level - average over the last 24 hours
attribute "aqiColor_avg_24h", "string"; // AQI HTML color - average over the last 24 hours
// attribute "water", "enum", ["dry", "wet"]; // "dry" or "wet"
attribute "waterMsg", "string"; // dry) "Dry", wet) "Leak detected!"
attribute "waterColor", "string"; // dry) "ffffff", wet) "ff0000" to colorize the icon
attribute "lightningTime", "string"; // Strike time - local time
attribute "lightningDistance", "number"; // Strike distance - km
attribute "lightningEnergy", "number"; // Strike energy - MJ/m
attribute "lightningCount", "number"; // Strike total count
// attribute "ultravioletIndex", "number"; // UV index (0-11+)
attribute "ultravioletDanger", "string"; // UV danger (0-2.9) Low, (3-5.9) Medium, (6-7.9) High, (8-10.9) Very High, (11+) Extreme
attribute "ultravioletColor", "string"; // UV HTML color
// attribute "illuminance", "number"; // lux
attribute "solarRadiation", "number"; // W/m²
attribute "windDirection", "number"; // 0-359°
attribute "windCompass", "string"; // NNE
attribute "windDirection_avg_10m", "number"; // 0-359° - average over the last 10 minutes
attribute "windCompass_avg_10m", "string"; // NNE - average over the last 10 minutes
attribute "windSpeed", "number"; // mph
attribute "windSpeed_avg_10m", "number"; // mph - average over the last 10 minutes
attribute "windGust", "number"; // mph
attribute "windGustMaxDaily", "number"; // mph - max in the current day
attribute "windChill", "number"; // °F - calculated using outdoor "temperature" & "windSpeed"
attribute "windDanger", "string"; // Windchill danger level
attribute "windColor", "string"; // Windchill HTML color
attribute "html", "string"; //
attribute "html1", "string"; //
attribute "html2", "string"; // e.g. "<div>Temperature: ${temperature}°F<br>Humidity: ${humidity}%</div>"
attribute "html3", "string"; //
attribute "html4", "string"; //
attribute "status", "string"; // Display current driver status
attribute "orphaned", "enum", ["false", "true"]; // Whether or not the unbundled sensor is still receiving data from the gateway
attribute "orphanedTemp", "enum", ["false", "true"]; // Whether or not the bundled WH32 is still receiving data from the gateway
attribute "orphanedRain", "enum", ["false", "true"]; // Whether or not the bundled WH40 is still receiving data from the gateway
attribute "orphanedWind", "enum", ["false", "true"]; // Whether or not the bundled WH68/WH80 sensor is still receiving data from the gateway
attribute "lastUpdate", "string"
attribute "bundled", "string"
attribute "rainLastUpdate", "string"
attribute "windLastUpdate", "string"
attribute "temperatureLastUpdate", "string"
attribute "humidityLastUpdate", "string"
attribute "lightningLastUpdate", "string"
attribute "lastTemperature", "number"
attribute "lastHumidity", "number"
attribute "temperatureChange", "number"
attribute "humidityChange", "number"
}
preferences {
input(name: "htmlTemplate", type: "string", title: "<font style='font-size:12px; color:#1a77c9'>Tile HTML Template(s)</font>", description: "<font style='font-size:12px; font-style: italic'>See <u><a href='https://github.com/mircolino/ecowitt/blob/master/readme.md#templates' target='_blank'>documentation</a></u> for input formats</font>", defaultValue: "");
input("debug", "bool", title: "Enable logging?", required: true, defaultValue: false)
if (localAltitude != null) {
input(name: "localAltitude", type: "string", title: "<font style='font-size:12px; color:#1a77c9'><u><a href='https://www.advancedconverter.com/map-tools/altitude-on-google-maps' target='_blank'>Altitude</a></u> to Correct Sea Level Pressure</font>", description: "<font style='font-size:12px; font-style: italic'>Examples: \"378 ft\" or \"115 m\"</font>", defaultValue: "", required: true);
}
if (voltageMin != null) {
input(name: "voltageMin", type: "string", title: "<font style='font-size:12px; color:#1a77c9'>Empty Battery Voltage</font>", description: "<font style='font-size:12px; font-style: italic'>Sensor value when battery is empty</font>", defaultValue: "", required: true);
input(name: "voltageMax", type: "string", title: "<font style='font-size:12px; color:#1a77c9'>Full Battery Voltage</font>", description: "<font style='font-size:12px; font-style: italic'>Sensor value when battery is full</font>", defaultValue: "", required: true);
}
if (calcDewPoint != null) {
input(name: "calcDewPoint", type: "bool", title: "<font style='font-size:12px; color:#1a77c9'>Calculate Dew Point & Absolute Humidity</font>", description: "<font style='font-size:12px; font-style: italic'>Temperature below which water vapor will condense & amount of water contained in a parcel of air</font>", defaultValue: false);
}
if (calcHeatIndex != null) {
input(name: "calcHeatIndex", type: "bool", title: "<font style='font-size:12px; color:#1a77c9'>Calculate Heat Index</font>", description: "<font style='font-size:12px; font-style: italic'>Perceived discomfort as a result of the combined effects of the air temperature and humidity</font>", defaultValue: false);
}
if (calcSimmerIndex != null) {
input(name: "calcSimmerIndex", type: "bool", title: "<font style='font-size:12px; color:#1a77c9'>Calculate Summer Simmer Index</font>", description: "<font style='font-size:12px; font-style: italic'>Similar to the Heat Index but using a newer and more accurate formula</font>", defaultValue: false);
}
if (calcWindChill != null) {
input(name: "calcWindChill", type: "bool", title: "<font style='font-size:12px; color:#1a77c9'>Calculate Wind-chill Factor</font>", description: "<font style='font-size:12px; font-style: italic'>Lowering of body temperature due to the passing-flow of lower-temperature air</font>", defaultValue: false);
}
}
}
/*
* State variables used by the driver:
*
* sensor \
* sensorTemp | null) not present, 0) waiting to receive data, 1) processing data
* sensorRain |
* sensorWind /
*
*/
/*
* Data variables used by the driver:
*
* "isBundled" // "true" if we are a bundled PWS (set by the parent at creation time)
* "htmlTemplate" // User template 0
* "htmlTemplate1" // User template 1
* "htmlTemplate2" // User template 2
* "htmlTemplate3" // User template 3
* "htmlTemplate4" // User template 4
*/
// Logging --------------------------------------------------------------------------------------------------------------------
private void logError(String str) { log.error(str); }
private void logWarning(String str) { if (getParent().logGetLevel() > 0) log.warn(str); }
private void logInfo(String str) { if (getParent().logGetLevel() > 1) log.info(str); }
private void logDebug(String str) { if (getParent().logGetLevel() > 2) log.debug(str); }
private void logTrace(String str) { if (getParent().logGetLevel() > 3) log.trace(str); }
// Ztatus ---------------------------------------------------------------------------------------------------------------------
private Boolean ztatus(String str, String color = null) {
if (color) str = "<font style='color:${color}'>${str}</font>";
return (attributeUpdateString(str, "status"));
}
// ------------------------------------------------------------
private Boolean ztatusIsError() {
String str = device.currentValue("status") as String;
if (str && str.contains("<font style='color:red'>")) return (true);
return (false);
}
// Conversions ----------------------------------------------------------------------------------------------------------------
private Boolean unitSystemIsMetric() {
//
// Return true if the selected unit system is metric
//
return (getParent().unitSystemIsMetric());
}
// ------------------------------------------------------------
private String timeEpochToLocal(String time) {
//
// Convert Unix Epoch time (seconds) to local time with locale format
//
try {
Long epoch = time.toLong() * 1000L;
Date date = new Date(epoch);
java.text.SimpleDateFormat format = new java.text.SimpleDateFormat();
time = format.format(date);
}
catch (Exception e) {
logError("Exception in timeEpochToLocal(): ${e}");
}
return (time);
}
// ------------------------------------------------------------
private BigDecimal convertRange(BigDecimal val, BigDecimal inMin, BigDecimal inMax, BigDecimal outMin, BigDecimal outMax, Boolean returnInt = true) {
// Let make sure ranges are correct
assert (inMin <= inMax);
assert (outMin <= outMax);
// Restrain input value
if (val < inMin) val = inMin;
else if (val > inMax) val = inMax;
val = ((val - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
if (returnInt) {
// If integer is required we use the Float round because the BigDecimal one is not supported/not working on Hubitat
val = val.toFloat().round().toBigDecimal();
}
return (val);
}
// ------------------------------------------------------------
private BigDecimal convert_F_to_C(BigDecimal val) {
return ((val - 32) / 1.8);
}
// ------------------------------------------------------------
private BigDecimal convert_C_to_F(BigDecimal val) {
return ((val * 1.8) + 32);
}
// ------------------------------------------------------------
private BigDecimal convert_inHg_to_hPa(BigDecimal val) {
return (val * 33.863886666667);
}
// ------------------------------------------------------------
private BigDecimal convert_hPa_to_inHg(BigDecimal val) {
return (val / 33.863886666667);
}
// ------------------------------------------------------------
private BigDecimal convert_in_to_mm(BigDecimal val) {
return (val * 25.4);
}
// ------------------------------------------------------------
private BigDecimal convert_mm_to_in(BigDecimal val) {
return (val / 25.4);
}
// ------------------------------------------------------------
private BigDecimal convert_ft_to_m(BigDecimal val) {
return (val / 3.28084);
}
// ------------------------------------------------------------
private BigDecimal convert_m_to_ft(BigDecimal val) {
return (val * 3.28084);
}
// ------------------------------------------------------------
private BigDecimal convert_mi_to_km(BigDecimal val) {
return (val * 1.609344);
}
// ------------------------------------------------------------
private BigDecimal convert_km_to_mi(BigDecimal val) {
return (val / 1.609344);
}
// ------------------------------------------------------------
private BigDecimal convert_Wm2_to_lux(BigDecimal val) {
return (val / 0.0079);
}
// ------------------------------------------------------------
private BigDecimal convert_lux_to_Wm2(BigDecimal val) {
return (val * 0.0079);
}
// ------------------------------------------------------------
private BigDecimal convert_gm3_to_ozyd3(BigDecimal val) {
return (val / 37.079776);
}
// ------------------------------------------------------------
private BigDecimal convert_ozyd3_to_gm3(BigDecimal val) {
return (val * 37.079776);
}
// Attribute handling ----------------------------------------------------------------------------------------------------------
private Boolean attributeUpdateString(String val, String attribute) {
//
// Only update "attribute" if different
// Return true if "attribute" has actually been updated/created
//
if ((device.currentValue(attribute) as String) != val) {
sendEvent(name: attribute, value: val);
return (true);
}
return (false);
}
// ------------------------------------------------------------
private Boolean attributeUpdateNumber(BigDecimal val, String attribute, String measure = null, Integer decimals = -1) {
//
// Only update "attribute" if different
// Return true if "attribute" has actually been updated/created
//
// If rounding is required we use the Float one because the BigDecimal is not supported/not working on Hubitat
if (debug) log.debug "in attr update number val [ $val attribute = $attribute"
if (decimals >= 0) val = val.toFloat().round(decimals).toBigDecimal();
BigDecimal integer = val.toBigInteger();
// We don't strip zeros on an integer otherwise it gets converted to scientific exponential notation
val = (val == integer)? integer: val.stripTrailingZeros();
// Coerce Object -> BigDecimal
if ((device.currentValue(attribute) as BigDecimal) != val) {
if (measure) sendEvent(name: attribute, value: val, unit: measure);
else sendEvent(name: attribute, value: val);
return (true);
}
return (false);
}
// ------------------------------------------------------------
private List<String> attributeEnumerate(Boolean existing = true) {
//
// Return a list of all available attributes
// If "existing" == true return only those that have been already created (non-null ones)
// Returned list can be empty but never return null
//
List<String> list = [];
List<com.hubitat.hub.domain.Attribute> attrib = device.getSupportedAttributes();
if (attrib) {
attrib.each {
if (existing == false || device.currentValue(it.name) != null) list.add(it.name);
}
}
return (list);
}
// ------------------------------------------------------------
private Boolean attributeUpdateBattery(String val, String attribBattery, String attribBatteryIcon, String attribBatteryOrg, Integer type) {
//
// Convert all different batteries returned values to a 0-100% range
// Type: 1) voltage: range from 1.30V (empty) to 1.65V (full)
// 2) pentastep: range from 0 (empty) to 5 (full)
// 0) binary: 0 (full) or 1 (empty)
//
BigDecimal original = val.toBigDecimal();
BigDecimal percent;
BigDecimal icon;
String unitOrg;
// log.debug "in attribute update battery val = $val attrib = $attribBattery type = $type"
switch (type) {
case 1:
// Change range from voltage to (0% - 100%)
BigDecimal vMin, vMax;
if (!(settings.voltageMin) || !(settings.voltageMax)) {
// First time: initialize and show the preference
vMin = 1.3;
vMax = 1.65;
device.updateSetting("voltageMin", [value: vMin, type: "string"]);
device.updateSetting("voltageMax", [value: vMax, type: "string"]);
}
else {
vMin = (settings.voltageMin).toBigDecimal();
vMax = (settings.voltageMax).toBigDecimal();
}
percent = convertRange(original, vMin, vMax, 0, 100);
unitOrg = "V";
break;
case 2:
// Change range from (0 - 5) to (0% - 100%)
percent = convertRange(original, 0, 5, 0, 100);
unitOrg = "level";
break;
default:
// Change range from (0 or 1) to (100% or 0%)
percent = (original == 0)? 100: 0;
unitOrg = "!bool";
}
if (percent < 10) icon = 0;
else if (percent < 30) icon = 20;
else if (percent < 50) icon = 40;
else if (percent < 70) icon = 60;
else if (percent < 90) icon = 80;
else icon = 100;
Boolean updated = attributeUpdateNumber(percent, attribBattery, "%", 0);
if (attributeUpdateNumber(icon, attribBatteryIcon, "%")) updated = true;
if (attributeUpdateNumber(original, attribBatteryOrg, unitOrg)) updated = true;
return (updated);
}
// -----------------------------
private Boolean attributeUpdateLowestBattery() {
BigDecimal percent = 100;
String org = "0";
Integer type = 0;
BigDecimal temp = device.currentValue("batteryTemp") as BigDecimal;
BigDecimal rain = device.currentValue("batteryRain") as BigDecimal;
BigDecimal wind = device.currentValue("batteryWind") as BigDecimal;
if (temp != null) {
percent = temp;
org = device.currentValue("batteryTempOrg") as String;
type = 0;
}
if (rain != null && rain < percent) {
percent = rain;
org = device.currentValue("batteryRainOrg") as String;
type = 1;
}
if (wind != null && wind < percent) {
percent = wind;
org = device.currentValue("batteryWindOrg") as String;
type = 1;
}
return (attributeUpdateBattery(org, "battery", "batteryIcon", "batteryOrg", type));
}
// ------------------------------------------------------------
private Boolean attributeUpdateTemperature(String val, String attribTemperature) {
BigDecimal degrees = val.toBigDecimal();
String measure = "°F";
// Convert to metric if requested
if (unitSystemIsMetric()) {
degrees = convert_F_to_C(degrees);
measure = "°C";
}
Boolean hasChanged = (attributeUpdateNumber(degrees, attribTemperature, measure, 1))
// only do this if actually temp not other attributes that come through here like dew pt
if (attribTemperature == "temperature")
{
def lastTemp = (device.currentValue(attribTemperature) as BigDecimal)
BigDecimal change = 0.00
if (lastTemp != null)
change = (degrees - lastTemp as BigDecimal)
else lastTemp = 0.00
attributeUpdateNumber(lastTemp,"lastTemperature",measure,1)
if (debug) log.debug "In update temp val = $val , measure = $measure, attribute = $attribTemperature, lastTemp = $lastTemp, change = $change, hasChanged = $hasChanged"
// only log difference if we have a changed value.
if (hasChanged == true)
{
sendEvent(name: "temperatureChange", value: change)
}
else
{
sendEvent(name: "temperatureChange", value: 0.00)
}
}
return hasChanged
}
// ------------------------------------------------------------
private Boolean attributeUpdateHumidity(String val, String attribHumidity) {
BigDecimal percent = val.toBigDecimal();
def now = new Date().format('MM/dd/yyyy h:mm a',location.timeZone)
sendEvent(name: "humidityLastUpdate", value: now)
def lastHumid = (device.currentValue(attribHumidity) as BigDecimal)
BigDecimal change = 0.00
if (lastHumid != null)
change = (percent - lastHumid as BigDecimal)
else lastHumid = 0.00
attributeUpdateNumber(lastHumid,"lastHumidity","%",0)
Boolean hasChanged = (attributeUpdateNumber(percent, attribHumidity, "%", 0))
// only log difference if we have a changed value.
if (hasChanged == true)
sendEvent(name: "humidityChange", value: change)
else sendEvent(name: "humidityChange", value: 0.00)
return hasChanged
}
// ------------------------------------------------------------
private Boolean attributeUpdatePressure(String val, String attribPressure, String attribPressureAbs) {
// Get unit system
Boolean metric = unitSystemIsMetric();
// Get pressure in hectopascal
BigDecimal absolute = convert_inHg_to_hPa(val.toBigDecimal());
// Get altitude in meters
val = settings.localAltitude;
if (!val) {
// First time: initialize and show the preference
val = metric? "0 m": "0 ft";
device.updateSetting("localAltitude", [value: val, type: "string"]);
}
BigDecimal altitude;
try {
String[] field = val.split();
altitude = field[0].toBigDecimal();
if (field.size() == 1) {
// No unit found: let's use the parent setting
if (!metric) altitude = convert_ft_to_m(altitude);
}
else {
// Found a unit: convert accordingly
if (field[1][0] == "f" || field[1][0] == "F") altitude = convert_ft_to_m(altitude);
}
}
catch(Exception ignored) {
altitude = 0;
}
// Get temperature in celsious
BigDecimal temperature = (device.currentValue("temperature") as BigDecimal);
if (temperature == null) temperature = 18;
else if (!metric) temperature = convert_F_to_C(temperature);
// Correct pressure to sea level using this conversion formula: https://keisan.casio.com/exec/system/1224575267
BigDecimal relative = absolute * Math.pow(1 - ((altitude * 0.0065) / (temperature + (altitude * 0.0065) + 273.15)), -5.257);
// Convert to imperial if requested
if (metric) val = "hPa";
else {
absolute = convert_hPa_to_inHg(absolute);
relative = convert_hPa_to_inHg(relative);
val = "inHg";
}
Boolean updated = attributeUpdateNumber(relative, attribPressure, val, 2);
if (attributeUpdateNumber(absolute, attribPressureAbs, val, 2)) updated = true;
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateRain(String val, String attribRain, Boolean hour = false) {
BigDecimal amount = val.toBigDecimal();
String measure = hour? "in/h": "in";
// Convert to metric if requested
if (unitSystemIsMetric()) {
amount = convert_in_to_mm(amount);
measure = hour? "mm/h": "mm";
}
def now = new Date().format('MM/dd/yyyy h:mm a',location.timeZone)
sendEvent(name: "rainLastUpdate", value: now)
attributeUpdateString("false", "orphanedRain");
return (attributeUpdateNumber(amount, attribRain, measure, 2));
}
// ------------------------------------------------------------
private Boolean attributeUpdatePM(String val, String attribPm) {
BigDecimal pm = val.toBigDecimal();
return (attributeUpdateNumber(pm, attribPm, "µg/m³"));
}
// ------------------------------------------------------------
private Boolean attributeUpdateAQI(String val, Boolean pm25, String attribAqi, String attribAqiDanger, String attribAqiColor) {
//
// Conversions based on https://en.wikipedia.org/wiki/Air_quality_index
//
BigDecimal pm = val.toBigDecimal();
BigDecimal aqi;
if (pm25) {
// PM2.5
if (pm < 12.1) aqi = convertRange(pm, 0.0, 12.0, 0, 50);
else if (pm < 35.5) aqi = convertRange(pm, 12.1, 35.4, 51, 100);
else if (pm < 55.5) aqi = convertRange(pm, 35.5, 55.4, 101, 150);
else if (pm < 150.5) aqi = convertRange(pm, 55.5, 150.4, 151, 200);
else if (pm < 250.5) aqi = convertRange(pm, 150.5, 250.4, 201, 300);
else if (pm < 350.5) aqi = convertRange(pm, 250.5, 350.4, 301, 400);
else aqi = convertRange(pm, 350.5, 500.4, 401, 500);
}
else {
// PM10
if (pm < 55) aqi = convertRange(pm, 0, 54, 0, 50);
else if (pm < 155) aqi = convertRange(pm, 55, 154, 51, 100);
else if (pm < 255) aqi = convertRange(pm, 155, 254, 101, 150);
else if (pm < 355) aqi = convertRange(pm, 255, 354, 151, 200);
else if (pm < 425) aqi = convertRange(pm, 355, 424, 201, 300);
else if (pm < 505) aqi = convertRange(pm, 425, 504, 301, 400);
else aqi = convertRange(pm, 505, 604, 401, 500);
// Choose the highest AQI between PM2.5 and PM10
BigDecimal aqi25 = (device.currentValue(attribAqi) as BigDecimal);
if (aqi < aqi25) aqi = aqi25;
}
String danger;
String color;
if (aqi < 51) { danger = "Good"; color = "3ea72d"; }
else if (aqi < 101) { danger = "Moderate"; color = "fff300"; }
else if (aqi < 151) { danger = "Unhealthy for Sensitive Groups"; color = "f18b00"; }
else if (aqi < 201) { danger = "Unhealthy"; color = "e53210"; }
else if (aqi < 301) { danger = "Very Unhealthy"; color = "b567a4"; }
else if (aqi < 401) { danger = "Hazardous"; color = "7e0023"; }
else { danger = "Hazardous"; color = "7e0023"; }
// lgk set airQualityIndex only if actual aqi not avg
if (attribAqi == "aqi") attributeUpdateNumber(aqi, "airQualityIndex", "AQI");
Boolean updated = attributeUpdateNumber(aqi, attribAqi, "AQI");
if (attributeUpdateString(danger, attribAqiDanger)) updated = true;
if (attributeUpdateString(color, attribAqiColor)) updated = true;
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateCarbonDioxide(String val, String attribCo2) {
BigDecimal co2 = val.toBigDecimal();
return (attributeUpdateNumber(co2, attribCo2, "ppm"));
}
// ------------------------------------------------------------
private Boolean attributeUpdateLeak(String val, String attribWater, String attribWaterMsg, String attribWaterColor) {
BigDecimal leak = (val.toBigDecimal())? 1: 0;
String water, message, color;
if (leak) {
water = "wet";
message = "Leak detected!";
color = "ff0000";
}
else {
water = "dry";
message = "Dry";
color = "ffffff";
}
Boolean updated = attributeUpdateString(water, attribWater);
if (attributeUpdateString(message, attribWaterMsg)) updated = true;
if (attributeUpdateString(color, attribWaterColor)) updated = true;
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateLightningDistance(String val, String attrib) {
if (!val) val = "0";
BigDecimal distance = val.toBigDecimal();
String measure = "km";
// Convert to imperial if requested
if (unitSystemIsMetric() == false) {
distance = convert_km_to_mi(distance);
measure = "mi";
}
return (attributeUpdateNumber(distance, attrib, measure, 1));
}
// ------------------------------------------------------------
private Boolean attributeUpdateLightningCount(String val, String attrib) {
if (!val) val = "0";
def now = new Date().format('MM/dd/yyyy h:mm a',location.timeZone)
sendEvent(name: "lightningLastUpdate", value: now)
return (attributeUpdateNumber(val.toBigDecimal(), attrib));
}
// ------------------------------------------------------------
private Boolean attributeUpdateLightningTime(String val, String attrib) {
val = (!val || val == "0")? "n/a": timeEpochToLocal(val);
return (attributeUpdateString(val, attrib));
}
// ------------------------------------------------------------
private Boolean attributeUpdateLightningEnergy(String val, String attrib) {
if (!val) val = "0";
return (attributeUpdateNumber(val.toBigDecimal(), attrib, "MJ/m", 1));
}
// ------------------------------------------------------------
private Boolean attributeUpdateUV(String val, String attribUvIndex, String attribUvDanger, String attribUvColor) {
//
// Conversions based on https://en.wikipedia.org/wiki/Ultraviolet_index
//
BigDecimal index = val.toBigDecimal();
String danger;
String color;
if (index < 3) { danger = "Low"; color = "3ea72d"; }
else if (index < 6) { danger = "Medium"; color = "fff300"; }
else if (index < 8) { danger = "High"; color = "f18b00"; }
else if (index < 11) { danger = "Very High"; color = "e53210"; }
else { danger = "Extreme"; color = "b567a4"; }
Boolean updated = attributeUpdateNumber(index, attribUvIndex, "uvi");
if (attributeUpdateString(danger, attribUvDanger)) updated = true;
if (attributeUpdateString(color, attribUvColor)) updated = true;
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateLight(String val, String attribSolarRadiation, String attribIlluminance) {
BigDecimal light = val.toBigDecimal();
Boolean updated = attributeUpdateNumber(light, attribSolarRadiation, "W/m²");
if (attributeUpdateNumber(convert_Wm2_to_lux(light), attribIlluminance, "lux", 0)) updated = true;
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateWindSpeed(String val, String attribWindSpeed) {
BigDecimal speed = val.toBigDecimal();
String measure = "mph";
// Convert to metric if requested
if (unitSystemIsMetric()) {
speed = convert_mi_to_km(speed);
measure = "km/h";
}
def now = new Date().format('MM/dd/yyyy h:mm a',location.timeZone)
sendEvent(name: "windLastUpdate", value: now)
attributeUpdateString("false", "orphanedWind");
return (attributeUpdateNumber(speed, attribWindSpeed, measure, 1));
}
// ------------------------------------------------------------
private Boolean attributeUpdateWindDirection(String val, String attribWindDirection, String attribWindCompass) {
BigDecimal direction = val.toBigDecimal();
// BigDecimal doesn't support modulo operation so we roll up our own
direction = direction - (direction.divideToIntegralValue(360) * 360);
String compass;
if (direction >= 348.75 || direction < 11.25) compass = "N";
else if (direction < 33.75) compass = "NNE";
else if (direction < 56.25) compass = "NE";
else if (direction < 78.75) compass = "ENE";
else if (direction < 101.25) compass = "E";
else if (direction < 123.75) compass = "ESE";
else if (direction < 146.25) compass = "SE";
else if (direction < 168.75) compass = "SSE";
else if (direction < 191.25) compass = "S";
else if (direction < 213.75) compass = "SSW";
else if (direction < 236.25) compass = "SW";
else if (direction < 258.75) compass = "WSW";
else if (direction < 281.25) compass = "W";
else if (direction < 303.75) compass = "WNW";
else if (direction < 326.25) compass = "NW";
else compass = "NNW";
Boolean updated = attributeUpdateNumber(direction, attribWindDirection, "°");
if (attributeUpdateString(compass, attribWindCompass)) updated = true;
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateDewPoint(String val, String attribDewPoint, String attribHumidityAbs) {
Boolean updated = false;
BigDecimal temperature = (device.currentValue("temperature") as BigDecimal);
if (temperature != null) {
if (settings.calcDewPoint == null) {
// First time: initialize and show the preference
device.updateSetting("calcDewPoint", [value: false, type: "bool"]);
}
else if (settings.calcDewPoint) {
if (!unitSystemIsMetric()) {
// Convert temperature to C
temperature = convert_F_to_C(temperature);
}
// Calculate dewPoint based on https://web.archive.org/web/20150209041650/http://www.gorhamschaffler.com:80/humidity_formulas.htm
BigDecimal humidity = val.toBigDecimal();
double tC = temperature as double;
// Calculate saturation vapor pressure in millibars
BigDecimal e = (tC < 0) ?
6.1115 * Math.exp((23.036 - (tC / 333.7)) * (tC / (279.82 + tC))) :
6.1121 * Math.exp((18.678 - (tC / 234.4)) * (tC / (257.14 + tC)));
// Calculate current vapor pressure in millibars
e *= humidity / 100;
BigDecimal degrees = (-430.22 + 237.7 * Math.log(e)) / (-Math.log(e) + 19.08);
// Calculate humidityAbs based on https://carnotcycle.wordpress.com/2012/08/04/how-to-convert-relative-humidity-to-absolute-humidity/
BigDecimal volume = ((6.1121 * Math.exp((17.67 * tC) / (tC + 243.5)) * (humidity as double) * 2.1674)) / (tC + 273.15);
if (!unitSystemIsMetric()) {
degrees = convert_C_to_F(degrees);
volume = convert_gm3_to_ozyd3(volume);
}
if (attributeUpdateTemperature(degrees.toString(), attribDewPoint)) updated = true;
if (attributeUpdateNumber(volume, attribHumidityAbs, unitSystemIsMetric()? "g/m³": "oz/yd³", 2)) updated = true;
}
}
return (updated);
}
// ------------------------------------------------------------
private Boolean attributeUpdateHeatIndex(String val, String attribHeatIndex, String attribHeatDanger, String attribHeatColor) {
Boolean updated = false;
BigDecimal temperature = (device.currentValue("temperature") as BigDecimal);
if (temperature != null) {
if (settings.calcHeatIndex == null) {
// First time: initialize and show the preference
device.updateSetting("calcHeatIndex", [value: false, type: "bool"]);
}
else if (settings.calcHeatIndex) {
if (unitSystemIsMetric()) {
// Convert temperature back to F
temperature = convert_C_to_F(temperature);
}
// Calculate heatIndex based on https://en.wikipedia.org/wiki/Heat_index
BigDecimal degrees;
String danger;
String color;
if (temperature < 80) {
degrees = temperature;
danger = "Safe";
color = "ffffff";
}
else {
BigDecimal humidity = val.toBigDecimal();
degrees = -42.379 +
( 2.04901523 * temperature) +
( 10.14333127 * humidity) -
( 0.22475541 * (temperature * humidity)) -
( 0.00683783 * (temperature ** 2)) -
( 0.05481717 * (humidity ** 2)) +
( 0.00122874 * ((temperature ** 2) * humidity)) +
( 0.00085282 * (temperature * (humidity ** 2))) -
( 0.00000199 * ((temperature ** 2) * (humidity ** 2)));
if (degrees < 80) { danger = "Safe"; color = "ffffff"; }
else if (degrees < 91) { danger = "Caution"; color = "ffff66"; }
else if (degrees < 104) { danger = "Extreme Caution"; color = "ffd700"; }
else if (degrees < 126) { danger = "Danger"; color = "ff8c00"; }
else { danger = "Extreme Danger"; color = "ff0000"; }
}
updated = attributeUpdateTemperature(degrees.toString(), attribHeatIndex);
if (attributeUpdateString(danger, attribHeatDanger)) updated = true;
if (attributeUpdateString(color, attribHeatColor)) updated = true;