forked from lgkahn/hubitat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
openweatheralerts
1836 lines (1710 loc) · 97.2 KB
/
openweatheralerts
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
/*
OpenWeatherMap-Alerts Weather Driver
Import URL: https://raw.githubusercontent.com/HubitatCommunity/OpenWeatherMap-Alerts-Weather-Driver/master/OpenWeatherMap-Alerts%2520Weather%2520Driver.groovy
Copyright 2020 @Matthew (Scottma61)
This driver has morphed many, many times, so the genesis is very blurry now. It stated as a WeatherUnderground
driver, then when they restricted their API it morphed into an APIXU driver. When APIXU ceased it became a
Dark Sky driver .... and now that Dark Sky is going away it is morphing into a OpenWeatherMap driver.
Many people contributed to the creation of this driver. Significant contributors include:
- @Cobra who adapted it from @mattw01's work and I thank them for that!
- @bangali for his original APIXU.COM base code that much of the early versions of this driver was
adapted from.
- @bangali for his the Sunrise-Sunset.org code used to calculate illuminance/lux and the more
recent adaptations of that code from @csteele in his continuation driver 'wx-ApiXU'.
- @csteele (and prior versions from @bangali) for the attribute selection code.
- @csteele for his examples on how to convert to asyncHttp calls to reduce Hub resource utilization.
- @bangali also contributed the icon work from
https://github.com/jebbett for new cooler 'Alternative' weather icons with icons courtesy
of https://www.deviantart.com/vclouds/art/VClouds-Weather-Icons-179152045.
- @storageanarchy for his Dark Sky Icon mapping and some new icons to compliment the Vclouds set.
- @nh.schottfam for lots of code clean up and optimizations.
In addition to all the cloned code from the Hubitat community, I have heavily modified/created new
code myself @Matthew (Scottma61) with lots of help from the Hubitat community. If you believe you
should have been acknowledged or received attribution for a code contribution, I will happily do so.
While I compiled and orchestrated the driver, very little is actually original work of mine.
This driver is free to use. I do not accept donations. Please feel free to contribute to those
mentioned here if you like this work, as it would not have been possible without them.
This driver is intended to pull weather data from OpenWeatherMap.org (https://OpenWeatherMap.org). You will need your
OpenWeatherMap API key to use the data from that site. It also pulls in weather alerts from the Nation Weather
Service's API (weather.gov). At the present time there is no API required for consume Alert data.
The driver exposes both metric and imperial measurements for you to select from.
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.
Last Update 06/10/2022
{ Left room below to document version changes...}
V0.5.5 06/10/2022 corrected PoP1 & PoP2 from not displaying when extended precipitation forcast was slected.
V0.5.4 04/17/2022 Fallback for Sunrise-Sunset.org failure.
V0.5.3 08/11/2021 Exposed cloud coverage forecasts.
V0.5.2 01/26/2021 Corrected a display issue on Alerts.
V0.5.1 12/12/2020 Changes to dahboard tile logo/hyperlinks when using weather.gov for alerts and there is an alert.
V0.5.0 12/08/2020 Bug fix for 'forecast_textn' optional attributes.
V0.4.9 12/03/2020 New tinyurl for icons. Added tinyurl for weather.gov alert poll.
V0.4.8 12/01/2020 Added ability to select Weather Alert source (none/OWM/Weather.gov {US Only}).
V0.4.7 11/26/2020 Bug fixes. Fix timeouts on http calls (by @nh.schottfam).
V0.4.6 11/06/2020 Refactored the dashboard tiles.
V0.4.5 10/31/2020 Tweaked threedayfcstTile for small screens.
V0.4.4 10/30/2020 More code cleanups/reductions/optimizations by @nh.schottfam.
V0.4.3 10/29/2020 Bug fixes and the usual code cleanup/reduction/optimizations by @nh.schottfam.
V0.4.2 10/29/2020 Yet another Precip bux fix.
V0.4.1 10/29/2020 Move today's precip back to 'Daily'. More bux fixes.
V0.4.0 10/28/2020 More Bux fixes for new Probability of Precipitation (PoP) from OWM.
V0.3.9 10/28/2020 Bux fixes for new Probability of Precipitation (PoP) from OWM.
V0.3.8 10/28/2020 Added Probability of Precipitation (PoP) from OWM. Bug fixes and code and string reductions by @nh.schottfam).
V0.3.7 10/27/2020 Bug fixes.
V0.3.6 10/27/2020 Removed '+' from attribute names. Three Day Tile now has optional 'Low/High' or 'High/Low' setting.
V0.3.5 10/25/2020 Bug fixes for null JSON returns.
V0.3.4 10/24/2020 Added indicator of multiple alerts in tiles. Minor bug fixes (by @nh.schottfam).
V0.3.3 10/23/2020 Code optimizations and minor bug fixes (by @nh.schottfam).
V0.3.2 10/22/2020 Removed 'NWS' from driver name, minor bug fixes.
V0.3.1 10/21/2020 Improved OWM URLs in the dashboard tiles to pull in location's city code (if available).
V0.3.0 10/21/2020 Better OWM URLs in the dashboard tiles.
V0.2.9 10/20/2020 Correcting some Tile displays from the last update.
V0.2.8 10/20/2020 Pulling Alerts from OWM instead of NWS.
V0.2.7 10/19/2020 Added forecast 'Morn', 'Day', 'Eve' and 'Night' temperatures for current day and tomorrow.
V0.2.6 10/07/2020 Change to use asynchttp for NWS alerts (by @nh.schottfam).
V0.2.5 10/02/2020 More string constant optimizations (by @nh.schottfam)
V0.2.4 09/27/2020 Fix to allow for use of multiple virtual devices, More string constant optimizations (by @nh.schottfam)
V0.2.3 09/24/2020 More string constant optimizations, and removal of white space characters (by @nh.schottfam)
V0.2.2 09/23/2020 Removing 'urgency' restrictions from alerts poll
V0.2.1 09/22/2020 Added forecast icon url attributes for tomorrow and day-after-tomorrow
V0.2.0 09/21/2020 Added forecast High/Low temp attributes for tomorrow and day-after-tomorrow
V0.1.9 09/16/2020 Removing 'severity' and 'certainty' restrictions from alerts poll
V0.1.8 09/13/2020 Re-worked Alerts to not be dependent on api.weather.gov returning a valid response code
V0.1.7 09/12/2020 Remove most DB accesses and string cleanup (by @nh.schottfam)
V0.1.6 09/08/2020 Restoring 'certainty' to weather.gov alert poll
V0.1.5 09/08/2020 Removed 'certainty' from weather.gov alert poll
V0.1.4 09/07/2020 Bug fix for NullPointerException on line 580
V0.1.3 09/05/2020 Improved Alert handling for dashboard tiles, again, various bug fixes
V0.1.2 07/02/2020 Bug fix sync MyTile and weatherSummary tiles upon alert update
V0.1.1 06/06/2020 Bug fix to exclude minutely and hourly data in poll
V0.1.0 05/07/2020 Improved Alert handling for dashboard tiles, various bug fixes
V0.0.9 04/24/2020 Continue to work on improving null handling, various bug fixes
V0.0.8 4/23/2020-2 Numerous bug fixes, better handling where alerts are not available, handling nulls
V0.0.7 04/23/2020 Numerous bug fixes, better handling where alerts are not available
V0.0.6 04/20/2020 Refactored much of the code, added Hubitat Package Manager compatibility
V0.0.5 04/19/2020 More code cleanup and optimizations (Thanks @nh.schottfam!)
V0.0.4 04/18/2020 Corrected forecast icon to always be 'day' instead of current time
V0.0.3 04/18/2020 More fixes on Alerts, mapped condition_code, weatherIcon(s)
V0.0.2 04/17/2020 Fixed Alerts on myTile and alertTile, Capitalized condition_text
V0.0.1 04/17/2020 Initial conversion from Dark Sky to OWM
=========================================================================================================
**ATTRIBUTES CAUTION**
The way the 'optional' attributes work:
- Initially, only the optional attributes selected will show under 'Current States' and will be available
in dashboard.
- Once an attribute has been selected it too will show under 'Current States' and be available in dashboard.
<*** HOWEVER ***> If you ever de-select the optional attribute, it will still show under 'Current States'
and will still show as an attribute for dashboards **BUT IT'S DATA WILL NO LONGER BE REFRESHED WITH DATA
POLLS**. This means what is shown on the 'Current States' and dashboard tiles for de-selected attributes
may not be current valid data.
- To my knowledge, the only way to remove the de-selected attribute from 'Current States' and not show it as
available in the dashboard is to delete the virtual device and create a new one AND DO NOT SELECT the
attribute you do not want to show.
*/
//file:noinspection GroovyUnusedAssignment
static String version() { return '0.5.5' }
import groovy.transform.Field
metadata {
definition (name: 'OpenWeatherMap-Alerts Weather Driver',
namespace: 'Matthew',
author: 'Scottma61',
importUrl: 'https://raw.githubusercontent.com/HubitatCommunity/OpenWeatherMap-Alerts-Weather-Driver/master/OpenWeatherMap-Alerts%2520Weather%2520Driver.groovy') {
capability 'Sensor'
capability 'Temperature Measurement'
capability 'Illuminance Measurement'
capability 'Relative Humidity Measurement'
capability 'Pressure Measurement'
capability 'Ultraviolet Index'
capability 'Refresh'
attributesMap.each {
k, v -> if (v.ty) attribute k, v.ty
}
// The following attributes may be needed for dashboards that require these attributes,
// so they are alway available and shown by default.
attribute 'city', sSTR //Hubitat OpenWeather SharpTool.io SmartTiles
attribute 'feelsLike', sNUM //SharpTool.io SmartTiles
attribute 'forecastIcon', sSTR //SharpTool.io
attribute 'localSunrise', sSTR //SharpTool.io SmartTiles
attribute 'localSunset', sSTR //SharpTool.io SmartTiles
attribute 'percentPrecip', sNUM //SharpTool.io SmartTiles
attribute 'pressured', sSTR //UNSURE SharpTool.io SmartTiles
attribute 'weather', sSTR //SharpTool.io SmartTiles
attribute 'weatherIcon', sSTR //SharpTool.io SmartTiles
attribute 'weatherIcons', sSTR //Hubitat openWeather
attribute 'wind', sNUM //SharpTool.io
attribute 'windDirection', sNUM //Hubitat OpenWeather
attribute 'windSpeed', sNUM //Hubitat OpenWeather
// The attributes below are sub-groups of optional attributes. They need to be listed here to be available
//alert
attribute 'alert', sSTR
attribute 'alertTile', sSTR
attribute 'alertDescr', sSTR
attribute 'alertSender', sSTR
//threedayTile
attribute 'threedayfcstTile', sSTR
//fcstHighLow
attribute 'forecastHigh', sNUM
attribute 'forecastHigh1', sNUM
attribute 'forecastHigh2', sNUM
attribute 'forecastLow', sNUM
attribute 'forecastLow1', sNUM
attribute 'forecastLow2', sNUM
attribute 'forecastMorn', sNUM
attribute 'forecastDay', sNUM
attribute 'forecastEve', sNUM
attribute 'forecastNight', sNUM
attribute 'forecastMorn1', sNUM
attribute 'forecastDay1', sNUM
attribute 'forecastEve1', sNUM
attribute 'forecastNight1', sNUM
attribute 'forecast_text1', sSTR
attribute 'forecast_text2', sSTR
attribute 'condition_icon_url1', sSTR
attribute 'condition_icon_url2', sSTR
//controlled with localSunrise
attribute 'tw_begin', sSTR
attribute 'sunriseTime', sSTR
attribute 'noonTime', sSTR
attribute 'sunsetTime', sSTR
attribute 'tw_end', sSTR
//obspoll
attribute 'last_poll_Forecast', sSTR // time the poll was initiated
attribute 'last_observation_Forecast', sSTR // datestamp of the forecast observation
//precipExtended
attribute 'rainTomorrow', sNUM
attribute 'rainDayAfterTomorrow', sNUM
attribute 'Precip0', sNUM
attribute 'Precip1', sNUM
attribute 'Precip2', sNUM
attribute 'PoP1', sNUM
attribute 'PoP2', sNUM
//cloudExtended
attribute 'cloudToday', sNUM
attribute 'cloudTomorrow', sNUM
attribute 'cloudDayAfterTomorrow', sNUM
command 'pollData'
}
preferences() {
String settingDescr = settingEnable ? '<br><i>Hide many of the optional attributes to reduce the clutter, if needed, by turning OFF this toggle.</i><br>' : '<br><i>Many optional attributes are available to you, if needed, by turning ON this toggle.</i><br>'
section('Query Inputs'){
input 'apiKey', 'text', required: true, title: 'Type OpenWeatherMap.org API Key Here', defaultValue: null
input 'city', 'text', required: true, defaultValue: 'City or Location name forecast area', title: 'City name'
input 'pollIntervalForecast', 'enum', title: 'External Source Poll Interval (daytime)', required: true, defaultValue: '3 Hours', options: ['Manual Poll Only', '2 Minutes', '5 Minutes', '10 Minutes', '15 Minutes', '30 Minutes', '1 Hour', '3 Hours']
input 'pollIntervalForecastnight', 'enum', title: 'External Source Poll Interval (nighttime)', required: true, defaultValue: '3 Hours', options: ['Manual Poll Only', '2 Minutes', '5 Minutes', '10 Minutes', '15 Minutes', '30 Minutes', '1 Hour', '3 Hours']
input 'logSet', 'bool', title: 'Enable extended Logging', description: '<i>Extended logging will turn off automatically after 30 minutes.</i>', required: true, defaultValue: false
input 'alertSource', 'enum', required: true, defaultValue: sONE, title: 'Weather Alert Source<br>0=None 1=OWM or 2=Weather.gov (US only)', options: [0:sZERO, 1:sONE, 2:sTWO]
input 'tempFormat', 'enum', required: true, defaultValue: 'Fahrenheit (°F)', title: 'Display Unit - Temperature: Fahrenheit (°F) or Celsius (°C)', options: ['Fahrenheit (°F)', 'Celsius (°C)']
input 'TWDDecimals', 'enum', required: true, defaultValue: sZERO, title: 'Display decimals for Temperature & Wind Speed', options: [0:sZERO, 1:sONE, 2:'2', 3:'3', 4:'4']
input 'RDecimals', 'enum', required: true, defaultValue: sZERO, title: 'Display decimals for Precipitation', options: [0:sZERO, 1:sONE, 2:'2', 3:'3', 4:'4']
input 'PDecimals', 'enum', required: true, defaultValue: sZERO, title: 'Display decimals for Pressure', options: [0:sZERO, 1:sONE, 2:'2', 3:'3', 4:'4']
input 'datetimeFormat', 'enum', required: true, defaultValue: sONE, title: 'Display Unit - Date-Time Format', options: [1:'m/d/yyyy 12 hour (am|pm)', 2:'m/d/yyyy 24 hour', 3:'mm/dd/yyyy 12 hour (am|pm)', 4:'mm/dd/yyyy 24 hour', 5:'d/m/yyyy 12 hour (am|pm)', 6:'d/m/yyyy 24 hour', 7:'dd/mm/yyyy 12 hour (am|pm)', 8:'dd/mm/yyyy 24 hour', 9:'yyyy/mm/dd 24 hour']
input 'distanceFormat', 'enum', required: true, defaultValue: 'Miles (mph)', title: 'Display Unit - Distance/Speed: Miles, Kilometers, knots or meters', options: ['Miles (mph)', 'Kilometers (kph)', 'knots', 'meters (m/s)']
input 'pressureFormat', 'enum', required: true, defaultValue: 'Inches', title: 'Display Unit - Pressure: Inches or Millibar/Hectopascal', options: ['Inches', 'Millibar', 'Hectopascal']
input 'rainFormat', 'enum', required: true, defaultValue: 'Inches', title: 'Display Unit - Precipitation: Inches or Millimeters', options: ['Inches', 'Millimeters']
input 'luxjitter', 'bool', title: 'Use lux jitter control (rounding)?', required: true, defaultValue: false
// https://tinyurl.com/icnqz/ points to https://raw.githubusercontent.com/HubitatCommunity/WeatherIcons/master/
input 'iconLocation', 'text', required: true, defaultValue: 'https://tinyurl.com/icnqz/', title: 'Alternative Icon Location:'
input 'iconType', 'bool', title: 'Condition Icon: On=Current or Off=Forecast', required: true, defaultValue: false
input 'altCoord', 'bool', required: true, defaultValue: false, title: "Override Hub's location coordinates"
if (altCoord) {
input 'altLat', sSTR, title: 'Override location Latitude', required: true, defaultValue: location.latitude.toString(), description: '<br>Enter location Latitude<br>'
input 'altLon', sSTR, title: 'Override location Longitude', required: true, defaultValue: location.longitude.toString(), description: '<br>Enter location Longitude<br>'
}
input 'settingEnable', 'bool', title: '<b>Display All Optional Attributes</b>', description: settingDescr, defaultValue: true
//build a Selector for each mapped Attribute or group of attributes
attributesMap.each {
keyname, attribute ->
if (settingEnable) {
input keyname+'Publish', 'bool', title: attribute.t, required: true, defaultValue: attribute.defa, description: sBR+(String)attribute.d+sBR
if(keyname == 'threedayTile') input 'threedayLH', 'bool', title: 'Three Day Temp Display', description: '<br>High/Low: On or Low/High: Off<br>', required: true, defaultValue: false
if(keyname == 'weatherSummary') input 'summaryType', 'bool', title: 'Full Weather Summary', description: '<br>Full: on or short: off summary?<br>', required: true, defaultValue: false
}
}
if (settingEnable) {
input 'windPublish', 'bool', title: 'Wind Speed', required: true, defaultValue: sFLS, description: '<br>Display wind speed<br>'
}
}
}
}
@Field static final String sNULL=(String)null
@Field static final String sAB='<a>'
@Field static final String sACB='</a>'
@Field static final String sCSPAN='</span>'
@Field static final String sBR='<br>'
@Field static final String sBLK=''
@Field static final String sSPC=' '
@Field static final String sRB='>'
@Field static final String sCOMMA=','
@Field static final String sMINUS='-'
@Field static final String sCOLON=':'
@Field static final String sZERO='0'
@Field static final String sONE='1'
@Field static final String sTWO='2'
@Field static final String sDOT='.'
@Field static final String sICON='iconLocation'
@Field static final String sTMETR='tMetric'
@Field static final String sDMETR='dMetric'
@Field static final String sPMETR='pMetric'
@Field static final String sRMETR='rMetric'
@Field static final String sTEMP='temperature'
@Field static final String sSUMLST='Summary_last_poll_time'
@Field static final String sTRU='true'
@Field static final String sFLS='false'
@Field static final String sNPNG='na.png'
@Field static final String s11D='11d.png'
@Field static final String s11N='11n.png'
@Field static final String sCTS='chancetstorms'
@Field static final String sNCTS='nt_chancetstorms'
@Field static final String sRAIN='rain'
@Field static final String sNRAIN='nt_rain'
@Field static final String sPCLDY='partlycloudy'
@Field static final String sNPCLDY='nt_partlycloudy'
@Field static final String s23='23.png'
@Field static final String s9='9.png'
@Field static final String s39='39.png'
@Field static final String sDF='°F'
@Field static final String sIMGS5='<img class="cI" src='
@Field static final String sIMGS8='<img class="cIb" src='
@Field static final String sTD='<td>'
@Field static final String sTR='<tr><td>'
@Field static final String sSTR='string'
@Field static final String sNUM='number'
@Field static final String sNCWA='No current weather alerts for this area'
// <<<<<<<<<< Begin Sunrise-Sunset Poll Routines >>>>>>>>>>
void pollSunRiseSet() {
if(ifreInstalled()) { updated(); return }
String currDate = new Date().format('yyyy-MM-dd', TimeZone.getDefault())
LOGINFO('Polling Sunrise-Sunset.org')
Map requestParams = [ uri: 'https://api.sunrise-sunset.org/json?lat=' + (String)altLat + '&lng=' + (String)altLon + '&formatted=0', timeout: 20 ]
if (currDate) {requestParams = [ uri: 'https://api.sunrise-sunset.org/json?lat=' + (String)altLat + '&lng=' + (String)altLon + '&formatted=0&date=' + currDate, timeout: 20 ]}
LOGINFO('Poll Sunrise-Sunset: ' + requestParams.toString())
asynchttpGet('sunRiseSetHandler', requestParams)
}
void sunRiseSetHandler(resp, data) {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Map sunRiseSet = resp.getJson().results
myUpdData('sunRiseSet', resp.data.toString())
LOGINFO('Sunrise-Sunset Data: ' + sunRiseSet.toString())
if(ifreInstalled()) { updated(); return }
if(myGetData('sunRiseSet')==sNULL) {
pauseExecution(1000)
pollSunRiseSet()
return
}
String tfmt='yyyy-MM-dd\'T\'HH:mm:ssXXX'
String tfmt1='HH:mm'
myUpdData('riseTime', new Date().parse(tfmt, (String)sunRiseSet.sunrise).format(tfmt1, TimeZone.getDefault()))
myUpdData('noonTime', new Date().parse(tfmt, (String)sunRiseSet.solar_noon).format(tfmt1, TimeZone.getDefault()))
myUpdData('setTime', new Date().parse(tfmt, (String)sunRiseSet.sunset).format(tfmt1, TimeZone.getDefault()))
myUpdData('tw_begin', new Date().parse(tfmt, (String)sunRiseSet.civil_twilight_begin).format(tfmt1, TimeZone.getDefault()))
myUpdData('tw_end', new Date().parse(tfmt, (String)sunRiseSet.civil_twilight_end).format(tfmt1, TimeZone.getDefault()))
myUpdData('localSunset',new Date().parse(tfmt, (String)sunRiseSet.sunset).format(myGetData('timeFormat'), TimeZone.getDefault()))
myUpdData('localSunrise', new Date().parse(tfmt, (String)sunRiseSet.sunrise).format(myGetData('timeFormat'), TimeZone.getDefault()))
myUpdData('riseTime1', new Date().parse(tfmt, (String)sunRiseSet.sunrise).plus(1).format(tfmt1, TimeZone.getDefault()))
myUpdData('riseTime2', new Date().parse(tfmt, (String)sunRiseSet.sunrise).plus(2).format(tfmt1, TimeZone.getDefault()))
myUpdData('setTime1', new Date().parse(tfmt, (String)sunRiseSet.sunset).plus(1).format(tfmt1, TimeZone.getDefault()))
myUpdData('setTime2', new Date().parse(tfmt, (String)sunRiseSet.sunset).plus(2).format(tfmt1, TimeZone.getDefault()))
}else{
LOGWARN('Sunrise-Sunset api did not return data.')
myUpdData('sunRiseSet', sNULL)
myUpdData('localSunset', todaysSunrise.format(myGetData('timeFormat'), TimeZone.getDefault()))
myUpdData('localSunrise', todaysSunset.format(myGetData('timeFormat'), TimeZone.getDefault()))
}
}
// >>>>>>>>>> End Sunrise-Sunset Poll Routines <<<<<<<<<<
// <<<<<<<<<< Begin OWM Poll Routines >>>>>>>>>>
void pollOWM() {
if(ifreInstalled()) { updated(); return }
if( apiKey == null ) {
LOGWARN('OpenWeatherMap API Key not found. Please configure in preferences.')
return
}
/* for testing a different Lat/Lon location uncommnent the two lines below */
// String altLat = "44.809122" //"41.5051613" // "40.6" //"38.627003" //"30.6953657"
// String altLon = "-68.735892" //"-81.6934446" // "-75.43" //"-90.199402" //-88.0398912"
Map ParamsOWM
ParamsOWM = [ uri: 'https://api.openweathermap.org/data/2.5/onecall?lat=' + (String)altLat + '&lon=' + (String)altLon + '&exclude=minutely,hourly&mode=json&units=imperial&appid=' + (String)apiKey, timeout: 20 ]
LOGINFO('Poll OpenWeatherMap.org: ' + ParamsOWM)
asynchttpGet('pollOWMHandler', ParamsOWM)
}
void pollOWMHandler(resp, data) {
LOGINFO('Polling OpenWeatherMap.org')
if(resp.getStatus() != 200 && resp.getStatus() != 207) {
LOGWARN('Calling https://api.openweathermap.org/data/2.5/onecall?lat=' + (String)altLat + '&lon=' + (String)altLon + '&exclude=minutely,hourly&mode=json&units=imperial&appid=' + (String)apiKey)
LOGWARN(resp.getStatus() + sCOLON + resp.getErrorMessage())
}else{
Map owm = parseJson(resp.data)
LOGINFO('OpenWeatherMap Data: ' + owm.toString())
if(ifreInstalled()) { updated(); return }
if(owm.toString()==sNULL) {
pauseExecution(1000)
pollOWM()
return
}
Date fotime = (owm?.current?.dt==null) ? new Date() : new Date((Long)owm.current.dt * 1000L)
myUpdData('fotime', fotime.toString())
Date futime = new Date()
myUpdData('futime', futime.toString())
myUpdData(sSUMLST, futime.format(myGetData('timeFormat'), TimeZone.getDefault()).toString())
myUpdData('Summary_last_poll_date', futime.format(myGetData('dateFormat'), TimeZone.getDefault()).toString())
myUpdData('currDate', new Date().format('yyyy-MM-dd', TimeZone.getDefault()))
myUpdData('currTime', new Date().format('HH:mm', TimeZone.getDefault()))
if(myGetData('riseTime') <= myGetData('currTime') && myGetData('setTime') >= myGetData('currTime')) {
myUpdData('is_day', sTRU)
}else{
myUpdData('is_day', sFLS)
}
if(myGetData('currTime') < myGetData('tw_begin') || myGetData('currTime') > myGetData('tw_end')) {
myUpdData('is_light', sFLS)
}else{
myUpdData('is_light', sTRU)
}
if(myGetData('is_light') != myGetData('is_lightOld')) {
if(myGetData('is_light')==sTRU) {
log.info('OpenWeatherMap.org Weather Driver - INFO: Switching to Daytime schedule.')
}else{
log.info('OpenWeatherMap.org Weather Driver - INFO: Switching to Nighttime schedule.')
}
initialize_poll()
myUpdData('is_lightOld', myGetData('is_light'))
}
// >>>>>>>>>> End Setup Global Variables <<<<<<<<<<
// <<<<<<<<<< Begin Process Standard Weather-Station Variables (Regardless of Forecast Selection) >>>>>>>>>>
Integer mult_twd = myGetData('mult_twd')==sNULL ? 1 : myGetData('mult_twd').toInteger()
Integer mult_p = myGetData('mult_p')==sNULL ? 1 : myGetData('mult_p').toInteger()
Integer mult_r = myGetData('mult_r')==sNULL ? 1 : myGetData('mult_r').toInteger()
String ddisp_twd = myGetData('ddisp_twd')==sNULL ? '%3.0f' : myGetData('ddisp_twd')
Boolean isF = myGetData(sTMETR) == sDF
BigDecimal t_dew = owm?.current?.dew_point
myUpdData('dewpoint', adjTemp(t_dew, isF, mult_twd))
myUpdData('humidity', (Math.round((owm?.current?.humidity==null ? 0.00 : owm.current.humidity.toBigDecimal()) * 10) / 10).toString())
BigDecimal t_press = owm?.current?.pressure==null ? 0.00 : owm.current.pressure.toBigDecimal()
if(myGetData(sPMETR) == 'inHg') {
t_press = Math.round(t_press * 0.029529983071445 * mult_p) / mult_p
}else{
t_press = Math.round(t_press * mult_p) / mult_p
}
myUpdData('pressure', t_press.toString())
myUpdData(sTEMP, adjTemp(owm?.current?.temp, isF, mult_twd))
String w_string_bft=sNULL
String w_bft_icon=sNULL
BigDecimal t_ws = owm?.current?.wind_speed==null ? 0.00 : owm.current.wind_speed.toBigDecimal()
if(t_ws < 1.0) {
w_string_bft = 'Calm'; w_bft_icon = 'wb0.png'
}else if(t_ws < 4.0) {
w_string_bft = 'Light air'; w_bft_icon = 'wb1.png'
}else if(t_ws < 8.0) {
w_string_bft = 'Light breeze'; w_bft_icon = 'wb2.png'
}else if(t_ws < 13.0) {
w_string_bft = 'Gentle breeze'; w_bft_icon = 'wb3.png'
}else if(t_ws < 19.0) {
w_string_bft = 'Moderate breeze'; w_bft_icon = 'wb4.png'
}else if(t_ws < 25.0) {
w_string_bft = 'Fresh breeze'; w_bft_icon = 'wb5.png'
}else if(t_ws < 32.0) {
w_string_bft = 'Strong breeze'; w_bft_icon = 'wb6.png'
}else if(t_ws < 39.0) {
w_string_bft = 'High wind, moderate gale, near gale'; w_bft_icon = 'wb7.png'
}else if(t_ws < 47.0) {
w_string_bft = 'Gale, fresh gale'; w_bft_icon = 'wb8.png'
}else if(t_ws < 55.0) {
w_string_bft = 'Strong/severe gale'; w_bft_icon = 'wb9.png'
}else if(t_ws < 64.0) {
w_string_bft = 'Storm, whole gale'; w_bft_icon = 'wb10.png'
}else if(t_ws < 73.0) {
w_string_bft = 'Violent storm'; w_bft_icon = 'wb11.png'
}else if(t_ws >= 73.0) {
w_string_bft = 'Hurricane force'; w_bft_icon = 'wb12.png'
}
myUpdData('wind_string_bft', w_string_bft)
myUpdData('wind_bft_icon', w_bft_icon)
BigDecimal t_wd = owm?.current?.wind_speed==null ? 0.00 : owm.current.wind_speed.toBigDecimal()
BigDecimal t_wg = owm?.current?.wind_gust==null ? t_wd : owm.current.wind_gust.toBigDecimal()
if(myGetData(sDMETR) == 'MPH') {
t_wd = Math.round(t_wd * mult_twd) / mult_twd
t_wg = Math.round(t_wg * mult_twd) / mult_twd
} else if(myGetData(sDMETR) == 'KPH') {
t_wd = Math.round(t_wd * 1.609344 * mult_twd) / mult_twd
t_wg = Math.round(t_wg * 1.609344 * mult_twd) / mult_twd
} else if(myGetData(sDMETR) == 'knots') {
t_wd = Math.round(t_wd * 0.868976 * mult_twd) / mult_twd
t_wg = Math.round(t_wg * 0.868976 * mult_twd) / mult_twd
}else{ // this leave only m/s
t_wd = Math.round(t_wd * 0.44704 * mult_twd) / mult_twd
t_wg = Math.round(t_wg * 0.44704 * mult_twd) / mult_twd
}
myUpdData('wind', t_wd.toString())
myUpdData('wind_gust', t_wg.toString())
BigDecimal twb = owm?.current?.wind_deg==null ? 0.00 : owm.current.wind_deg.toBigDecimal()
myUpdData('wind_degree', twb.toInteger().toString())
String w_cardinal=sNULL
String w_direction=sNULL
if(twb < 11.25) {
w_cardinal = 'N'; w_direction = 'North'
}else if(twb < 33.75) {
w_cardinal = 'NNE'; w_direction = 'North-Northeast'
}else if(twb < 56.25) {
w_cardinal = 'NE'; w_direction = 'Northeast'
}else if(twb < 56.25) {
w_cardinal = 'ENE'; w_direction = 'East-Northeast'
}else if(twb < 101.25) {
w_cardinal = 'E'; w_direction = 'East'
}else if(twb < 123.75) {
w_cardinal = 'ESE'; w_direction = 'East-Southeast'
}else if(twb < 146.25) {
w_cardinal = 'SE'; w_direction = 'Southeast'
}else if(twb < 168.75) {
w_cardinal = 'SSE'; w_direction = 'South-Southeast'
}else if(twb < 191.25) {
w_cardinal = 'S'; w_direction = 'South'
}else if(twb < 213.75) {
w_cardinal = 'SSW'; w_direction = 'South-Southwest'
}else if(twb < 236.25) {
w_cardinal = 'SW'; w_direction = 'Southwest'
}else if(twb < 258.75) {
w_cardinal = 'WSW'; w_direction = 'West-Southwest'
}else if(twb < 281.25) {
w_cardinal = 'W'; w_direction = 'West'
}else if(twb < 303.75) {
w_cardinal = 'WNW'; w_direction = 'West-Northwest'
}else if(twb < 326.25) {
w_cardinal = 'NW'; w_direction = 'Northwest'
}else if(twb < 348.75) {
w_cardinal = 'NNW'; w_direction = 'North-Northwest'
}else if(twb >= 348.75) {
w_cardinal = 'N'; w_direction = 'North'
}
myUpdData('wind_direction', w_direction)
myUpdData('wind_cardinal', w_cardinal)
myUpdData('wind_string', w_string_bft + ' from the ' + myGetData('wind_direction') + (myGetData('wind').toBigDecimal() < 1.0 ? sBLK: ' at ' + String.format(ddisp_twd, myGetData('wind').toBigDecimal()) + sSPC + myGetData(sDMETR)))
// >>>>>>>>>> End Process Standard Weather-Station Variables (Regardless of Forecast Selection) <<<<<<<<<<
Integer cloudCover = owm?.current?.clouds==null ? 1 : owm.current.clouds <= 1 ? 1 : owm.current.clouds
myUpdData('cloud', cloudCover.toString())
myUpdData('vis', (myGetData(sDMETR)!='MPH' ? Math.round(owm?.current?.visibility==null ? 0.01 : owm.current.visibility.toBigDecimal() * 0.001 * mult_twd) / mult_twd : Math.round(owm?.current?.visibility==null ? 0.00 : owm.current.visibility.toBigDecimal() * 0.0006213712 * mult_twd) / mult_twd).toString())
List owmCweat = owm?.current?.weather
myUpdData('condition_id', owmCweat==null || owmCweat[0]?.id==null ? '999' : owmCweat[0].id.toString())
myUpdData('condition_code', getCondCode(myGetData('condition_id').toInteger(), myGetData('is_day')))
myUpdData('condition_text', owmCweat==null || owmCweat[0]?.description==null ? 'Unknown' : owmCweat[0].description.capitalize())
myUpdData('OWN_icon', owmCweat == null || owmCweat[0]?.icon==null ? (myGetData('is_day')==sTRU ? '50d' : '50n') : owmCweat[0].icon)
List owmDaily = owm?.daily != null && ((List)owm.daily)[0]?.weather != null ? ((List)owm?.daily)[0].weather : null
myUpdData('forecast_id', owmDaily==null || owmDaily[0]?.id==null ? '999' : owmDaily[0].id.toString())
myUpdData('forecast_code', getCondCode(myGetData('forecast_id').toInteger(), sTRU))
myUpdData('forecast_text', owmDaily==null || owmDaily[0]?.description==null ? 'Unknown' : owmDaily[0].description.capitalize())
owmDaily = owm?.daily != null ? (List)owm.daily : null
BigDecimal t_p0 = (owmDaily==null || !owmDaily[0]?.rain ? 0.00 : owmDaily[0].rain.toBigDecimal()) + (owmDaily==null || !owmDaily[0]?.snow ? 0.00 : owmDaily[0].snow.toBigDecimal())
myUpdData('rainToday', (Math.round((myGetData(sRMETR) == 'in' ? t_p0 * 0.03937008 : t_p0) * mult_r) / mult_r).toString())
myUpdData('PoP', (!owmDaily[0].pop ? 0 : Math.round(owmDaily[0].pop.toBigDecimal() * 100.toInteger())).toString())
myUpdData('percentPrecip', myGetData('PoP'))
if(owmDaily && (threedayTilePublish || precipExtendedPublish || myTile2Publish)) {
BigDecimal t_p1 = (owmDaily==null || !owmDaily[1]?.rain ? 0.00 : owmDaily[1].rain.toBigDecimal()) + (owmDaily==null || !owmDaily[1]?.snow ? 0.00 : owmDaily[1].snow.toBigDecimal())
BigDecimal t_p2 = (owmDaily==null || !owmDaily[2]?.rain ? 0.00 : owmDaily[2].rain.toBigDecimal()) + (owmDaily==null || !owmDaily[2]?.snow ? 0.00 : owmDaily[2].snow.toBigDecimal())
myUpdData('Precip0', (Math.round((myGetData(sRMETR) == 'in' ? t_p0 * 0.03937008 : t_p0) * mult_r) / mult_r).toString())
myUpdData('Precip1', (Math.round((myGetData(sRMETR) == 'in' ? t_p1 * 0.03937008 : t_p1) * mult_r) / mult_r).toString())
myUpdData('Precip2', (Math.round((myGetData(sRMETR) == 'in' ? t_p2 * 0.03937008 : t_p2) * mult_r) / mult_r).toString())
myUpdData('PoP1', (!owmDaily[1].pop ? 0 : Math.round(owmDaily[1].pop.toBigDecimal() * 100.toInteger())).toString())
myUpdData('PoP2', (!owmDaily[2].pop ? 0 : Math.round(owmDaily[2].pop.toBigDecimal() * 100.toInteger())).toString())
}
if(owmDaily && cloudExtendedPublish) {
myUpdData('Cloud0', (owmDaily[0].clouds==null ? 1 : owmDaily[0].clouds <= 1 ? 1 : owmDaily[0].clouds).toString())
myUpdData('Cloud1', (owmDaily[1].clouds==null ? 1 : owmDaily[1].clouds <= 1 ? 1 : owmDaily[1].clouds).toString())
myUpdData('Cloud2', (owmDaily[2].clouds==null ? 1 : owmDaily[2].clouds <= 1 ? 1 : owmDaily[2].clouds).toString())
}
String imgT1=(myGetData(sICON).toLowerCase().contains('://github.com/') && myGetData(sICON).toLowerCase().contains('/blob/master/') ? '?raw=true' : sBLK)
if(owmDaily && owmDaily[1] && owmDaily[2]) {
String tmpImg0= myGetData(sICON) + getImgName((!owmDaily[0].weather[0].id ? 999 : owmDaily[0].weather[0].id.toInteger()), sTRU) + imgT1
String tmpImg1= myGetData(sICON) + getImgName((!owmDaily[1].weather[0].id ? 999 : owmDaily[1].weather[0].id.toInteger()), sTRU) + imgT1
String tmpImg2= myGetData(sICON) + getImgName((!owmDaily[2].weather[0].id ? 999 : owmDaily[2].weather[0].id.toInteger()), sTRU) + imgT1
if(threedayTilePublish || myTile2Publish || fcstHighLowPublish) {
myUpdData('day1', owmDaily[1]?.dt==null ? sBLK : new Date((Long)owmDaily[1].dt * 1000L).format('EEEE'))
myUpdData('day2', owmDaily[2]?.dt==null ? sBLK : new Date((Long)owmDaily[2].dt * 1000L).format('EEEE'))
myUpdData('is_day1', sTRU)
myUpdData('is_day2', sTRU)
myUpdData('forecast_id1', owmDaily[1]?.weather[0]?.id==null ? '999' : owmDaily[1].weather[0].id.toString())
myUpdData('forecast_code1', getCondCode(myGetData('forecast_id1').toInteger(), sTRU))
myUpdData('forecast_text1', owmDaily[1]?.weather[0]?.description==null ? 'Unknown' : owmDaily[1].weather[0].description.capitalize())
myUpdData('forecast_id2', owmDaily[2]?.weather[0]?.id==null ? '999' : owmDaily[2].weather[0].id.toString())
myUpdData('forecast_code2', getCondCode(myGetData('forecast_id2').toInteger(), sTRU))
myUpdData('forecast_text2', owmDaily[2]?.weather[0]?.description==null ? 'Unknown' : owmDaily[2].weather[0].description.capitalize())
myUpdData('forecastHigh1', adjTemp(owmDaily[1]?.temp?.max, isF, mult_twd))
myUpdData('forecastHigh2', adjTemp(owmDaily[2]?.temp?.max, isF, mult_twd))
myUpdData('forecastLow1', adjTemp(owmDaily[1]?.temp?.min, isF, mult_twd))
myUpdData('forecastLow2', adjTemp(owmDaily[2]?.temp?.min, isF, mult_twd))
myUpdData('forecastMorn', adjTemp(owmDaily[0]?.temp?.morn, isF, mult_twd))
myUpdData('forecastDay', adjTemp(owmDaily[0]?.temp?.day, isF, mult_twd))
myUpdData('forecastEve', adjTemp(owmDaily[0]?.temp?.eve, isF, mult_twd))
myUpdData('forecastNight', adjTemp(owmDaily[0]?.temp?.night, isF, mult_twd))
myUpdData('forecastMorn1', adjTemp(owmDaily[1]?.temp?.morn, isF, mult_twd))
myUpdData('forecastDay1', adjTemp(owmDaily[1]?.temp?.day, isF, mult_twd))
myUpdData('forecastEve1', adjTemp(owmDaily[1]?.temp?.eve, isF, mult_twd))
myUpdData('forecastNight1', adjTemp(owmDaily[1]?.temp?.night, isF, mult_twd))
myUpdData('imgName0', sIMGS5 + myGetData(sICON) + getImgName(myGetData('condition_id').toInteger(), myGetData('is_day')) + imgT1 + sRB) // For current condition text for 'Today'
// myUpdData('imgName0', sIMGS5 + tmpImg0 + sRB) // For daily forecasted condition text for 'Today'
myUpdData('imgName1', sIMGS5 + tmpImg1 + sRB)
myUpdData('imgName2', sIMGS5 + tmpImg2 + sRB)
}
if(condition_icon_urlPublish) {
sendEvent(name: 'condition_icon_url1', value: tmpImg1)
sendEvent(name: 'condition_icon_url2', value: tmpImg2)
}
}
myUpdData('forecastHigh', adjTemp(owmDaily[0]?.temp?.max, isF, mult_twd))
myUpdData('forecastLow', adjTemp(owmDaily[0]?.temp?.min, isF, mult_twd))
if(precipExtendedPublish){
myUpdData('rainTomorrow', myGetData('Precip1'))
myUpdData('rainDayAfterTomorrow', myGetData('Precip2'))
}
if(cloudExtendedPublish){
myUpdData('cloudToday', myGetData('Cloud0'))
myUpdData('cloudTomorrow', myGetData('Cloud1'))
myUpdData('cloudDayAfterTomorrow', myGetData('Cloud2'))
}
updateLux(false)
myUpdData('ultravioletIndex', (owm?.current?.uvi==null ? 0.00 : owm.current.uvi.toBigDecimal()).toString())
myUpdData('feelsLike', adjTemp(owm?.current?.feels_like, isF, mult_twd))
if(alertPublish) {
if(alertSource==sTWO) {
/* for testing a different Lat/Lon location uncommnent the two lines below */
// String altLat = "44.809122" //"41.5051613" // "40.6" //"38.627003" //"30.6953657"
// String altLon = "-68.735892" //"-81.6934446" // "-75.43" //"-90.199402" //-88.0398912"
pollWDG()
}
if((alertSource==sZERO) || (!owm.alerts && alertSource==sONE) || (myGetData('curAl')==sNCWA && alertSource==sTWO)) {
clearAlerts()
}else{
if(alertSource==sONE) {
Map owmAlerts0= owm?.alerts ? owm.alerts[0] : null
String curAl = owmAlerts0?.event==null ? sNCWA : owmAlerts0.event.replaceAll('\n', sSPC).replaceAll('[{}\\[\\]]', sBLK)
String curAlSender = owmAlerts0?.sender_name==null ? sNULL : owmAlerts0.sender_name.replaceAll('\n',sSPC).replaceAll('[{}\\[\\]]', sBLK)
String curAlDescr = owmAlerts0?.description==null ? sNULL : owmAlerts0.description.replaceAll('\n',sSPC).replaceAll('[{}\\[\\]]', sBLK).take(1024)
if(curAl==sNCWA) {
clearAlerts()
}else{
Integer alertCnt = 0
for(Integer i = 1;i<10;i++) {
if(owm?.alerts[i]?.event!=null) {
alertCnt = i
}
}
myUpdData('alertCnt', alertCnt.toString())
}
myUpdData('alert', curAl + (myGetData('alertCnt') != sZERO ? ' +' + myGetData('alertCnt') : sBLK))
myUpdData('curAlSender', curAlSender)
myUpdData('curAlDescr', curAlDescr)
LOGINFO('OWM Weather Alert: ' + curAl + '; Description: ' + curAlDescr.length() + ' ' +curAlDescr)
myUpdData('alertTileLink', '<a style="font-style:italic;color:red" href="https://openweathermap.org/city/' + myGetData('OWML') + '" target="_blank">'+myGetData('alert')+sACB)
myUpdData('alertLink', '<a style="font-style:italic;color:red">'+myGetData('alert')+sACB)
}else{
/* for testing a different Lat/Lon location uncommnent the two lines below */
// String altLat = "44.809122" //"41.5051613" // "40.6" //"38.627003" //"30.6953657"
// String altLon = "-68.735892" //"-81.6934446" // "-75.43" //"-90.199402" //-88.0398912"
myUpdData('alert', myGetData('curAl') + (myGetData('alertCnt') != sZERO ? ' +' + myGetData('alertCnt') : sBLK))
// https://tinyurl.com/zznws points to https://forecast.weather.gov/MapClick.php
myUpdData('alertTileLink', '<a style="font-style:italic;color:red" href="https://tinyurl.com/zznws?lat=' + altLat + '&lon=' + altLon +'" target=\'_blank\'>'+myGetData('alert')+sACB)
myUpdData('alertLink', '<a style="font-style:italic;color:red">'+myGetData('alert')+sACB)
if(myGetData('curAl')==sNCWA) {
clearAlerts()
}
}
myUpdData('noAlert',sFLS)
myUpdData('alertDescr', myGetData('curAlDescr'))
myUpdData('alertSender', myGetData('curAlSender'))
myUpdData('possAlert', sTRU)
}
// <<<<<<<<<< Begin Built alertTile >>>>>>>>>>
String alertTile = (myGetData('alert')== sNCWA ? 'No Weather Alerts for ' : 'Weather Alert for ') + myGetData('city') + (myGetData('alertSender')==null || myGetData('alertSender')==sSPC ? '' : ' issued by ' + myGetData('alertSender')) + sBR
alertTile+= myGetData('alertTileLink') + sBR
if(alertSource==sONE) {
alertTile+= '<a href="https://openweathermap.org/city/' + myGetData('OWML') + '" target="_blank">' + sIMGS5 + myGetData(sICON) + 'OWM.png style="height:2em"></a> @ ' + myGetData(sSUMLST)
}else{
if(alertSource==sTWO) {
alertTile+= '<a href=https://tinyurl.com/zznws?lat=' + altLat + '&lon=' + altLon + '" target="_blank">' + sIMGS5 + myGetData(sICON) + 'NWS_240px.png style="height:2em"></a> @ ' + myGetData(sSUMLST)
}
}
myUpdData('alertTile', alertTile)
sendEvent(name: 'alert', value: myGetData('alert'))
sendEvent(name: 'alertDescr', value: myGetData('alertDescr'))
sendEvent(name: 'alertSender', value: myGetData('alertSender'))
sendEvent(name: 'alertTile', value: myGetData('alertTile'))
// >>>>>>>>>> End Built alertTile <<<<<<<<<<
}
// >>>>>>>>>> End Setup Forecast Variables <<<<<<<<<<
// <<<<<<<<<< Begin Icon Processing >>>>>>>>>>
String imgName = (myGetData('iconType')== sTRU ? getImgName(myGetData('condition_id').toInteger(), myGetData('is_day')) : getImgName(myGetData('forecast_id').toInteger(), myGetData('is_day')))
sendEventPublish(name: 'condition_icon', value: sIMGS5 + myGetData(sICON) + imgName + imgT1 + sRB)
sendEventPublish(name: 'condition_iconWithText', value: sIMGS5 + myGetData(sICON) + imgName + imgT1 + sRB+ sBR + (myGetData('iconType')== sTRU ? myGetData('condition_text') : myGetData('forecast_text')))
sendEventPublish(name: 'condition_icon_url', value: myGetData(sICON) + imgName + imgT1)
myUpdData('condition_icon_url', myGetData(sICON) + imgName + imgT1)
sendEventPublish(name: 'condition_icon_only', value: imgName.split('/')[-1].replaceFirst('\\?raw=true',sBLK))
// >>>>>>>>>> End Icon Processing <<<<<<<<<<
PostPoll()
}
}
// >>>>>>>>>> End OpenWeatherMap Poll Routine <<<<<<<<<<
// <<<<<<<<<< Begin polling weather.gov for Alerts >>>>>>>>>>
void pollWDG() {
/* for testing a different Lat/Lon location uncommnent the two lines below */
// String altLat = "44.809122" //"41.5051613" // "40.6" //"38.627003" //"30.6953657"
// String altLon = "-68.735892" //"-81.6934446" // "-75.43" //"-90.199402" //-88.0398912"
Map wdgParams = [ uri: 'https://api.weather.gov/alerts/active?status=actual&message_type=alert,update&point=' + altLat + ',' + altLon,
requestContentType:'application/json',
contentType:'application/json',
timeout: 20
]
LOGINFO('Poll api.weather.gov/alerts/active: ' + wdgParams)
asynchttpGet('pollWDGHandler', wdgParams)
}
void pollWDGHandler(resp, data) {
LOGINFO('Polling weather.gov')
if(resp.getStatus() != 200 && resp.getStatus() != 207) {
LOGWARN('Calling https://api.weather.gov/alerts/active?status=actual&message_type=alert,update&point=' + altLat + ',' + altLon)
LOGWARN(resp.getStatus() + sCOLON + resp.getErrorMessage())
}else{
Map wdg = parseJson(resp.data)
myUpdData('wdg', wdg.toString())
LOGINFO('weather.gov Data: ' + wdg.toString())
if(wdg.toString()==sNULL) {
pauseExecution(1000)
pollWDG()
return
}
myUpdData('curAl', wdg?.features[0]?.properties?.event == null ? sNCWA : wdg.features[0].properties.event.replaceAll('\n', sSPC).replaceAll('[{}\\[\\]]', sBLK))
myUpdData('curAlSender', wdg?.features[0]?.properties?.senderName==null ? sNULL : wdg?.features[0]?.properties?.senderName.replaceAll('\n',sSPC).replaceAll('[{}\\[\\]]', sBLK))
myUpdData('curAlDescr', wdg?.features[0]?.properties?.description==null ? sNULL : wdg?.features[0]?.properties?.description.replaceAll('\n',sSPC).replaceAll('[{}\\[\\]]', sBLK).take(1024))
Integer alertCnt = 0
for(Integer i = 1;i<10;i++) {
if(wdg?.features[i]?.properties?.event!=null) {
alertCnt = i
}
}
myUpdData('alertCnt', alertCnt.toString())
}
}
// >>>>>>>>>> End polling weather.gov for Alerts <<<<<<<<<<
static String adjTemp(temp, Boolean isF, Integer mult_twd){
BigDecimal t_fl
t_fl = temp==null ? 0.00 : temp.toBigDecimal()
if(!isF) t_fl = (t_fl - 32.0) / 1.8
t_fl = Math.round(t_fl * mult_twd) / mult_twd
return t_fl.toString()
}
void clearAlerts(){
myUpdData('noAlert',sTRU)
myUpdData('alert', sNCWA)
myUpdData('alertDescr', sNCWA)
myUpdData('alertSender', sSPC)
String al3 = '<a style="font-style:italic">'
myUpdData('alertTileLink', al3+myGetData('alert')+sACB)
myUpdData('alertLink', sAB + myGetData('condition_text') + sACB)
myUpdData('possAlert', sFLS)
}
@Field static Map<String,Map> dataStoreFLD=[:]
void myUpdData(String key, String val){
String mc=device.id.toString()
Map<String,String> myV=dataStoreFLD[mc]
myV= myV!=null ? myV : [:]
myV[key]=val
dataStoreFLD[mc]=myV
//removeDataValue(key) // THIS SHOULD BE REMOVED AT SOME POINT
}
String myGetData(String key){
String mc=device.id.toString()
Map<String,String> myV=dataStoreFLD[mc]
myV= myV!=null ? myV : [:]
if(myV[key]) return (String)myV[key]
else return sNULL
}
static String dumpListDesc(data, Integer level, List<Boolean> lastLevel, String listLabel, Boolean html=false){
String str=sBLK
Integer cnt=1
List<Boolean> newLevel=lastLevel
List list1=data?.collect{it}
Integer sz=(Integer)list1.size()
list1?.each{ par ->
Integer t0=cnt-1
String myStr="${listLabel}[${t0}]".toString()
if(par instanceof Map){
Map newmap=[:]
newmap[myStr]=(Map)par
Boolean t1= cnt==sz
newLevel[level]=t1
str += dumpMapDesc(newmap, level, newLevel, !t1, html)
}else if(par instanceof List || par instanceof ArrayList){
Map newmap=[:]
newmap[myStr]=par
Boolean t1= cnt==sz
newLevel[level]=t1
str += dumpMapDesc(newmap, level, newLevel, !t1, html)
}else{
String lineStrt='\n'
for(Integer i=0; i<level; i++){
lineStrt += (i+1<level)? (!lastLevel[i] ? ' │' : ' '):' '
}
lineStrt += (cnt==1 && sz>1)? '┌─ ':(cnt<sz ? '├─ ' : '└─ ')
if(html)str += '<span>'
str += "${lineStrt}${listLabel}[${t0}]: ${par} (${getObjType(par)})".toString()
if(html)str += sCSPAN
}
cnt=cnt+1
}
return str
}
static String dumpMapDesc(data, Integer level, List<Boolean> lastLevel, Boolean listCall=false, Boolean html=false){
String str=sBLK
Integer cnt=1
Integer sz=data?.size()
data?.each{ par ->
String lineStrt
List<Boolean> newLevel=lastLevel
Boolean thisIsLast= cnt==sz && !listCall
if(level>0){
newLevel[(level-1)]=thisIsLast
}
Boolean theLast=thisIsLast
if(level==0){
lineStrt='\n\n • '
}else{
theLast= theLast && thisIsLast
lineStrt='\n'
for(Integer i=0; i<level; i++){
lineStrt += (i+1<level)? (!newLevel[i] ? ' │' : ' '):' '
}
lineStrt += ((cnt<sz || listCall) && !thisIsLast) ? '├─ ' : '└─ '
}
String objType=getObjType(par.value)
if(par.value instanceof Map){
if(html)str += '<span>'
str += "${lineStrt}${(String)par.key}: (${objType})".toString()
if(html)str += sCSPAN
newLevel[(level+1)]=theLast
str += dumpMapDesc((Map)par.value, level+1, newLevel, false, html)
}
else if(par.value instanceof List || par.value instanceof ArrayList){
if(html)str += '<span>'
str += "${lineStrt}${(String)par.key}: [${objType}]".toString()
if(html)str += sCSPAN
newLevel[(level+1)]=theLast
str += dumpListDesc(par.value, level+1, newLevel, sBLK, html)
}
else{
if(html)str += '<span>'
str += "${lineStrt}${(String)par.key}: (${par.value}) (${objType})".toString()
if(html)str += sCSPAN
}
cnt=cnt+1
}
return str
}
static String myObj(obj){
if(obj instanceof String){return sSTR}
else if(obj instanceof Map){return 'Map'}
else if(obj instanceof List){return 'List'}
else if(obj instanceof ArrayList){return 'ArrayList'}
else if(obj instanceof Integer){return 'Int'}
else if(obj instanceof BigInteger){return 'BigInt'}
else if(obj instanceof Long){return 'Long'}
else if(obj instanceof Boolean){return 'Bool'}
else if(obj instanceof BigDecimal){return 'BigDec'}
else if(obj instanceof Float){return 'Float'}
else if(obj instanceof Byte){return 'Byte'}
else{ return 'unknown'}
}
static String getObjType(obj){
return "<span style='color:orange'>"+myObj(obj)+sCSPAN
}
static String getMapDescStr(data){
String str
List<Boolean> lastLevel=[true]
str=dumpMapDesc(data, 0, lastLevel, false, true)
return str!=sBLK ? str:'No Data was returned'
}
def pageDump(){
String mc=device.id.toString()
Map myV=dataStoreFLD[mc]
myV= myV!=null ? myV : [:]
String message=getMapDescStr(myV)
log.info message
}
// >>>>>>>>>> Begin Lux Processing <<<<<<<<<<
void updateLux(Boolean pollAgain=true) {
if(ifreInstalled()) { updated(); return }
LOGINFO('Calling UpdateLux(' + pollAgain + ')')
if(pollAgain) {
String curTime = new Date().format('HH:mm', TimeZone.getDefault())
String newLight
if(curTime < myGetData('tw_begin') || curTime > myGetData('tw_end')) {
newLight = sFLS
}else{
newLight = sTRU
}
if(newLight != myGetData('is_lightOld') || myGetData('condition_id')==sNULL || myGetData('cloud')==sNULL) {
pollOWM()
return
}
}
def (Long lux, String bwn) = estimateLux(myGetData('condition_id').toInteger(), myGetData('cloud').toInteger())
myUpdData('illuminance', (!lux) ? sZERO : lux.toString())
myUpdData('illuminated', String.format('%,4d', (!lux) ? 0 : lux).toString())
myUpdData('bwn', bwn)
if(pollAgain) PostPoll()
}
// >>>>>>>>>> End Lux Processing <<<<<<<<<<
// <<<<<<<<<< Begin Post-Poll Routines >>>>>>>>>>
void PostPoll() {
if(ifreInstalled()) { updated(); return }
Integer mult_twd = myGetData('mult_twd')==sNULL ? 1 : myGetData('mult_twd').toInteger()
String ddisp_twd = myGetData('ddisp_twd')==sNULL ? '%3.0f' : myGetData('ddisp_twd')
String ddisp_p = myGetData('ddisp_p')==sNULL ? '%4.0f' : myGetData('ddisp_p')
String ddisp_r = myGetData('ddisp_r')==sNULL ? '%2.0f' : myGetData('ddisp_r')
String tfmt='yyyy-MM-dd\'T\'HH:mm:ssXXX'
String tfmt1=myGetData('timeFormat')
if(myGetData('sunRiseSet')!=sNULL) {
Map sunRiseSet = parseJson(myGetData('sunRiseSet')).results
/* SunriseSunset Data Elements */
if(localSunrisePublish){ // don't bother setting these values if it's not enabled
sendEvent(name: tw_begin, value: new Date().parse(tfmt, (String)sunRiseSet.civil_twilight_begin).format(tfmt1, TimeZone.getDefault()))
sendEvent(name: sunriseTime, value: new Date().parse(tfmt, (String)sunRiseSet.sunrise).format(tfmt1, TimeZone.getDefault()))
sendEvent(name: noonTime, value: new Date().parse(tfmt, (String)sunRiseSet.solar_noon).format(tfmt1, TimeZone.getDefault()))
sendEvent(name: sunsetTime, value: new Date().parse(tfmt, (String)sunRiseSet.sunset).format(tfmt1, TimeZone.getDefault()))
sendEvent(name: tw_end, value: new Date().parse(tfmt, (String)sunRiseSet.civil_twilight_end).format(tfmt1, TimeZone.getDefault()))
}
if(dashSharpToolsPublish || dashSmartTilesPublish || localSunrisePublish) {
sendEvent(name: 'localSunset', value: new Date().parse(tfmt, (String)sunRiseSet.sunset).format(tfmt1, TimeZone.getDefault())) // only needed for certain dashboards
sendEvent(name: 'localSunrise', value: new Date().parse(tfmt, (String)sunRiseSet.sunrise).format(tfmt1, TimeZone.getDefault())) // only needed for certain dashboards
}
}
/* Capability Data Elements */
sendEvent(name: 'humidity', value: myGetData('humidity').toBigDecimal(), unit: '%')
sendEvent(name: 'illuminance', value: myGetData('illuminance').toInteger(), unit: 'lx')
sendEvent(name: 'pressure', value: myGetData('pressure').toBigDecimal(), unit: myGetData(sPMETR))
if(dashSharpToolsPublish || dashSmartTilesPublish)sendEvent(name: 'pressured', value: String.format(ddisp_p, myGetData('pressure').toBigDecimal()), unit: myGetData(sPMETR))
sendEvent(name: sTEMP, value: myGetData(sTEMP).toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'ultravioletIndex', value: myGetData('ultravioletIndex').toBigDecimal(), unit: 'uvi')
sendEvent(name: 'feelsLike', value: myGetData('feelsLike').toBigDecimal(), unit: myGetData(sTMETR))
/* 'Required for Dashboards' Data Elements */
if(dashHubitatOWMPublish || dashSharpToolsPublish || dashSmartTilesPublish) { sendEvent(name: 'city', value: myGetData('city')) }
if(dashSharpToolsPublish) { sendEvent(name: 'forecastIcon', value: getCondCode(myGetData('condition_id').toInteger(), myGetData('is_day'))) }
if(dashSharpToolsPublish || dashSmartTilesPublish || rainTodayPublish) { sendEvent(name: 'rainToday', value: myGetData('rainToday').toBigDecimal(), unit: myGetData(sRMETR)) }
if(dashSharpToolsPublish || dashSmartTilesPublish || percentPrecipPublish) { sendEvent(name: 'percentPrecip', value: myGetData('percentPrecip').toInteger()) }
if(dashSharpToolsPublish || dashSmartTilesPublish) { sendEvent(name: 'weather', value: myGetData('condition_text')) }
if(dashSharpToolsPublish || dashSmartTilesPublish) { sendEvent(name: 'weatherIcon', value: getCondCode(myGetData('condition_id').toInteger(), myGetData('is_day'))) }
if(dashHubitatOWMPublish) { sendEvent(name: "weatherIcons", value: myGetData('OWN_icon')) }
if(dashHubitatOWMPublish || dashSharpToolsPublish || windPublish) { sendEvent(name: 'wind', value: myGetData('wind').toBigDecimal(), unit: myGetData(sDMETR)) }
if(dashHubitatOWMPublish) { sendEvent(name: 'windSpeed', value: myGetData('wind').toBigDecimal(), unit: myGetData(sDMETR)) }
if(dashHubitatOWMPublish) { sendEvent(name: 'windDirection', value: myGetData('wind_degree').toInteger(), unit: 'DEGREE') }
/* Selected optional Data Elements */
sendEventPublish(name: 'betwixt', value: myGetData('bwn'))
sendEventPublish(name: 'cloud', value: myGetData('cloud').toInteger(), unit: '%')
sendEventPublish(name: 'condition_code', value: myGetData('condition_code'))
sendEventPublish(name: 'condition_text', value: myGetData('condition_text'))
sendEventPublish(name: 'dewpoint', value: myGetData('dewpoint').toBigDecimal(), unit: myGetData(sTMETR))
sendEventPublish(name: 'forecast_code', value: myGetData('forecast_code'))
if(forecast_textPublish) {
sendEventPublish(name: 'forecast_text', value: myGetData('forecast_text'))
sendEvent(name: 'forecast_text1', value: myGetData('forecast_text1'))
sendEvent(name: 'forecast_text2', value: myGetData('forecast_text2'))
}
if(fcstHighLowPublish){ // don't bother setting these values if it's not enabled
sendEvent(name: 'forecastHigh', value: myGetData('forecastHigh').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastHigh1', value: myGetData('forecastHigh1').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastHigh2', value: myGetData('forecastHigh2').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastLow', value: myGetData('forecastLow').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastLow1', value: myGetData('forecastLow1').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastLow2', value: myGetData('forecastLow2').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastMorn', value: myGetData('forecastMorn').toBigDecimal(), unit: myGetData(sTMETR))
sendEvent(name: 'forecastDay', value: myGetData('forecastDay').toBigDecimal(), unit: myGetData(sTMETR))