/
L_MsWeather.lua
1942 lines (1860 loc) · 70.9 KB
/
L_MsWeather.lua
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
ABOUT = {
NAME = "Multi Weather Station",
VERSION = "1.1",
DESCRIPTION = "Multi Weather Station plugin",
AUTHOR = "Rene Boer"
}
--[[
Icons based on Wunderground. Information : https://docs.google.com/document/d/1qpc4QN3YDpGDGGNYVINh7tfeulcZ4fxPSC5f4KzpR_U/edit
Version 1.1 2021-04-1
- Added KNMI (weerlive, NL) weather provider
- No longer using S_GenericSensor.xml as it limits SDATA possibilities
- Fix for Precipitation update
- Fix for Wundergrouns metric_si units
- More generic functions, less code per provider
- Minor fixes
Version 1.0 2021-03-17
- First GA version
- Change in Display Line settings directly reflected after Luup reload.
- Added Air Quality values (OpenWeather only)
Version 0.2 2021-03-16 - Beta version for public testing
Version 0.1 2021-02-25 - Alpha version for testing
https://www.visualcrossing.com/resources/documentation/weather-api/how-to-replace-the-dark-sky-api/
--]]
-- plugin general variables
local https = require("ssl.https")
local ltn12 = require("ltn12")
local dkjson = require("dkjson")
local cjson = nil
pcall(function ()
-- Install via LuaRocks: luarocks install lua-cjson
cjson = require("cjson")
if not cjson.decode then cjson = nil end
end)
local zlib = nil
pcall(function()
-- Install package: sudo apt-get install lua-zlib
zlib = require('zlib')
if not zlib.inflate then zlib = nil end
end)
local SID_Weather = "urn:upnp-rboer-com:serviceId:Weather1"
local SID_WeatherM = "urn:upnp-rboer-com:serviceId:WeatherMetric1"
local SID_Security = "urn:micasaverde-com:serviceId:SecuritySensor1"
local SID_Humid = "urn:micasaverde-com:serviceId:HumiditySensor1"
local SID_UV = "urn:micasaverde-com:serviceId:LightSensor1"
local SID_HA = "urn:micasaverde-com:serviceId:HaDevice1"
local SID_Baro = "urn:upnp-org:serviceId:BarometerSensor1"
local SID_Temp = "urn:upnp-org:serviceId:TemperatureSensor1"
local SID_Generic = "urn:micasaverde-com:serviceId:GenericSensor1"
local SID_AltUI = "urn:upnp-org:serviceId:altui1"
local this_device = nil
-- these are the configuration and their default values
local MS = {
Provider = 0,
Key = "",
ApplicationKey = "",
Latitude = "",
Longitude = "",
StationID = 0,
StationName = "",
Period = 1800, -- data refresh interval in seconds
Units = "",
ForecastDays = 2,
DispLine1 = 1,
DispLine2 = 2,
ChildDev = "",
RainSensor = 0, -- Can support rain alarm for US,CA,UK (for NL we could use buienradar).
Language = "en", -- default language
IconsProvider = "Thanks to TWC icons at https://docs.google.com/document/d/1qpc4QN3YDpGDGGNYVINh7tfeulcZ4fxPSC5f4KzpR_U",
Documentation = "https://github.com/reneboer/MsWeather/wiki",
LogLevel = 1,
Version = ABOUT.VERSION
}
local static_Vars = "|IconsProvider|Documentation|Version|"
-- this is the table used to map any providers output elements with the conversion rules and child details.
local VariablesMap = {
currently = {
["CurrentApparentTemperature"] = {decimal = 1, childKey = "A", childID = nil},
["CurrentCloudCover"] = {decimal = 0, childKey = "C", childID = nil},
["CurrentDewPoint"] = {decimal = 1, childKey = "D", initVal = 0, childID = nil},
["CurrentHumidity"] = {decimal = 0, childKey = "H", childID = nil},
["Icon"] = {},
["CurrentOzone"] = {childKey = "O", childID = nil},
["CurrentCO"] = {decimal = 0, childKey = "X", childID = nil},
["CurrentNO"] = {},
["CurrentNO2"] = {},
["CurrentSO2"] = {},
["CurrentNH3"] = {},
["CurrentPM25"] = {},
["CurrentPM10"] = {},
["CurrentAirQuality"] = {childKey = "Q", childID = nil},
["CurrentuvIndex"] = {childKey = "U", childID = nil},
["CurrentVisibility"] = {decimal = 3, childKey = "V", childID = nil},
["CurrentPrecipIntensity"] = {childKey = "R", childID = nil},
["CurrentPrecipProbability"] = {decimal = 0},
["CurrentPrecipType"] = {},
["CurrentPressure"] = {decimal = 0, childKey = "P", childID = nil},
["CurrentConditions"] = {},
["CurrentTemperature"] = {decimal = 1, childKey = "T", childID = nil},
["LastUpdate"] = {},
["CurrentSunrise"] = {},
["CurrentSunset"] = {},
["CurrentWindDirection"] = {},
["CurrentWindBearing"] = {},
["CurrentWindSpeed"] = {decimal = 1, childKey = "W", childID = nil},
["CurrentWindGust"] = {decimal = 1},
["WeekConditions"] = {},
["ReportedUnits"] = {}
},
forecast = {
["Pressure"] = {decimal = 0},
["Conditions"] = {},
["Ozone"] = {},
["uvIndex"] = {},
["uvIndexTime"] = {},
["Visibility"] = {decimal = 3},
["PrecipIntensity"] = {},
["PrecipIntensityMax"] = {},
["PrecipProbability"] = {decimal = 0},
["SunProbability"] = {decimal = 0},
["PrecipType"] = {},
["MaxTemp"] = {decimal = 1},
["MinTemp"] = {decimal = 1},
["HighTemp"] = {decimal = 1},
["LowTemp"] = {decimal = 1},
["ApparentMaxTemp"] = {decimal = 1},
["ApparentMinTemp"] = {decimal = 1},
["Icon"] = {},
["CloudCover"] = {decimal = 0},
["DewPoint"] = {decimal = 1},
["Humidity"] = {decimal = 0},
["WindDirection"] = {},
["WindBearing"] = {},
["WindSpeed"] = {decimal = 1},
["WindGust"] = {decimal = 1},
["Sunrise"] = {},
["Sunset"] = {}
}
}
local languageMap = {
["en"] = "en-US", ["ar"] = "ar-AE", ["bg"] = "bg-BG", ["bn"] = "bn-IN", ["bs"] = "bs-BA", ["cs"] = "cs-CZ",
["da"] = "da-DK", ["nl"] = "nl-NL", ["de"] = "de-DE", ["el"] = "el-GR", ["es"] = "es-ES", ["et"] = "et-EE",
["fi"] = "fi-FI", ["fr"] = "fr-FR", ["he"] = "he-IL", ["hi"] = "hi-IN", ["hr"] = "hr-HR", ["hu"] = "hu-HU",
["id"] = "in-ID", ["is"] = "is-IS", ["it"] = "it-IT", ["ja"] = "ja-JP", ["ko"] = "ko-KR", ["lv"] = "lv-LV",
["no"] = "no-NO", ["pa"] = "pa-PK", ["pl"] = "pl-PL", ["pt"] = "pt-PT", ["ro"] = "ro-RO", ["ru"] = "ru-RU",
["sk"] = "sk-SK", ["sl"] = "sl-SI", ["sr"] = "sr-RS", ["sv"] = "sv-SE", ["tr"] = "tr-TR", ["uk"] = "uk-UA"
}
-- Mapping of data to display in ALTUI DisplayLines 1 & 2.
-- Keep definitions in sync with JS code.
local DisplayMap = {
[1] = {{ prefix = "", var = "CurrentConditions" }},
[2] = {{ prefix = "Pressure: ", var = "CurrentPressure"}},
[3] = {{ prefix = "Last update: ", var = "LastUpdate" }},
[4] = {{ prefix = "Wind: ", var = "CurrentWindSpeed" },{ prefix = "Gust: ", var = "CurrentWindGust" },{ prefix = "Bearing: ", var = "CurrentWindBearing" }},
[5] = {{ prefix = "Ozone: ", var = "CurrentOzone" },{ prefix = "UV Index: ", var = "CurrentuvIndex" }},
[6] = {{ prefix = "Current Temperature: ", var = "CurrentTemperature" }},
[7] = {{ prefix = "Apparent Temperature: ", var = "CurrentApparentTemperature" }},
[8] = {{ prefix = "Current Cloud Cover: ", var = "CurrentCloudCover" }},
[9] = {{ prefix = "Precip: ", var = "CurrentPrecipType" },{ prefix = "Prob.: ", var = "CurrentPrecipProbability" },{ prefix = "Intensity: ", var = "CurrentPrecipIntensity" }},
[10] = {{ prefix = "Humidity: ", var = "CurrentHumidity" },{ prefix = "Dew Point: ", var = "CurrentDewPoint" }},
[11] = {{ prefix = "AQI: ", var = "CurrentAirQuality" },{ prefix = "PM2.5: ", var = "CurrentPM25" },{ prefix = "PM10: ", var = "CurrentPM10" }},
[12] = {{ prefix = "Co: ", var = "CurrentCO" },{ prefix = "No: ", var = "CurrentNO" },{ prefix = "No2: ", var = "CurrentNO2" }}
}
-- for writing to Luup variables, need serviceId and variable name for each sensor type
-- for creating child devices also need device xml filename
local SensorInfo = setmetatable (
{
['A'] = { deviceXML = "D_TemperatureSensor1.xml", serviceId = SID_Temp, variable = "CurrentTemperature", name="Apparent Temp."},
['D'] = { deviceXML = "D_TemperatureSensor1.xml", serviceId = SID_Temp, variable = "CurrentTemperature", name="Dewpoint"},
['T'] = { deviceXML = "D_TemperatureSensor1.xml", serviceId = SID_Temp, variable = "CurrentTemperature", name="Temperature"},
['H'] = { deviceXML = "D_HumiditySensor1.xml", serviceId = SID_Humid, variable = "CurrentLevel", name="Humidity"},
['U'] = { deviceXML = "D_LightSensor1.xml", deviceJSON = "D_UVSensor1.json", serviceId = SID_UV, variable = "CurrentLevel", name="UV Index"},
['P'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 1 , name="Pressure"},
['O'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 2 , name="Ozone"},
['V'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 3 , name="Visibility"},
['W'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 4 , name="Wind"},
['R'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 5 , name="Precipitation"},
['Q'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 6 , name="Air Quality"},
['X'] = { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel", icon = 6 , name="Air Quality values"}
},
{__index = function () -- default for everything else
return { deviceXML = "D_MsWeatherMetric.xml", serviceId = SID_Generic, variable = "CurrentLevel"}
end
}
)
---------------------------------------------------------------------------------------------
-- Utility functions
---------------------------------------------------------------------------------------------
local log
local var
local utils
local json
-- Wrapper for more solid handling for cjson as it trows a bit more errors that I'd like.
local function jsonAPI()
local is_cj, is_dk
local function clean_cjson_nulls (x) -- 2020.05.20 replace any cjson.null with nil. To use, maybe, thanks akbooer.
for n,v in pairs (x) do
if type(v) == "table" then
clean_cjson_nulls (v)
elseif v == cjson.null then
x[n] = nil
end
end
end
local function _init()
is_cj = type(cjson) == "table"
is_dk = type(dkjson) == "table"
-- is_cj, cjson = pcall(require, "cjson")
-- is_dk, dkjson = pcall(require, "dkjson")
end
local function _decode(data)
if is_cj then
local ok, res = pcall(cjson.decode, data)
if ok then return res end
end
local res, pos, msg = dkjson.decode(data)
return res, msg
end
local function _encode(data)
-- No special chekcing required as we must pass valid data our selfs
if is_cj then
return cjson.encode(data)
else
return dkjson.encode(data)
end
end
return {
Initialize = _init,
decode = _decode,
encode = _encode
}
end
-- API getting and setting variables and attributes from Vera more efficient.
local function varAPI()
local def_sid, def_dev = '', 0
local function _init(sid,dev)
def_sid = sid
def_dev = dev
end
-- Get variable value
local function _get(name, sid, device)
local value = luup.variable_get(sid or def_sid, name, tonumber(device or def_dev))
return (value or '')
end
-- Get variable value as number type
local function _getnum(name, sid, device)
local value = luup.variable_get(sid or def_sid, name, tonumber(device or def_dev))
local num = tonumber(value,10)
return (num or 0)
end
-- Set variable value
local function _set(name, value, sid, device)
local sid = sid or def_sid
local device = tonumber(device or def_dev)
local old = luup.variable_get(sid, name, device)
if (tostring(value) ~= tostring(old or '')) then
luup.variable_set(sid, name, value, device)
end
end
-- create missing variable with default value or return existing
local function _default(name, default, sid, device)
local sid = sid or def_sid
local device = tonumber(device or def_dev)
local value = luup.variable_get(sid, name, device)
if (not value) then
value = default or ''
luup.variable_set(sid, name, value, device)
end
return value
end
-- Get an attribute value, try to return as number value if applicable
local function _getattr(name, device)
local value = luup.attr_get(name, tonumber(device or def_dev))
local nv = tonumber(value,10)
return (nv or value)
end
-- Set an attribute
local function _setattr(name, value, device)
local val = _getattr(name, device)
if val ~= value then
luup.attr_set(name, value, tonumber(device or def_dev))
end
end
return {
Get = _get,
Set = _set,
GetNumber = _getnum,
Default = _default,
GetAttribute = _getattr,
SetAttribute = _setattr,
Initialize = _init
}
end
-- API to handle basic logging and debug messaging
local function logAPI()
local def_level = 1
local def_prefix = ''
local def_name = 'log'
local def_debug = false
local def_file = false
local max_length = 100
local onOpenLuup = false
local taskHandle = -1
local function _update(level)
if level > 100 then
def_file = true
def_debug = true
def_level = 10
elseif level > 10 then
def_debug = true
def_file = false
def_level = 10
else
def_file = false
def_debug = false
def_level = level
end
end
local function _init(prefix, level,onol)
_update(level)
def_prefix = prefix
def_name = prefix:gsub(" ","")
onOpenLuup = onol
end
-- Build loggin string safely up to given lenght. If only one string given, then do not format because of length limitations.
local function prot_format(ln,str,...)
local msg = ""
if arg[1] then
_, msg = pcall(string.format, str, unpack(arg))
else
msg = str or "no text"
end
if ln > 0 then
return msg:sub(1,ln)
else
return msg
end
end
local function _log(...)
if (def_level >= 10) then
luup.log(def_prefix .. ": " .. prot_format(max_length,...), 50)
end
end
local function _info(...)
if (def_level >= 8) then
luup.log(def_prefix .. "_info: " .. prot_format(max_length,...), 8)
end
end
local function _warning(...)
if (def_level >= 2) then
luup.log(def_prefix .. "_warning: " .. prot_format(max_length,...), 2)
end
end
local function _error(...)
if (def_level >= 1) then
luup.log(def_prefix .. "_error: " .. prot_format(max_length,...), 1)
end
end
local function _debug(...)
if def_debug then
luup.log(def_prefix .. "_debug: " .. prot_format(-1,...), 50)
end
end
-- Write to file for detailed analysis
local function _logfile(...)
if def_file then
local fh = io.open("/tmp/log/"..def_name..".log","a")
local msg = prot_format(-1,...)
fh:write(msg)
fh:write("\n")
fh:close()
end
end
local function _devmessage(devID, isError, timeout, ...)
local message = prot_format(60,...)
local status = isError and 2 or 4
-- Standard device message cannot be erased. Need to do a reload if message w/o timeout need to be removed. Rely on caller to trigger that.
if onOpenLuup then
taskHandle = luup.task(message, status, def_prefix, taskHandle)
if timeout ~= 0 then
luup.call_delay("logAPI_clearTask", timeout, "", false)
else
taskHandle = -1
end
else
luup.device_message(devID, status, message, timeout, def_prefix)
end
end
local function logAPI_clearTask()
luup.task("", 4, def_prefix, taskHandle)
taskHandle = -1
end
_G.logAPI_clearTask = logAPI_clearTask
return {
Initialize = _init,
Error = _error,
Warning = _warning,
Info = _info,
Log = _log,
Debug = _debug,
Update = _update,
LogFile = _logfile,
DeviceMessage = _devmessage
}
end
-- API to handle some Util functions
local function utilsAPI()
local _UI5 = 5
local _UI6 = 6
local _UI7 = 7
local _UI8 = 8
local _OpenLuup = 99
local function _init()
end
-- See what system we are running on, some Vera or OpenLuup
local function _getui()
if (luup.attr_get("openLuup",0) ~= nil) then
return _OpenLuup
else
return luup.version_major
end
return _UI7
end
local function _getmemoryused()
return math.floor(collectgarbage "count") -- app's own memory usage in kB
end
local function _setluupfailure(status,devID)
if (luup.version_major < 7) then status = status ~= 0 end -- fix UI5 status type
luup.set_failure(status,devID)
end
-- Luup Reload function for UI5,6 and 7
local function _luup_reload()
if (luup.version_major < 6) then
luup.call_action("urn:micasaverde-com:serviceId:HomeAutomationGateway1", "Reload", {}, 0)
else
luup.reload()
end
end
return {
Initialize = _init,
ReloadLuup = _luup_reload,
GetMemoryUsed = _getmemoryused,
SetLuupFailure = _setluupfailure,
GetUI = _getui,
IsUI5 = _UI5,
IsUI6 = _UI6,
IsUI7 = _UI7,
IsUI8 = _UI8,
IsOpenLuup = _OpenLuup
}
end
-- Need wrapper for Vera UI7.31 to set TLS protocol. Sadly tls1.2 is not supported on the Lite.
-- Also supports gzip to reduce network load if lua_zlib is installed.
local function HttpsGet(strURL)
if (utils.GetUI() ~= utils.IsOpenLuup) and (not luup.model) then
-- Older try to user curl
local bdy,cde,hdrs = 1, 200, nil
local p = io.popen("curl -k -s -m 15 -o - '" .. strURL .. "'")
local result = p:read("*a")
p:close()
return bdy,cde,hdrs,result
else
-- Newer veras we can use http module
local bodys = {}
local headers = {}
if zlib then
headers["accept-encoding"] = "gzip, deflate"
else
headers["accept-encoding"] = "deflate"
end
local bdy,cde,hdrs,stts = https.request{
url = strURL,
method = 'GET',
headers = headers,
protocol = "any",
options = {"all", "no_sslv2", "no_sslv3"},
verify = "none",
sink=ltn12.sink.table(bodys)
}
local enc = hdrs["content-encoding"] or "none"
if type(bodys) == 'table' then bodys = table.concat(bodys) end
if zlib and string.find(enc, "gzip") then
bodys = zlib.inflate()(bodys)
end
return bdy,cde,hdrs,bodys
end
end
-- Insert found value into table
local function insert_value(tab, varName, value, iconMap)
local ti = table.insert
local mult = nil
local def = nil
local vn = nil
if type(varName) == "table" then
mult = varName.multiplier
def = varName.default
vn = varName.name
else
vn = varName
end
if value then
if mult then
value = tonumber(value) * mult
elseif vn == "Icon" and iconMap then
value = iconMap[value] or 44
end
-- log.Debug("Insert key %s, value %s", vn, value)
ti(tab, {vn, value})
return true
else
if def then
-- log.Debug("Insert key %s, default value %s", vn, def)
ti(tab, {vn, def})
return true
end
return false
end
end
-- Do nested key mapping.
local function key_map(tkey, curItems, confMap)
local function key_map_sub(key, curItems)
local value = nil
if key:find("%.") then
local x = curItems
for field in key:gmatch "[^%.%[%]]+" do
x = x[tonumber(field) or field]
if not x then return nil end
end
value = x
else
value = curItems[key]
end
return value
end
-- Look for key conversions
if confMap then
-- Substitude part of key if needed.
if type(confMap.sub) == "table" and #confMap.sub == 2 then
if tkey:find(confMap.sub[1]) then
tkey = tkey:gsub(confMap.sub[1], confMap.sub[2])
--log.Debug(" sub %s with %s, resulting key %s",confMap.sub[1], confMap.sub[2], tkey)
end
end
-- Prefix key if needed.
if type(confMap.prfx) == "string" then
tkey = confMap.prfx .. tkey
--log.Debug(" prefix with %s, resulting key %s",confMap.prfx,tkey)
end
end
local value = nil
if tkey:find("|") then
if tkey:sub(1,2) == "o|" then
-- Use either key as value
local key1,key2 = tkey:match("o|([%w_]-)|([%w_]+)")
if curItems[key1] then
value = key1
elseif curItems[key2] then
value = key2
end
else
-- Get value of either key. If missing there is none, i.e. zero.
local key1,key2 = tkey:match("([%w_%.]-)|([%w_%.]+)")
value = key_map_sub(key1, curItems) or key_map_sub(key2, curItems)
end
else
value = key_map_sub(tkey, curItems)
end
if confMap and confMap.ppf then
value = confMap.ppf(tkey, value)
end
return value
end
-- Process one day data and map
local function parse_input_day(input, varMap, iconMap, confMap)
local res = {}
for tkey, varName in pairs(varMap) do
-- See if complex mapping is needed
local value = key_map(tkey, input, confMap)
if not insert_value(res, varName, value, iconMap) then
log.Debug("Key not found %s",tkey)
end
end
return res
end
-- Table of Weather providers with init and update functions
-- Must match providerMap in J_MsWeather.js
local ProviderMap = {
[1] = { name = "Dark Sky",
init = function()
-- Check for required settings
complete = MS.Latitude ~= "" and MS.Longitude ~= "" and MS.Key ~= "" and MS.Units ~= "" and MS.Language ~= ""
if not complete then
var.Set("DisplayLine1", "Complete settings first.", SID_AltUI)
log.Error("DarkSky setup is not completed.")
end
var.Set("ProviderName", "DarkSky")
var.Set("ProviderURL", "darksky.net")
return complete
end,
update = function()
local urltemplate = "https://api.darksky.net/forecast/%s/%s,%s?lang=%s&units=%s&exclude=hourly,alerts"
local url = string.format(urltemplate, MS.Key, MS.Latitude, MS.Longitude, MS.Language, MS.Units)
-- See if user wants forecast, if not eliminate daily from request
if MS.ForecastDays == 0 then url = url .. ",daily" end
-- If there is no rain sensor we do not need minutely data
if MS.RainSensor == 0 then url = url .. ",minutely" end
log.Debug("calling DarkSky API with url = %s", url)
local wdata, retcode, headers, res = HttpsGet(url)
local err = (retcode ~=200)
if err then -- something wrong happened (website down, wrong key or location)
log.Error("DarkSky API call failed with http code = %s", tostring(retcode))
return false, res
end
log.Debug(res)
local data, err = json.decode(res)
if not data then
log.Error("DarkSky API json decode error = %s", tostring(err))
return false, "Invalid data"
end
-- this is the table used to map any providers output elements with the plugin variables
local currentlyMap = {
["apparentTemperature"] = "CurrentApparentTemperature",
["cloudCover"] = { name = "CurrentCloudCover", multiplier = 100 },
["dewPoint"] = "CurrentDewPoint",
["humidity"] = { name = "CurrentHumidity", multiplier = 100 },
["icon"] = "Icon",
["ozone"] = "CurrentOzone",
["uvIndex"] = "CurrentuvIndex",
["visibility"] = "CurrentVisibility",
["precipIntensity"] = "CurrentPrecipIntensity",
["precipProbability"] = { name = "CurrentPrecipProbability", multiplier = 100 },
["precipType"] = "CurrentPrecipType",
["pressure"] = "CurrentPressure",
["summary"] = "CurrentConditions",
["temperature"] = "CurrentTemperature",
["time"] = "LastUpdate",
["sunriseTime"] = "CurrentSunrise",
["sunsetTime"] = "CurrentSunset",
["windBearing"] = "CurrentWindBearing",
["windSpeed"] = "CurrentWindSpeed",
["windGust"] = "CurrentWindGust"
}
local forecastMap = {
["pressure"] = "Pressure",
["summary"] = "Conditions",
["ozone"] = "Ozone",
["uvIndex"] = "uvIndex",
["visibility"] = "Visibility",
["precipIntensity"] = "PrecipIntensity",
["precipIntensityMax"] = "PrecipIntensityMax",
["precipProbability"] = { name = "PrecipProbability", multiplier = 100 },
["precipType"] = "PrecipType",
["temperatureMax"] = "MaxTemp",
["temperatureMin"] = "MinTemp",
["temperatureHigh"] = "HighTemp",
["temperatureLow"] = "LowTemp",
["apparentTemperatureMax"] = "ApparentMaxTemp",
["apparentTemperatureMin"] = "ApparentMinTemp",
["icon"] = "Icon",
["cloudCover"] = { name = "CloudCover", multiplier = 100 },
["dewPoint"] = "DewPoint",
["humidity"] = { name = "Humidity", multiplier = 100 },
["sunriseTime"] = "Sunrise",
["sunsetTime"] = "Sunset",
["windBearing"] = "WindBearing",
["windSpeed"] = "WindSpeed",
["windGust"] = "WindGust"
}
local iconMap = {
["clear-day"] = 32, ["clear-night"] = 31, ["rain"] = 12, ["snow"] = 16, ["sleet"] = 18, ["wind"] = 24,
["fog"] = 20, ["cloudy"] = 26, ["partly-cloudy-day"] = 30, ["partly-cloudy-night"] = 29, ["hail"] = 17,
["thunderstorm"] = 4, ["tornado"] = 1
}
local varContainer = {}
-- Get the currently values we are interested in.
local curItems = data.currently
if curItems then
varContainer.currently = parse_input_day(curItems, currentlyMap, iconMap)
else
log.Warning("No currently data")
end
-- Get the forecast data the user wants
if MS.ForecastDays > 0 then
varContainer.forecast = {}
for fd = 1, MS.ForecastDays do
local curDay = data.daily.data[fd]
if curDay then
varContainer.forecast[fd] = parse_input_day(curDay, forecastMap, iconMap)
else
log.Warning("No daily data for day "..fd)
end
end
else
log.Debug("No forecast data configured")
end
return true, varContainer
end
},
[2] = { name = "Weather Underground",
init = function()
-- Check for required settings
complete = MS.Latitude ~= "" and MS.Longitude ~= "" and MS.Key ~= "" and MS.StationID ~= ""
if not complete then
var.Set("DisplayLine1", "Complete settings first.", SID_AltUI)
log.Error("Weather Underground setup is not completed.")
end
var.Set("ProviderName", "WunderGround")
var.Set("ProviderURL", "www.wunderground.com")
return complete
end,
update = function()
-- Update for local station
--https://github.com/timuckun/wunderground-web-component/blob/main/weather_underground_web_component.js
-- https://docs.google.com/document/d/1KGb8bTVYRsNgljnNH67AMhckY8AQT2FVwZ9urj8SWBs/edit#
local lang = languageMap[MS.Language] or "en-US"
local urltemplate = "https://api.weather.com/v2/pws/observations/current?numericPrecision=decimal&stationId=%s&format=json&units=%s&apiKey=%s"
local url = string.format(urltemplate, MS.StationName, MS.Units, MS.Key)
log.Debug("calling Wunder Ground API with url = %s", url)
local wdata, retcode, headers, res = HttpsGet(url)
local err = (retcode ~=200)
if err then -- something wrong happened (website down, wrong key or location)
log.Error("Wunder Ground API call failed with http code = %s", tostring(retcode))
return false, res
end
log.Debug(res)
local data, pos, msg = dkjson.decode(res) -- Response can include null values, do not use cjson.
if not data then
log.Error("Wunder Ground API json decode error = %s", tostring(msg))
return false, "Invalid data"
end
-- this is the table used to map any providers output elements with the plugin variables
local currentlyMap = {
["units.heatIndex"] = "CurrentApparentTemperature",
-- [""] = "CurrentCloudCover",
["units.dewpt"] = "CurrentDewPoint",
["humidity"] = "CurrentHumidity",
-- [""] = "Icon",
-- [""] = "CurrentOzone",
["uv"] = "CurrentuvIndex",
-- [""] = "CurrentVisibility",
["units.precipRate"] = "CurrentPrecipIntensity",
-- [""] = "CurrentPrecipProbability",
-- [""] = "CurrentPrecipType",
["units.pressure"] = "CurrentPressure",
-- [""] = "CurrentConditions",
["units.temp"] = "CurrentTemperature",
["epoch"] = "LastUpdate",
-- [""] = "CurrentSunrise",
-- [""] = "CurrentSunset",
["winddir"] = "CurrentWindBearing",
["units.windSpeed"] = "CurrentWindSpeed",
["units.windGust"] = "CurrentWindGust"
}
local forecastMap = {
-- [""] = "Pressure",
["narrative"] = "Conditions",
-- [""] = "Ozone",
["daypart.1.uvIndex"] = "uvIndex",
-- [""] = "Visibility",
["qpf"] = "PrecipIntensity",
-- ["precipIntensityMax"] = "PrecipIntensityMax",
["daypart.1.precipChance"] = "PrecipProbability",
["daypart.1.precipType"] = "PrecipType",
["temperatureMax"] = "MaxTemp",
["temperatureMin"] = "MinTemp",
["daypart.1.temperatureHeatIndex"] = "ApparentMaxTemp",
["daypart.1.temperatureWindChill"] = "ApparentMinTemp",
["daypart.1.iconCode"] = "Icon",
["daypart.1.cloudCover"] = "CloudCover",
-- [""] = "DewPoint",
["sunriseTimeUtc"] = "Sunrise",
["sunsetTimeUtc"] = "Sunset",
["daypart.1.relativeHumidity"] = "Humidity",
["daypart.1.windDirection"] = "WindBearing",
["daypart.1.windSpeed"] = "WindSpeed",
-- [""] = "WindGust"
}
local varContainer = {}
-- Get the currently values we are interested in.
local curItems = data.observations[1]
-- We need to change string .units. in key to right value
local confMap = {
sub = {"units.", (MS.Units == "m" and "metric." or (MS.Units == "e" and "imperial." or (MS.Units == "s" and "metric_si." or "uk_hybrid.")))}
}
if curItems then
varContainer.currently = parse_input_day(curItems, currentlyMap, iconMap, confMap)
else
log.Warning("No current data")
end
if MS.ForecastDays > 0 then
-- We check forecast only once an hour even if poll rate is higher.
local lastfcUpdate = var.GetNumber("LastForecastTS")
local now = os.time()
local tt = os.date("*t", now)
if (now - lastfcUpdate) < 3600 then
log.Info("Skipping Wunder Ground forecast request. Last update was %s seconds ago.", now - lastfcUpdate)
return true, varContainer
end
var.Set("LastForecastTS", now)
-- Get forecast data
local days = 3
if MS.ForecastDays > 3 then days = 5 end
if MS.ForecastDays > 5 then days = 7 end
local urltemplate = "https://api.weather.com/v3/wx/forecast/daily/%sday?geocode=%s,%s&format=json&language=%s&units=%s&apiKey=%s"
local url = string.format(urltemplate, days, MS.Latitude, MS.Longitude, lang, MS.Units, MS.Key)
log.Debug("calling Wunder Ground API with url = %s", url)
local wdata, retcode, headers, res = HttpsGet(url)
local err = (retcode ~=200)
if err then -- something wrong happened (website down, wrong key or location)
log.Error("Wunder Ground API call failed with http code = %s", tostring(retcode))
return false, res
end
log.Debug(res)
local data, pos, msg = dkjson.decode(res) -- Response can include null values, do not use cjson.
if not data then
log.Error("Wunder Ground API json decode error = %s", tostring(msg))
return false, "Invalid data"
end
varContainer.forecast = {}
local curDay = data
for fd = 1, MS.ForecastDays do
if curDay then
local confMap = {
ppf = function(key, value)
local res = value
if value then
if key:find("daypart.1") then
res = value[(fd-1)*2+1]
else
res = value[fd]
end
end
return res
end
}
varContainer.forecast[fd] = parse_input_day(curDay, forecastMap, iconMap, confMap)
else
log.Warning("No daily data for day "..fd)
end
end
end
return true, varContainer
end
},
[3] = { name = "OpenWeather",
init = function()
-- Check for required settings
complete = MS.Latitude ~= "" and MS.Longitude ~= "" and MS.Key ~= ""
if not complete then
var.Set("DisplayLine1", "Complete settings first.", SID_AltUI)
log.Error("OpenWeather setup is not completed.")
end
var.Set("ProviderName", "OpenWeather")
var.Set("ProviderURL", "www.openweathermap.org")
return complete
end,
update = function()
local urltemplate = "https://api.openweathermap.org/data/2.5/onecall?lat=%s&lon=%s&units=%s&lang=%s&appid=%s&exclude=hourly"
local url = string.format(urltemplate, MS.Latitude, MS.Longitude, MS.Units, MS.Language, MS.Key)
-- See if user wants forecast, if not eliminate daily from request
if MS.ForecastDays == 0 then url = url .. ",daily" end
-- If there is no rain sensor we do not need minutely data
if MS.RainSensor == 0 then url = url .. ",minutely" end
log.Debug("calling OpenWeather API with url = %s", url)
local wdata, retcode, headers, res = HttpsGet(url)
local err = (retcode ~=200)
if err then -- something wrong happened (website down, wrong key or location)
log.Error("OpenWeather API call failed with http code = %s", tostring(retcode))
return false, res
end
-- this is the table used to map any providers output elements with the plugin variables
local currentlyMap = {
["feels_like"] = "CurrentApparentTemperature",
["clouds"] = "CurrentCloudCover",
["dew_point"] = "CurrentDewPoint",
["humidity"] = "CurrentHumidity",
["weather.1.icon"] = "Icon",
-- [""] = "CurrentOzone",
["uvi"] = "CurrentuvIndex",
["visibility"] = { name = "CurrentVisibility", multiplier = 0.001 },
["rain.1h|snow.1h"] = { name = "CurrentPrecipIntensity", default = 0 },
-- [""] = "CurrentPrecipProbability",
["o|rain|snow"] = { name = "CurrentPrecipType", default = "None" },
["pressure"] = "CurrentPressure",
["weather.1.description"] = "CurrentConditions",
["temp"] = "CurrentTemperature",
["dt"] = "LastUpdate",
["sunrise"] = "CurrentSunrise",
["sunset"] = "CurrentSunset",
["wind_deg"] = "CurrentWindBearing",
["wind_speed"] = "CurrentWindSpeed",
["wind_gust"] = "CurrentWindGust"
}
local forecastMap = {
["pressure"] = "Pressure",
["weather.1.description"] = "Conditions",
-- [""] = "Ozone",
["uvi"] = "uvIndex",
-- [""] = "Visibility",
["rain|snow"] = { name = "PrecipIntensity", default = 0 },
-- [""] = "PrecipIntensityMax",
["pop"] = "PrecipProbability",
["o|rain|snow"] = { name = "PrecipType", default = "None" },
["temp.max"] = "MaxTemp",
["temp.min"] = "MinTemp",
["temp.day"] = "HighTemp",
["temp.night"] = "LowTemp",
["feels_like.day"] = "ApparentMaxTemp",
["feels_like.night"] = "ApparentMinTemp",
["weather.1.icon"] = "Icon",
["clouds"] = "CloudCover",
["dew_point"] = "DewPoint",
["humidity"] = "Humidity",
["sunrise"] = "Sunrise",
["sunset"] = "Sunset",
["wind_deg"] = "WindBearing",
["wind_speed"] = "WindSpeed",
["wind_gust"] = "WindGust"
}
local iconMap = {
["01d"] = 32, ["01n"] = 31, ["02d"] = 34, ["02n"] = 33, ["03d"] = 30, ["03n"] = 29, ["04d"] = 28,
["04n"] = 29, ["09d"] = 11, ["09n"] = 11, ["11d"] = 38, ["11n"] = 47, ["13d"] = 16, ["13n"] = 16,
["50d"] = 20, ["50n"] = 20
}
local airMap = {
["components.o3"] = "CurrentOzone",
["components.co"] = "CurrentCO",
["components.no"] = "CurrentNO",
["components.no2"] = "CurrentNO2",
["components.so2"] = "CurrentSO2",
["components.nh3"] = "CurrentNH3",
["components.pm10"] = "CurrentPM10",
["components.pm2_5"] = "CurrentPM25",
["main.aqi"] = "CurrentAirQuality"
}
log.Debug(res)
local data, err = json.decode(res)
if not data then
log.Error("OpenWeather API json decode error = %s", tostring(err))