-
Notifications
You must be signed in to change notification settings - Fork 7
/
Weather-Display With External Forecast.groovy
2085 lines (1948 loc) · 111 KB
/
Weather-Display With External Forecast.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
/*
Weather-Display With OWM-Alerts Forecast Driver
Import URL: https://raw.githubusercontent.com/HubitatCommunity/Weather-Display-With-OWM-Alerts-Forecast-Driver/master/Weather-Display%20With%20OWM-Alerts%20Forecast%20Driver.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.
- 'waynedgrant' for his json webservice that make the weather station data available to the driver.
- @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.
- @bptworld for weather.gov poll error handling.
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.
*********************************************************************************************************
* REQUIREMENTS: You MUST have a Personal Weather Station (PWS) and use Weather-Display software to *
* capture that weather data from your network or a web server. If you do not meet this requirement *
* then this driver will not work for you. This uses the Weather-Display data files from a webserver *
* you specify in the driver preferences. I used waynedgrant's work to make those data files available *
* in JSON format (https://github.com/waynedgrant/json-webservice-wdlive). *
*********************************************************************************************************
This driver is intended to pull data from data files on a web server created by Weather-Display software
(http://www.weather-display.com). It will also supplement forecast data from OpenWeatherMap ('OWM')
(https://openweathermap.org). You will need your OWM API key to use the forecast from that sites,
but the driver it will work without an external forecast source.
The driver uses the Weather-Display data as the primary current weather dataset. There are a few options you can select
from like using your forecast source for illuminance/solar radiation/lux if you do not have those sensors.
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 10/24/2020
{ Left room below to document version changes...}
V0.2.8 10/24/2020 Added indicate of multiple alerts in tiles. Minor bug fixes (by @nh.schottfam).
V0.2.7 10/23/2020 Code optimizations and minor bug fixes (by @nh.schottfam).
V0.2.6 10/22/2020 Removed 'NWS' from driver name, minor bug fixes.
V0.2.5 10/21/2020 Improved OWM URLs in the dashboard tiles to pull in location's city code (if available).
V0.2.4 10/21/2020 Better OWM URLs in the dashboard tiles.
V0.2.3 10/20/2020 Correcting some Tile displays from the last update.
V0.2.2 10/20/2020 Pulling Alerts from OWM instead of NWS.
V0.2.1 10/19/2020 Added forecast 'Morn', 'Day', 'Eve' and 'Night' temperatures for current day and tomorrow.
V0.2.0 10/07/2020 Change to use asynchttp for NWS alerts (by @nh.schottfam).
V0.1.9 10/02/2020 More string constant optimizations (by @nh.schottfam)
V0.1.8 09/27/2020 Bug fix preventing polling I introduced in V0.1.7
V0.1.7 09/24/2020 Fix to allow for use of multiple virtual devices, More string constant optimizations (by @nh.schottfam)
V0.1.6 09/24/2020 More string constant optimizations, and removal of white space characters (by @nh.schottfam)
V0.1.5 09/23/2020 Removing 'urgency' restrictions from alerts poll
V0.1.4 09/22/2020 Added forecast icon url attributes for tomorrow and day-after-tomorrow
V0.1.3 09/21/2020 Added forecast High/Low temp attributes for tomorrow and day-after-tomorrow
V0.1.2 09/16/2020 Removing 'severity' and 'certainty' restrictions from alerts poll
V0.1.1 09/13/2020 Re-worked Alerts to not be dependent on api.weather.gov returning a valid response code
V0.1.0 091/12/2020 Remov most DB accesses and string cleanup (by @nh.schottfam)
V0.0.9 09/08/2020 Restoring 'certainty' to the weather.gov alert poll
V0.0.8 09/08/2020 Removed 'certainty' from weather.gov alert poll
V0.0.7 09/07/2020 Bug fix for NullPointerException on line 848
V0.0.6 09/05/2020 Improved Alert handling for dashboard tiles, again, various bug fixes
V0.0.5 05/07/2020 Improved Alert handling for dashboard tiles, various bug fixes
V0.0.4 04/24/2020 Corrected update time on dashboard tile attributes
V0.0.3 04/24/2020 Continue to work on improving null handling, various bug fixes
V0.0.2 04/23/2020 Numerous bug fixes, checking for null and scheduling corrections
V0.0.1 04/22/2020 Initial conversion from DarkSky.net to OWM-NWS Alerts
**ATTRIBUTES CAUTION**
The way the 'optional' attributes work:
- Initially, only the optional attributes selected will show under 'Current States' and will be available in
dashboards.
- Once an attribute has been selected it too will show under 'Current States' and be available in dashboards.
<*** 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.
*/
static String version() { return '0.2.8' }
import groovy.transform.Field
metadata {
definition (name: 'Weather-Display With OWM-Alerts Forecast Driver',
namespace: 'Matthew',
author: 'Scottma61',
importUrl: 'https://raw.githubusercontent.com/HubitatCommunity/Weather-Display-With-OWM-Alerts-Forecast-Driver/master/Weather-Display%20With%20OWM-Alerts%20Forecast%20Driver.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 listed here and shown by default.
attribute 'city', 'string' //Hubitat OpenWeather SharpTool.io SmartTiles
attribute 'feelsLike', 'number' //SharpTool.io SmartTiles
attribute 'forecastIcon', 'string' //SharpTool.io
attribute 'localSunrise', 'string' //SharpTool.io SmartTiles
attribute 'localSunset', 'string' //SharpTool.io SmartTiles
attribute 'percentPrecip', 'number' //SharpTool.io SmartTiles
attribute 'pressured', 'string' //UNSURE SharpTool.io SmartTiles
attribute 'weather', 'string' //SharpTool.io SmartTiles
attribute 'weatherIcon', 'string' //SharpTool.io SmartTiles
attribute 'weatherIcons', 'string' //Hubitat openWeather
attribute 'wind', 'number' //SharpTool.io
attribute 'windDirection', 'number' //Hubitat OpenWeather
attribute 'windSpeed', 'number' //Hubitat OpenWeather
//The attributes below are sub-groups of optional attributes. They need to be listed here to be available
//alert
attribute 'alert', 'string'
attribute 'alertTile', 'string'
attribute 'alertDescr', 'string'
attribute 'alertSender', 'string'
//threedayTile
attribute 'threedayfcstTile', 'string'
//fcstHighLow
attribute 'forecastHigh', 'number'
attribute 'forecastHigh+1', 'number'
attribute 'forecastHigh+2', 'number'
attribute 'forecastLow', 'number'
attribute 'forecastLow+1', 'number'
attribute 'forecastLow+2', 'number'
attribute 'forecastMorn', 'number'
attribute 'forecastDay', 'number'
attribute 'forecastEve', 'number'
attribute 'forecastNight', 'number'
attribute 'forecastMorn+1', 'number'
attribute 'forecastDay+1', 'number'
attribute 'forecastEve+1', 'number'
attribute 'forecastNight+1', 'number'
attribute 'condition_icon_url1', 'string'
attribute 'condition_icon_url2', 'string'
// controlled with localSunrise
attribute 'tw_begin', 'string'
attribute 'sunriseTime', 'string'
attribute 'noonTime', 'string'
attribute 'sunsetTime', 'string'
attribute 'tw_end', 'string'
//obspoll
attribute 'last_poll_Forecast', 'string'
attribute 'last_observation_Forecast', 'string'
//precipExtended
attribute 'rainDayAfterTomorrow', 'number'
attribute 'rainTomorrow', 'number'
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>'
String logDescr = '<br><i>Extended logging will turn off automatically after 30 minutes.</i><br>'
section('Query Inputs'){
input 'extSource', 'enum', title: 'Select Forecast Source', required:true, defaultValue: 1, options: [1:'Weather-Display', 2:'OpenWeatherMap']
input 'apiKey', 'text', required: true, defaultValue: 'Type OpenWeatherMap.org API Key Here', title: 'API Key'
input 'pollIntervalStation', 'enum', title: 'Station Poll Interval', required: true, defaultValue: '3 Hours', options: ['Manual Poll Only', '1 Minute', '2 Minutes', '5 Minutes', '10 Minutes', '15 Minutes', '30 Minutes', '1 Hour', '3 Hours']
input 'pollLocationStation', 'text', required: true, title: 'Station Data File Location:', defaultValue: 'http://', description: '<i>Enter location of \'everything.php\' with a trailing \'/\'</i><br>'
input 'pollIntervalForecast', 'enum', title: 'External Source Poll Interval (daylight)', 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 '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 Temp, Wind & Distance', 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 'RDecimals', 'enum', required: true, defaultValue: sZERO, title: 'Display decimals for Rain volume', 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 or knots', options: ['Miles (mph)', 'Kilometers (kph)', 'knots', 'meters (m/s)']
input 'pressureFormat', 'enum', required: true, defaultValue: 'Inches', title: 'Display Unit - Pressure: Inches or Millibar', 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
input 'iconLocation', 'text', required: true, defaultValue: 'https://tinyurl.com/y6xrbhpf/', title: 'Alternative Icon Location:'
input 'iconType', 'bool', title: 'Condition Icon: ON = Current - OFF = Forecast', required: true, defaultValue: false
input 'sourcefeelsLike', 'bool', required: true, title: 'Feelslike from Weather-Display?', defaultValue: false
input 'sourceIllumination', 'bool', required: true, title: 'Illuminance from Weather-Display?', defaultValue: true
input 'sourceUV', 'bool', required: true, title: 'UV from Weather-Display?', defaultValue: true
input 'sourceWind', 'bool', required: true, title: 'Wind from Weather-Display?', defaultValue: true
input 'altCoord', 'bool', required: true, defaultValue: false, title: 'Override Hub\'s location coordinates'
if (altCoord) {
input 'altLat', 'string', title: 'Override location Latitude', required: true, defaultValue: location.latitude.toString(), description: '<br>Enter location Latitude<br>'
input 'altLon', 'string', 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.title, required: true, defaultValue: attribute.default, description: sBR+(String)attribute.d+sBR
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 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 sIMGS='<img src='
@Field static final String sTD='<td>'
@Field static final String sTDE='</td>'
// <<<<<<<<<< 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' ]
if (currDate) {requestParams = [ uri: 'https://api.sunrise-sunset.org/json?lat=' + (String)altLat + '&lng=' + (String)altLon + '&formatted=0&date=' + currDate ]}
LOGINFO('Poll Sunrise-Sunset: ' + requestParams)
asynchttpGet('sunRiseSetHandler', requestParams)
}
void sunRiseSetHandler(resp, data) {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Map sunRiseSet = resp.getJson().results
myUpdData('sunRiseSet', resp.data)
LOGINFO('Sunrise-Sunset Data: ' + sunRiseSet)
if(ifreInstalled()) { updated(); 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.')
}
}
// >>>>>>>>>> End Sunrise-Sunset Poll Routines <<<<<<<<<<
// <<<<<<<<<< Begin Weather-Display Poll Routines >>>>>>>>>>
void pollWD() {
if(ifreInstalled()) { updated(); return }
Map ParamsWD = [ uri: pollLocationStation+'everything.php' ]
LOGINFO('Polling Weather-Display: ' + ParamsWD)
asynchttpGet('pollWDHandler', ParamsWD)
return
}
void pollWDHandler(resp, data) {
if(resp.getStatus() == 200 || resp.getStatus() == 207) {
Map wd = parseJson(resp.data)
LOGINFO('Weather-Display Data: ' + wd.toString())
doPollWD(wd) // parse the data returned by Weather-Display
}else{
LOGWARN('Weather-Display API did not return data')
}
return
}
void doPollWD(Map wd) {
// <<<<<<<<<< Begin Setup Global Variables >>>>>>>>>>
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('Weather-Display Driver - INFO: Switching to Daytime schedule.')
}else{
log.info('Weather-Display Driver - INFO: Switching to Nighttime schedule.')
}
initialize_poll()
myUpdData('is_lightOld', myGetData('is_light'))
}
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()
Boolean isF = myGetData(sTMETR) == sDF
// >>>>>>>>>> End Setup Global Variables <<<<<<<<<<
// <<<<<<<<<< Begin Setup Station Variables >>>>>>>>>>
Date sotime = new Date().parse('HH:mm dd/MM/yyyy', wd.time.time_date, TimeZone.getDefault())
myUpdData('sotime', sotime.toString())
Date sutime = new Date()
myUpdData('sutime', sutime.toString())
myUpdData(sSUMLST, sutime.format(myGetData('timeFormat'), TimeZone.getDefault()).toString())
myUpdData('Summary_last_poll_date', sutime.format(myGetData('dateFormat'), TimeZone.getDefault()).toString())
// >>>>>>>>>> End Setup Station Variables <<<<<<<<<<
// <<<<<<<<<< Begin Process Only If No External Forcast Is Selected >>>>>>>>>>
if(extSource.toInteger() == 1){
Date fotime = new Date().parse('HH:mm d/M/yyyy', wd.time.time_date, TimeZone.getDefault())
Date futime = new Date()
myUpdData(sSUMLST, futime.format(myGetData('timeFormat'), TimeZone.getDefault()).toString())
myUpdData('Summary_last_poll_date', futime.format(myGetData('dateFormat'), TimeZone.getDefault()).toString())
if(!wd.everything.weather.solar.percentage){
myUpdData('cloud', sONE)
}else{
if(wd.everything.weather.solar.percentage.toInteger() == 100){
myUpdData('cloud', sONE)
}else{
myUpdData('cloud',(100 - wd.everything.weather.solar.percentage.toInteger()).toString())
}
}
Integer c_code
switch(!wd.everything.forecast.icon.code ? 99 : wd.everything.forecast.icon.code.toInteger()) {
case 0: c_code = 800; break;
case 1: c_code = 800; break;
case 2: c_code = 701; break;
case 3: c_code = 800; break;
case 4: c_code = 804; break;
case 5: c_code = 800; break;
case 6: c_code = 741; break;
case 7: c_code = 721; break;
case 8: c_code = 300; break;
case 9: c_code = 800; break;
case 10: c_code = 721; break;
case 11: c_code = 741; break;
case 12: c_code = 300; break;
case 13: c_code = 803; break;
case 14: c_code = 300; break;
case 15: c_code = 300; break;
case 16: c_code = 601; break;
case 17: c_code = 211; break;
case 18: c_code = 803; break;
case 19: c_code = 803; break;
case 20: c_code = 300; break;
case 21: c_code = 300; break;
case 22: c_code = 300; break;
case 23: c_code = 612; break;
case 24: c_code = 612; break;
case 25: c_code = 601; break;
case 26: c_code = 601; break;
case 27: c_code = 601; break;
case 28: c_code = 800; break;
case 29: c_code = 210; break;
case 30: c_code = 211; break;
case 31: c_code = 212; break;
case 32: c_code = 221; break;
case 33: c_code = 800; break;
case 34: c_code = 701; break;
case 35: c_code = 300; break;
default: c_code = 999; break;
}
myUpdData('condition_id', c_code.toString())
myUpdData('condition_code', getCondCode(myGetData('condition_id').toInteger(),myGetData('is_day')))
myUpdData('condition_text', wd.everything.forecast.icon.text)
updateLux(false)
// <<<<<<<<<< Begin Icon processing >>>>>>>>>>
String imgName = getImgName(myGetData('condition_id').toInteger(), myGetData('is_day'))
sendEventPublish(name: 'condition_icon', value: sIMGS + imgName + '>')
sendEventPublish(name: 'condition_iconWithText', value: sIMGS + imgName + '><br>' + myGetData('condition_text'))
sendEventPublish(name: 'condition_icon_url', value: imgName)
myUpdData('condition_icon_url', imgName)
sendEventPublish(name: 'condition_icon_only', value: imgName.split('/')[-1].replaceFirst('\\?raw=true',sBLK))
// >>>>>>>>>> End Icon Processing <<<<<<<<<<
String Summary_forecastTemp = '. '
String Summary_vis = sBLK
}
// >>>>>>>>>> End Process Only If No External Forecast Is Selected <<<<<<<<<<
// <<<<<<<<<< Begin Process Standard Weather-Station Variables (Regardless of Forecast Selection) >>>>>>>>>>
myUpdData('dewpoint', (myGetData(sTMETR)==sDF ? wd.everything.weather.dew_point.current.f.toBigDecimal() : wd.everything.weather.dew_point.current.c.toBigDecimal()).toString())
myUpdData('humidity', wd.everything.weather.humidity.current.toBigDecimal().toString())
myUpdData('rainToday', (myGetData(sRMETR)=='in' ? wd.everything.weather.rainfall.daily.in.toBigDecimal() : wd.everything.weather.rainfall.daily.mm.toBigDecimal()).toString())
myUpdData('pressure', (myGetData(sPMETR)=='inHg' ? wd.everything.weather.pressure.current.inhg.toBigDecimal() : wd.everything.weather.pressure.current.mb.toBigDecimal()).toString())
myUpdData('temperature', (myGetData(sTMETR)==sDF ? wd.everything.weather.temperature.current.f.toBigDecimal() : wd.everything.weather.temperature.current.c.toBigDecimal()).toString())
// <<<<<<<<<< Begin Process Only If Wind from WD Is Selected >>>>>>>>>>
if(sourceWind==true){
myUpdData('wind_bft_icon', 'wb' + wd.everything.weather.wind.avg_speed.bft.toInteger().toString() + '.png')
String w_string_bft
switch(wd.everything.weather.wind.avg_speed.bft.toInteger()){
case 0: w_string_bft = 'Calm'; break;
case 1: w_string_bft = 'Light air'; break;
case 2: w_string_bft = 'Light breeze'; break;
case 3: w_string_bft = 'Gentle breeze'; break;
case 4: w_string_bft = 'Moderate breeze'; break;
case 5: w_string_bft = 'Fresh breeze'; break;
case 6: w_string_bft = 'Strong breeze'; break;
case 7: w_string_bft = 'High wind, moderate gale, near gale'; break;
case 8: w_string_bft = 'Gale, fresh gale'; break;
case 9: w_string_bft = 'Strong/severe gale'; break;
case 10: w_string_bft = 'Storm, whole gale'; break;
case 11: w_string_bft = 'Violent storm'; break;
case 12: w_string_bft = 'Hurricane force'; break;
default: w_string_bft = 'Calm'; break;
}
BigDecimal t_wd
BigDecimal t_wg
if(myGetData(sDMETR) == 'MPH') {
t_wd = Math.round(wd.everything.weather.wind.avg_speed.mph.toBigDecimal() * mult_twd) / mult_twd
t_wg = Math.round(wd.everything.weather.wind.gust_speed.mph.toBigDecimal() * mult_twd) / mult_twd
} else if(myGetData(sDMETR) == 'KPH') {
t_wd = Math.round(wd.everything.weather.wind.avg_speed.kmh.toBigDecimal() * mult_twd) / mult_twd
t_wg = Math.round(wd.everything.weather.wind.gust_speed.kmh.toBigDecimal() * 1.609344 * mult_twd) / mult_twd
} else if(myGetData(sDMETR) == 'knots') {
t_wd = Math.round(wd.everything.weather.wind.avg_speed.mph.toBigDecimal() * 0.868976 * mult_twd) / mult_twd
t_wg = Math.round(wd.everything.weather.wind.gust_speed.mph.toBigDecimal() * 0.868976 * mult_twd) / mult_twd
}else{ // this leave only m/s
t_wd = Math.round(wd.everything.weather.wind.avg_speed.mph.toBigDecimal() * 0.44704 * mult_twd) / mult_twd
t_wg = Math.round(wd.everything.weather.wind.gust_speed.mph.toBigDecimal() * 0.44704 * mult_twd) / mult_twd
}
myUpdData('wind', t_wd.toString())
myUpdData('wind_gust', t_wg.toString())
myUpdData('wind_degree', wd.everything.weather.wind.direction.degrees.toInteger().toString())
String w_direction
switch(wd.everything.weather.wind.direction.cardinal.toUpperCase()){
case 'N': w_direction = 'North'; break;
case 'NNE': w_direction = 'North-Northeast'; break;
case 'NE': w_direction = 'Northeast'; break;
case 'ENE': w_direction = 'East-Northeast'; break;
case 'E': w_direction = 'East'; break;
case 'ESE': w_direction = 'East-Southeast'; break;
case 'SE': w_direction = 'Southeast'; break;
case 'SSE': w_direction = 'South-Southeast'; break;
case 'S': w_direction = 'South'; break;
case 'SSW': w_direction = 'South-Southwest'; break;
case 'SW': w_direction = 'Southwest'; break;
case 'WSW': w_direction = 'West-Southwest'; break;
case 'W': w_direction = 'West'; break;
case 'WNW': w_direction = 'West-Northwest'; break;
case 'NW': w_direction = 'Northwest'; break;
case 'NNW': w_direction = 'North-Northwest'; break;
default: w_direction = 'Unknown'; break;
}
myUpdData('wind_direction', w_direction)
myUpdData('wind_cardinal', wd.everything.weather.wind.direction.cardinal.toUpperCase())
myUpdData('wind_string', w_string_bft + ' from the ' + myGetData('wind_direction') + (myGetData('wind').toBigDecimal() < 1.0 ? sBLK: ' at ' + String.format(myGetData('ddisp_twd'), myGetData('wind').toBigDecimal()) + sSPC + myGetData(sDMETR)))
}
// >>>>>>>>>> End Process Only If Wind from WD Is Selected <<<<<<<<<<
myUpdData('city', wd.station.name.split(/ /)[0])
myUpdData('state', wd.station.name.split(/ /)[1])
myUpdData('country', wd.station.name.split(/ /)[2])
myUpdData('moonAge', wd.everything.astronomy.moon.moon_age.toBigDecimal().toString())
String mPhase
BigDecimal tma = wd.everything.astronomy.moon.moon_age.toBigDecimal()
if (tma >= 0 && tma < 4) {mPhase = 'New Moon'}
else if (tma >= 4 && tma < 7) {mPhase = 'Waxing Crescent'}
else if (tma >= 7 && tma < 10) {mPhase = 'First Quarter'}
else if (tma >= 10 && tma < 14) {mPhase = 'Waxing Gibbous'}
else if (tma >= 14 && tma < 18) {mPhase = 'Full Moon'}
else if (tma >= 18 && tma < 22) {mPhase = 'Waning Gibbous'}
else if (tma >= 22 && tma < 26) {mPhase = 'Last Quarter'}
else if (tma >= 26) {mPhase = 'Waxing Gibbous'}
myUpdData('moonPhase', mPhase)
if(solarradiationPublish){
if(!wd.everything.weather.solar.irradiance.wm2){
myUpdData('solarradiation', 'This station does not send Solar Radiation data.')
}else{
myUpdData('solarradiation', wd.everything.weather.solar.irradiance.wm2.toInteger().toString())
}
}
// >>>>>>>>>> End Process Standard Weather-Station Variables (Regardless of Forecast Selection) <<<<<<<<<<
// <<<<<<<<<< Begin Process Only If Illumination from WD Is Selected >>>>>>>>>>
if(sourceIllumination == true){
if (!wd.everything.weather.solar.irradiance.wm2){
myUpdData('illuminance', 'This station does not send illuminance data.')
myUpdData('illuminated', 'This station does not send illuminance data.')
}else{
BigDecimal slux = Math.max(((wd.everything.weather.solar.irradiance.wm2.toBigDecimal() / 0.0079) / 12.8),5.000) //SolarRad to Lux conversion
myUpdData('illuminance', slux.toInteger().toString())
myUpdData('illuminated', String.format('%,4d', slux.toInteger()).toString())
}
}
// >>>>>>>>>> End Process Only If Illumination from WD Is Selected <<<<<<<<<<
// <<<<<<<<<< Begin Process Only If Ultraviolet Index from WD Is Selected >>>>>>>>>>
if(sourceUV==true){
if(!wd.everything.weather.uv.uvi){
myUpdData('ultravioletIndex', 'This station does not send ultravoilet index data.')
}else{
myUpdData('ultravioletIndex', wd.everything.weather.uv.uvi.toBigDecimal().toString())
}
}
// >>>>>>>>>> End Process Only If UV from WD Is Selected <<<<<<<<<<
// <<<<<<<<<< Begin Process Only If feelsLike from WD Is Selected >>>>>>>>>>
if(sourcefeelsLike==true){
BigDecimal t_fl
if(myGetData(sTMETR) == sDF) {
t_fl = Math.round(wd.everything.weather.apparent_temperature.current.f.toBigDecimal() * mult_twd) / mult_twd
}else{
t_fl = Math.round(wd.everything.weather.apparent_temperature.current.c.toBigDecimal() * mult_twd) / mult_twd
}
myUpdData('feelsLike', t_fl.toString())
}
// >>>>>>>>>> End Process Only If feelsLike from WD Is Selected <<<<<<<<<<
if(myGetData('forecastPoll') == sFLS){
if(extSource.toInteger() == 2){ pollOWM() }
}else{
PostPoll()
}
return
}
// >>>>>>>>>> End Weather-Display 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 different Lat/Lon location uncommnent the two lines below */
// String altLat = "42.8666667"
// String altLon = "-106.3125"
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=' + apiKey ]
LOGINFO('Poll OpenWeatherMap.org: ' + ParamsOWM)
asynchttpGet('pollOWMHandler', ParamsOWM)
}
void pollOWMHandler(resp, data) {
if(ifreInstalled()) { updated(); return }
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=' + apiKey)
LOGWARN(resp.getStatus() + sCOLON + resp.getErrorMessage())
}else{
Map owm = parseJson(resp.data)
LOGINFO('OpenWeatherMap Data: ' + owm.toString())
// <<<<<<<<<< Begin Setup Global Variables >>>>>>>>>>
Date fotime = 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('Weather-Display Driver - INFO: Switching to Daytime schedule.')
}else{
log.info('Weather-Display Driver - INFO: Switching to Nighttime schedule.')
}
initialize_poll()
myUpdData('is_lightOld', myGetData('is_light'))
}
// >>>>>>>>>> End Setup Global Variables <<<<<<<<<<
// <<<<<<<<<< Begin Setup Forecast Variables >>>>>>>>>>
Integer cloudCover
if (owm?.current?.clouds==null) {
cloudCover = 1
}else{
cloudCover = (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 * myGetData('mult_twd').toInteger()) / myGetData('mult_twd').toInteger() : Math.round(owm?.current?.visibility==null ? 0.00 : owm.current.visibility.toBigDecimal() * 0.0006213712 * myGetData('mult_twd').toInteger()) / myGetData('mult_twd').toInteger()).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==null ? 0.00 : owmDaily[0].rain) + (owmDaily==null || owmDaily[0]?.snow==null ? 0.00 : owmDaily[0].snow)
Integer mult_twd = myGetData('mult_twd').toInteger()
Integer mult_p = myGetData('mult_p').toInteger()
Integer mult_r = myGetData('mult_r').toInteger()
Boolean isF = myGetData(sTMETR) == sDF
String imgT1=(myGetData(sICON).toLowerCase().contains('://github.com/') && myGetData(sICON).toLowerCase().contains('/blob/master/') ? '?raw=true' : sBLK)
if(owmDaily && (threedayTilePublish || precipExtendedPublish)) {
BigDecimal t_p1 = (owmDaily[1]?.rain==null ? 0.00 : owmDaily[1].rain) + (owmDaily[1]?.snow==null ? 0.00 : owmDaily[1].snow)
BigDecimal t_p2 = (owmDaily[2]?.rain==null ? 0.00 : owmDaily[2].rain) + (owmDaily[2]?.snow==null ? 0.00 : owmDaily[2].snow)
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())
}
if(owmDaily && owmDaily[1] && owmDaily[2] && (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('forecastHigh+1', adjTemp(owmDaily[1]?.temp?.max, isF, mult_twd))
myUpdData('forecastHigh+2', adjTemp(owmDaily[2]?.temp?.max, isF, mult_twd))
myUpdData('forecastLow+1', adjTemp(owmDaily[1]?.temp?.min, isF, mult_twd))
myUpdData('forecastLow+2', 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('forecastMorn+1', adjTemp(owmDaily[1]?.temp?.morn, isF, mult_twd))
myUpdData('forecastDay+1', adjTemp(owmDaily[1]?.temp?.day, isF, mult_twd))
myUpdData('forecastEve+1', adjTemp(owmDaily[1]?.temp?.eve, isF, mult_twd))
myUpdData('forecastNight+1', adjTemp(owmDaily[1]?.temp?.night, isF, mult_twd))
String imgT= '<img class="centerImage" src=' + myGetData(sICON)
myUpdData('imgName0', imgT + getImgName(myGetData('condition_id').toInteger(), myGetData('is_day')) + imgT1 + sRB)
myUpdData('imgName1', imgT + getImgName((owmDaily[1]?.weather[0]?.id==null ? 999 : owmDaily[1].weather[0].id), sTRU) + imgT1 + sRB)
myUpdData('imgName2', imgT + getImgName((owmDaily[2]?.weather[0]?.id==null ? 999 : owmDaily[2].weather[0].id), sTRU) + imgT1 + sRB)
}
if(condition_icon_urlPublish) {
String imgName1 = getImgName(myGetData('forecast_id1').toInteger(), myGetData('is_day'))
String imgName2 = getImgName(myGetData('forecast_id2').toInteger(), myGetData('is_day'))
sendEvent(name: 'condition_icon_url1', value: myGetData(sICON) + imgName1 + imgT1)
sendEvent(name: 'condition_icon_url2', value: myGetData(sICON) + imgName2 + imgT1)
}
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'))
}
// <<<<<<<<<< Begin Process Only If Wind from WD Is NOT Selected >>>>>>>>>>
if(sourceWind==false){
String w_string_bft
String w_bft_icon
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
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())
myUpdData('wind_degree', owm.current.wind_deg.toInteger().toString())
String w_cardinal
String w_direction
BigDecimal twb = owm?.current?.wind_deg==null ? 0.00 : owm.current.wind_deg.toBigDecimal()
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(myGetData('ddisp_twd'), myGetData('wind').toBigDecimal()) + sSPC + myGetData(sDMETR)))
}
// >>>>>>>>>> End Process Only If Wind from WD Is NOT Selected <<<<<<<<<<
// >>>>>>>>>> End Setup Forecast Variables <<<<<<<<<<
//<<<<<<<<< Begin Process Only If Illumination from WD Is NOT Selected >>>>>>>>>>
updateLux(false)
//
// >>>>>>>>>> End Process Only If Illumination from WD Is NOT Selected <<<<<<<<<<
// <<<<<<<<<< Begin Process Only If Ultraviolet Index from WD Is NOT Selected >>>>>>>>>>
if(sourceUV==false){
myUpdData('ultravioletIndex', owm?.current?.uvi==null ? "0.00" : owm.current.uvi.toBigDecimal().toString())
}
// >>>>>>>>>> End Process Only If Ultraviolet Index from WD Is NOT Selected <<<<<<<<<<
// <<<<<<<<<< Begin Process Only If feelsLike Index from WD Is NOT Selected >>>>>>>>>>
if(sourcefeelsLike==false){
myUpdData('feelsLike', adjTemp(owm?.current?.feels_like, isF, mult_twd))
}
// >>>>>>>>>> End Process Only If feelsLike from WD Is NOT Selected <<<<<<<<<<
if(alertPublish) {
if(!owm?.alerts) {
clearAlerts()
}else{
String curAl = owm?.alerts[0]?.event==null ? 'No current weather alerts for this area' : owm?.alerts[0]?.event.replaceAll('\n', sSPC).replaceAll('[{}\\[\\]]', sBLK)
String curAlSender = owm?.alerts[0]?.sender_name==null ? sNULL : owm?.alerts[0]?.sender_name.replaceAll('\n',sSPC).replaceAll('[{}\\[\\]]', sBLK)
String curAlDescr = owm?.alerts[0]?.description==null ? sNULL : owm?.alerts[0]?.description.replaceAll('\n',sSPC).replaceAll('[{}\\[\\]]', sBLK).take(1024)
LOGINFO('OWM Weather Alert: ' + curAl + '; Description: ' + curAlDescr.length() + ' ' +curAlDescr)
if(curAl=='No current weather alerts for this area') {
clearAlerts()
}else{
Integer alertCnt = 0
for(int i = 1;i<10;i++) {
if(owm?.alerts[i]?.event!=null) {
alertCnt = i
}
}
myUpdData('noAlert',sFLS)
myUpdData('alert', curAl + (alertCnt>0 ? ' +' + alertCnt.toString() : sBLK))
myUpdData('alertDescr', curAlDescr)
myUpdData('alertSender', curAlSender)
// https://tinyurl.com/y42s2ndy points to https://openweathermap.org/city/
String al3 = '<a style="font-style:italic;color:red" href="https://tinyurl.com/y42s2ndy/' + myGetData('OWML') + '" target="_blank">'
myUpdData('alertTileLink', al3+myGetData('alert')+sACB)
myUpdData('alertLink', al3+myGetData('alert')+sACB)
myUpdData('alertLink2', al3+myGetData('alert')+sACB)
myUpdData('alertLink3', '<a style="font-style:italic;color:red" target=\'_blank\'>' + myGetData('alert')+sACB)
myUpdData('possAlert', sTRU)
}
}
// <<<<<<<<<< Begin Built alertTile >>>>>>>>>>
String alertTile = (myGetData('alert')== 'No current weather alerts for this area' ? 'No Weather Alerts for ' : 'Weather Alert for ') + myGetData('city') + (myGetData('alertSender')==null ? '' : ' issued by ' + myGetData('alertSender')) + ' updated at ' + myGetData(sSUMLST) + ' on ' + myGetData('Summary_last_poll_date') + '.<br>'
alertTile+= myGetData('alertTileLink') + sBR + sIMGS + myGetData(sICON) + 'OWM.png style="height:2em"></a>'
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 <<<<<<<<<<
}
// <<<<<<<<<< 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: sIMGS + myGetData(sICON) + imgName + imgT1 + sRB)
sendEventPublish(name: 'condition_iconWithText', value: sIMGS + 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 <<<<<<<<<<
if(myGetData('forecastPoll') == sFLS){
myUpdData('forecastPoll', sTRU)
}
PostPoll()
return
}
}
// >>>>>>>>>> End OpenWeatherMap Poll Routines <<<<<<<<<<
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', 'No current weather alerts for this area')
myUpdData('alertDescr', sBLK)
myUpdData('alertSender', sBLK)
// https://tinyurl.com/y42s2ndy points to https://openweathermap.org/city/
String al3 = '<a style="font-style:italic" href="https://tinyurl.com/y42s2ndy/' + myGetData('OWML') + '" target="_blank">'
myUpdData('alertTileLink', al3+myGetData('alert')+sACB)
myUpdData('alertLink', sAB + myGetData('condition_text') + sACB)
myUpdData('alertLink2', sAB + myGetData('condition_text') + sACB)
myUpdData('alertLink3', 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) ? '├─ ' : '└─ '
}