-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathL_WeMo1.lua
1220 lines (1104 loc) · 43.3 KB
/
L_WeMo1.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
--
-- WeMo plugin
-- Copyright (C) 2013 Deborah Pickett
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
-- Version 0.0 2013-01-05 by Deborah Pickett
--
module ("L_WeMo1", package.seeall)
local socket = require("socket")
local http = require("socket.http")
local url = require("socket.url")
local ltn12 = require("ltn12")
local lxp = require("lxp")
local g_appendPtr
Debug = 1
Device = nil
Timer = 60 --loop timer for manual checking of Insight parameters, subscribe sends to many messages.
Version = 1.326
ServiceId = "urn:futzle-com:serviceId:WeMo1"
TypeDeviceFileMap = {
[ "urn:Belkin:device:controllee:1" ] = "D_WeMo1_Controllee1.xml",
[ "urn:Belkin:device:lightswitch:1" ] = "D_WeMo1_Controllee1.xml",
[ "urn:Belkin:device:insight:1" ] = "D_WeMo1_Controllee1.xml",
[ "urn:Belkin:device:sensor:1" ] = "D_WeMo1_Sensor1.xml"
}
TypeDeviceFileMap_UI7 = {
[ "urn:Belkin:device:controllee:1" ] = "D_WeMo1_Controllee1_UI7.xml",
[ "urn:Belkin:device:lightswitch:1" ] = "D_WeMo1_Controllee1_UI7.xml",
[ "urn:Belkin:device:insight:1" ] = "D_WeMo1_Controllee1_UI7.xml",
[ "urn:Belkin:device:sensor:1" ] = "D_WeMo1_Sensor1_UI7.xml"
}
UsnChildMap = {}
ChildDevices = {}
ProxyApiVersion = nil
FutureActionQueue = {}
InsightQueue = {}
local parametersTable = {
"Status", -- 0 Off, 1 On or 8 On Below power threshold (See PowerThreshold).
"LastChange", -- Unix timestamp of last changed state.
"OnFor", -- Time in seconds an Insight device was last turned on for.
"OnToday", -- Time in seconds an Insight device has been switched on today.
"OnTotal", -- Time in seconds an Insight device has been switched on totally.
"TimePeriod", -- Time in seconds over which onTotal applies. Typically 2 weeks except first used.
"AveragePower", -- Average power consumption in Watts.
"InstantPower", -- Instantaneous power (mW).
"TodayMW", -- Energy used today in mW-minutes.
"TotalMW", -- Energy used over time period in mW-minutes.
"PowerThreshold" -- Power Threshold.
}
local currentParameters = {}
-- Debug levels:
-- 0: None except startup message.
-- 1: Errors that prevent the plugin from functioning (red).
-- 2: UPnP status information.
-- 3: UPnP request and response bodies.
-- 4: XML parsing.
function debug(s, level)
if (level == nil) then level = 1 end
if (level <= Debug) then
luup.log(s)
end
end
local function checkVersion()
local ui7Check = luup.variable_get(ServiceId, "UI7Check", Device) or ""
if ui7Check == "" then
luup.variable_set(ServiceId, "UI7Check", "false", Device)
ui7Check = "false"
end
if( luup.version_branch == 1 and luup.version_major == 7 and ui7Check == "false") then
luup.variable_set(ServiceId, "UI7Check", "true", Device)
luup.attr_set("device_json", "D_WeMo1_UI7.json", Device)
luup.reload()
end
end
-- ssdpSearchParse(resp)
-- Parameters:
-- resp: Full UDP response text.
-- Return value on success:
-- [1] location (URL to send UPnP commands to)
-- [2] table containing parsed response. Keys:
-- expiry: timestamp when the service will expire.
-- host: HTTP IP address from location.
-- port: HTTP port from location.
-- usn: Host's unique id
-- uuid: UUID portion of USN, before "::".
-- namespace: namespace portion of USN, after "::".
-- Return value on failure:
-- [1] nil
-- [2] reason for failure, or status code from first line of response.
function ssdpSearchParse(resp)
local responseStatus = resp:match("^HTTP/1\.1 (%d%d%d)")
if (responseStatus == "200") then
-- Got a good response.
local info = {}
-- CACHE-CONTROL says when this information expires
info.expiry = resp:match("\r\nCACHE-CONTROL: *max-age=(%d+)\r\n")
if (info.expiry) then info.expiry = os.time() + tonumber(info.expiry) end
-- LOCATION is a URL which says where this service can be reached.
local location = resp:match("\r\nLOCATION: *(.-)\r\n")
if (location) then
-- Extract host and port for convenience.
local host = location:match("^%w+://([^/]+)")
if (host:match(":")) then
info.host, info.port = host:match("^(.+):(.+)$")
info.port = tonumber(info.port)
else
info.host = host
info.port = 80
end
else
debug("Missing header LOCATION", 2)
return nil, "Missing header LOCATION"
end
-- USN is the service name.
info.usn = resp:match("\r\nUSN: *(.-)\r\n")
if (info.usn) then
info.uuid, info.namespace = info.usn:match("^(.-)::(.+)$")
if (not info.uuid or not info.namespace) then
debug("Bad USN format from " .. location .. ": " .. info.usn, 2)
return nil, "Bad USN format: " .. info.usn
end
else
debug("Missing header USN", 2)
return nil, "Missing header USN"
end
return location, info
else
debug("Bad SSDP response " .. responseStatus, 2)
return nil, responseStatus
end
end
-- ssdpSearch(target, delay, ipaddr)
-- Parameters:
-- target: UPnP search scope (nil means "upnp:rootdevice")
-- delay: Seconds to wait for all responses.
-- ipaddr: Unicast/Multicast address to send search packet (nil means 239.255.255.250)
-- Return value on success:
-- table of responses received (possibly length 0),
-- key: location,
-- value: table
function ssdpSearch(target, delay, ipaddr)
local returnImmediately = (ipaddr ~= nil)
if (ipaddr == nil) then ipaddr = "239.255.255.250" end
if (target == nil) then target = "upnp:rootdevice" end
local result = {}
local udp = socket.udp()
local req = "M-SEARCH * HTTP/1.1\r\n"..
"HOST: 239.255.255.250:1900\r\n" ..
"MAN: \"ssdp:discover\"\r\n" ..
"MX: " .. delay .. "\r\n" ..
"ST: " .. target .. "\r\n" ..
"\r\n"
debug("M-SEARCH sent to " .. ipaddr .. ":1900", 2)
debug("M-SEARCH body: " .. req, 3)
udp:sendto(req, ipaddr, 1900)
udp:settimeout(delay)
repeat
local resp, peer, port = udp:receivefrom()
if (resp ~= nil) then
debug("M-SEARCH response received from " .. peer .. " UDP port " .. port, 2)
debug("M-SEARCH response body: " .. resp, 3)
local location, info = ssdpSearchParse(resp)
if (location) then
debug("Response identifies itself as " .. info.host .. ":" .. info.port .. " from UUID " .. info.uuid, 2)
result[location] = info
end
end
until resp == nil or returnImmediately
udp:close()
return result
end
-- createXpathParser(targets)
-- Returns a parser object that collects strings in an XML document based on their root-to-element "xpath".
-- Parameters:
-- targets: array of strings, the paths to look for. In form "/root/element1/element2".
-- Returns:
-- table, keys:
-- sink: ltn12 sink, to be passed to the http.request() function.
-- result: function which takes an XPath that was sought (string).
-- returns an array, each element one occurrence of the xpath, contains the strings in that element.
function createXpathParser(targets)
local currentXpathTable = {}
local currentXpath = function()
return "/" .. table.concat(currentXpathTable, "/")
end
local result = {}
local targetTable = {}
for _, xpath in pairs(targets) do
targetTable[xpath] = true
result[xpath] = {}
end
local xmlParser = lxp.new({
CharacterData = function(parser, string)
debug("XML: string " .. string, 4)
if (targetTable[currentXpath()]) then
debug("XPath matched, add to result", 4)
result[currentXpath()][#(result[currentXpath()])] = result[currentXpath()][#(result[currentXpath()])] .. string
end
end,
StartElement = function(parser, elementName, attributes)
debug("XML: start element " .. elementName, 4)
table.insert(currentXpathTable, elementName)
if (targetTable[currentXpath()]) then
table.insert(result[currentXpath()], "")
end
end,
EndElement = function(parser, elementName)
debug("XML: end element " .. elementName, 4)
table.remove(currentXpathTable)
end,
}, "|")
local sink = function(chunk, err)
if (chunk == nil) then
debug("sink: end of file", 4)
xmlParser:parse()
xmlParser:close()
return nil
end
debug("sink: " .. chunk, 4)
if (xmlParser:parse(chunk) == nil) then
debug("sink: error", 4)
--xmlParser:close()
end
return 1
end
return {
sink = sink,
result = function(s) return result[s] end
}
end
-- upnpGetDevice(location, timeout)
-- Gets information about a UPnP device.
-- Parameters:
-- location: string, HTTP URI of the device from the SSDP discovery.
-- timeout: number of seconds to wait for a response.
-- Return value on success:
-- table, with keys:
-- deviceType
-- friendlyName
-- serialNumber
-- serviceList, keys are serviceIds, values are tables:
-- serviceType,
-- controlURL,
-- eventSubURL
-- Return value on failure:
-- [1] nil
-- [2] Reason for failure (from http.request()).
function upnpGetDevice(location, timeout)
-- UPnP nonconformance alert!
-- Namespace should be urn:schemas-upnp-org:device-1-0, but is urn:Belkin:device-1-0 on WeMo devices.
local deviceXPath = "/urn:Belkin:device-1-0|root/urn:Belkin:device-1-0|device"
local deviceTypeXPath = deviceXPath .. "/urn:Belkin:device-1-0|deviceType"
local friendlyNameXPath = deviceXPath .. "/urn:Belkin:device-1-0|friendlyName"
local serialNumberXPath = deviceXPath .. "/urn:Belkin:device-1-0|serialNumber"
local serviceListXPath = deviceXPath .. "/urn:Belkin:device-1-0|serviceList"
local serviceXPath = serviceListXPath .. "/urn:Belkin:device-1-0|service"
local serviceTypeXPath = serviceXPath .. "/urn:Belkin:device-1-0|serviceType"
local serviceIdXPath = serviceXPath .. "/urn:Belkin:device-1-0|serviceId"
local controlURLXPath = serviceXPath .. "/urn:Belkin:device-1-0|controlURL"
local eventSubURLXPath = serviceXPath .. "/urn:Belkin:device-1-0|eventSubURL"
-- Look for these paths in the XML.
local xpathParser = createXpathParser({
deviceTypeXPath,
friendlyNameXPath,
serialNumberXPath,
serviceTypeXPath,
serviceIdXPath,
controlURLXPath,
eventSubURLXPath,
})
-- Create a socket with a timeout.
local sock = function()
local s = socket.tcp()
s:settimeout(timeout)
return s
end
-- Get the device's top-level device XML, and pull out the interesting bits.
local request, code = http.request({
url = location,
sink = xpathParser.sink,
create = sock,
})
-- Seems to return (nil, "closed") even when successful.
if (request == nil and code ~= "closed" ) then
debug("HTTP response " .. code, 3)
return nil, code
else
local deviceType = xpathParser.result(deviceTypeXPath)
debug("Device type instances in this XML: " .. #deviceType, 3)
if (#deviceType == 1) then
debug("Device type is " .. deviceType[1], 2)
if(TypeDeviceFileMap[deviceType[1]]) then
debug("Device " .. location .. " is a " .. TypeDeviceFileMap[deviceType[1]], 1)
local friendlyName = xpathParser.result(friendlyNameXPath)[1]
local serialNumber = xpathParser.result(serialNumberXPath)[1]
debug("Device " .. location .. " is called " .. friendlyName .. " and has serial Number " .. serialNumber, 1)
local result = {
deviceType = deviceType[1],
friendlyName = xpathParser.result(friendlyNameXPath)[1],
serialNumber = xpathParser.result(serialNumberXPath)[1],
}
-- Service information is spread across several tables.
result.serviceList = {}
for s = 1, #(xpathParser.result(serviceIdXPath)) do
local serviceId = xpathParser.result(serviceIdXPath)[s]
local serviceType = xpathParser.result(serviceTypeXPath)[s]
local controlURL = xpathParser.result(controlURLXPath)[s]
local eventSubURL = xpathParser.result(eventSubURLXPath)[s]
result.serviceList[serviceId] = {
serviceType = serviceType,
controlURL = controlURL,
eventSubURL = eventSubURL,
}
end
return result
else
-- A device we don't care about.
return nil, deviceType[1]
end
else
-- Device is reporting too many, or too few, types.
return nil, table.concat(deviceType, ", ")
end
end
end
-- subscribeToDevice(eventSubURL, renewalSID, timeout)
-- Send a UPnP SUBSCRIBE to the WeMo device,
-- and have it send events back to the UPnP proxy process.
-- Parameters:
-- eventSubURL: Absolute URL, the event subscription URL
-- of the UPnP device.
-- renewalSID: nil, if this is a new subscription.
-- Otherwise, the SID to be renewed.
-- timeout: wait this many seconds before giving up.
-- Return value on success:
-- SID (subscription ID) provided by the device.
-- Duration (in seconds) before the subscription must
-- be renewed.
-- Return value on failure:
-- nil
-- Reason for failure (string)
function subscribeToDevice(eventSubURL, renewalSID, timeout)
-- Learn Vera's IP address.
local s = socket.udp()
local remoteHost = eventSubURL:match("://(.-)[/:]") or ""
if remoteHost == "" then
return nil, "UNKNOWN"
end
debug("Remote host is " .. remoteHost, 3)
s:setpeername(remoteHost, 80) -- Any port will do, not actually connecting.
local myAddress = s:getsockname()
debug("Local host is " .. myAddress, 3)
s:close()
-- Create a socket with a timeout.
local sock = function()
local s = socket.tcp()
s:settimeout(timeout)
return s
end
local headers = {
["TIMEOUT"] = "Second-3600",
}
if (renewalSID) then
-- Renewing, include SID header.
headers["SID"] = renewalSID
else
-- New subscription, include CALLBACK and NT headers
headers["CALLBACK"] = "<http://" .. myAddress .. ":2529/upnp/event>"
headers["NT"] = "upnp:event"
end
-- Ask the device to inform the proxy about status changes.
local request, code, headers = http.request({
url = eventSubURL,
method = "SUBSCRIBE",
headers = headers,
create = sock,
})
if (request == nil and code ~= "closed") then
debug("Failed to subscribe to " .. eventSubURL .. ": " .. code, 1)
return nil, code
elseif (code ~= 200) then
debug("Failed to subscribe to " .. eventSubURL .. ": " .. code, 1)
return nil, code
else
local duration = headers["timeout"]:match("Second%-(%d+)")
debug("Subscription confirmed, EVENTURL = " .. eventSubURL .. ", SID = " .. headers["sid"] .. " with timeout " .. duration, 2)
return headers["sid"], tonumber(duration)
end
end
-- getProxyApiVersion()
-- Calls the proxy with GET /version.
-- Sets the ProxyApiVersion Luup variable to the value received
-- (or the empty string).
-- Return value:
-- nil if the proxy is not running.
-- The proxy API version (as a string) otherwise.
function getProxyApiVersion()
local sock = function()
local s = socket.tcp()
s:settimeout(2)
return s
end
local t = {}
local request, code = http.request({
url = "http://localhost:2529/version",
create = sock,
sink = ltn12.sink.table(t)
})
if (request == nil and code == "timeout") then
-- Proxy may be busy.
debug("Temporarily cannot communicate with proxy", 1)
return nil
elseif (request == nil and code ~= "closed") then
-- Proxy not running.
debug("Cannot contact UPnP event proxy: " .. code, 1)
luup.variable_set(ServiceId, "ProxyApiVersion", "", Device)
return ""
else
-- Proxy is running, note its version number.
ProxyApiVersion = table.concat(t)
luup.variable_set(ServiceId, "ProxyApiVersion", ProxyApiVersion, Device)
return ProxyApiVersion
end
end
-- proxyVersionAtLeast(n)
-- Returns true if the proxy is running and is at least version n.
function proxyVersionAtLeast(n)
if (ProxyApiVersion and tonumber(ProxyApiVersion:match("^(%d+)")) >= n) then
return true
end
return false
end
-- informProxyOfSubscription(deviceId)
-- Sends a PUT /upnp/event/[sid] message to the proxy,
-- asking it to inform this plugin if the BinaryState
-- UPnP variable changes.
-- Return value:
-- nil if the proxy timed out (should try again).
-- false if the proxy refused our request (permanently).
-- true if the proxy agreed to our request.
function informProxyOfSubscription(deviceId, subType)
debug("Informing proxy of subscription for device " .. deviceId .. " to " .. subType .. " events", 2)
local sock = function()
local s = socket.tcp()
s:settimeout(2)
return s
end
local d = ChildDevices[deviceId]
if (subType == "insight") then
sid = d.insightSid
expiry = d.insightExpiry
else
sid = d.sid
expiry= d.expiry
end
local table subscriptionType = {
["basic"]={variableName ='BinaryState', action ='notifyBinaryState', parameter ='binaryState'},
["insight"]={variableName ='InsightParams', action ='notifyInsightParams', parameter ='insightParams'},
}
i = subscriptionType[subType]
-- Tell proxy about this subscription.
local proxyRequestBody = "<subscription expiry='" .. expiry .. "'>"
proxyRequestBody = proxyRequestBody ..
"<variable name='" .. i.variableName .. "' host='localhost' deviceId='" ..
deviceId .. "' serviceId='" .. ServiceId ..
"' action='" .. i.action .. "' parameter='" .. i.parameter .. "' sidParameter='sid'/>"
proxyRequestBody = proxyRequestBody .. "</subscription>"
local request, code = http.request({
url = "http://localhost:2529/upnp/event/" .. url.escape(sid),
create = sock,
method = "PUT",
headers = {
["Content-Type"] = "text/xml",
["Content-Length"] = proxyRequestBody:len(),
},
source = ltn12.source.string(proxyRequestBody),
sink = ltn12.sink.null(),
})
if (request == nil and code ~= "closed") then
debug("Failed to notify proxy of subscription: " .. code, 1)
return nil
elseif (code ~= 200) then
debug("Failed to notify proxy of subscription: " .. code, 1)
return false
else
debug("Successfully notified proxy of subscription", 2)
return true
end
end
-- cancelProxySubscription(sid)
-- Sends a DELETE /upnp/event/[sid] message to the proxy,
-- Return value:
-- nil if the proxy timed out (should try again).
-- false if the proxy refused our request (permanently).
-- true if the proxy agreed to our request.
function cancelProxySubscription(sid)
debug("Cancelling unwelcome subscription for sid " .. sid, 2)
local sock = function()
local s = socket.tcp()
s:settimeout(2)
return s
end
local request, code = http.request({
url = "http://localhost:2529/upnp/event/" .. url.escape(sid),
create = sock,
method = "DELETE",
source = ltn12.source.empty(),
sink = ltn12.sink.null(),
})
if (request == nil and code ~= "closed") then
debug("Failed to cancel subscription: " .. code, 1)
return nil
elseif (code ~= 200) then
debug("Failed to cancel subscription: " .. code, 1)
return false
else
debug("Successfully cancelled subscription", 2)
return true
end
end
-- queueAction(delay, retries, action)
-- Remember to run the function in action (with no parameters)
-- in delay seconds. Allow only the specified number of retries.
function queueAction(delay, retries, action)
debug("Action queued for " .. type(action) .. ".", 2)
table.insert(FutureActionQueue, {
time = os.time() + delay,
retries = retries,
action = action
})
end
-- renewSubscription(deviceId)
-- Try to renew the UPnP subscription for the child device deviceId.
-- Return value:
-- nil if the renewal request timed out (and we should retry).
-- false if the renewal was refused (permanently).
-- true if the renewal was accepted (a later renewal will be
-- queued and the proxy will be informed).
function renewSubscription(deviceId, subType)
local deviceType = luup.devices[deviceId].id:match("^uuid:(%w+)%-*")
debug("Renewing subscription for device " .. deviceId .. ", Event = " .. subType .. ", DeviceId = " .. deviceType .. ".", 2)
local d = ChildDevices[deviceId]
if subType == "basic" then
local eventSubURL = url.absolute(d.location, d.eventSubURL)
debug("Renewing subscription at " .. eventSubURL, 2)
-- Ask the device to inform the proxy about status changes.
local sid, duration = subscribeToDevice(eventSubURL, d.sid, 5)
if (sid) then
debug("Duration before renewing subscription at " .. eventSubURL .. " is " .. duration, 2)
d.expiry = os.time() + duration
d.sid = sid
-- Tell the proxy of this subscription soon.
queueAction(0, 3, function() return informProxyOfSubscription(deviceId, subType) end)
queueAction(duration / 2, 3, function() return renewSubscription(deviceId, subType) end)
return true
else
return nil
end
elseif subType == "insight" then
eventSubURL = url.absolute(d.location, d.insightEventSubURL)
debug("Renewing subscription at " .. eventSubURL, 2)
-- Ask the device to inform the proxy about status changes.
local sid, duration = subscribeToDevice(eventSubURL, d.insightSid, 5)
if (sid) then
debug("Duration before renewing subscription at " .. eventSubURL .. " is " .. duration, 2)
d.insightSid = sid
d.insightExpiry = os.time() + duration
-- Tell the proxy of this subscription soon.
queueAction(0, 3, function() return informProxyOfSubscription(deviceId, subType) end)
queueAction(duration / 2, 3, function() return renewSubscription(deviceId, subType) end)
return true
else
return nil
end
end
end
-- subscribeToAllDevices()
-- Attempt to make a UPnP event subscription to
-- all devices.
function subscribeToAllDevices()
-- Check that the proxy is running.
for retries = 1, 3 do
if (getProxyApiVersion()) then
break
end
end
-- Since Proxy API version 1: accepts NOTIFY from device.
if (proxyVersionAtLeast(1)) then
for childId, d in pairs(ChildDevices) do
local deviceType = luup.devices[childId].id:match("^uuid:(%w+)%-*")
local eventSubURL = url.absolute(d.location, d.eventSubURL) or ""
debug("Subscribing to events at " .. eventSubURL, 2)
-- Ask the device to inform the proxy about status changes.
local sid, duration = subscribeToDevice(eventSubURL, nil, 5)
if (sid) then
d.sid = sid
d.expiry = os.time() + duration
-- Tell the proxy of this subscription soon.
queueAction(0, 3, function() return informProxyOfSubscription(childId, "basic") end)
queueAction(duration / 2, 3, function() return renewSubscription(childId, "basic") end)
local report = luup.variable_get(ServiceId, "Report", Device) or "0"
local reportTimer = tonumber(luup.variable_get(ServiceId, "ReportTimer", Device),10) or Timer
report = (report == "1") and true or false
if report and (reportTimer > 0) then
if deviceType == "Insight" then
queueAction(reportTimer, 0, function() return Timer(childId) end)
end
else
debug("Optional parameters of Insight switches will not be reported", 2)
end
end
end
end
end
function Timer(childId)
handleGetInsightParams(childId)
local reportTimer = tonumber(luup.variable_get(ServiceId, "ReportTimer", Device),10) or Timer
queueAction(reportTimer, 0, function() return Timer(childId) end)
return true
end
-- schedule()
-- Ask the plugin to sleep for as many seconds as
-- the next event (or five minutes, if there are no events).
function schedule()
-- How long to sleep?
local delay = 300
for i = 1, #FutureActionQueue do
if (FutureActionQueue[i].time <= os.time()) then
delay = 1
break
end
delay = math.min(delay, FutureActionQueue[i].time - os.time())
end
debug("Sleeping for " .. delay .. " seconds", 2)
luup.call_delay("reentry", delay, "")
end
-- reentry()
-- This function will be called when a sleep from
-- schedule() completes. In theory, one of the queued actions
-- is now ready to perform.
function reentry()
local action = nil
for i = 1, #FutureActionQueue do
if (FutureActionQueue[i].time <= os.time()) then
action = table.remove(FutureActionQueue, i)
break
end
end
-- Clock skew might mean there is no action.
if (action) then
local result = action.action()
if (result == nil) then
if (action.retries > 0) then
queueAction(math.random(1, 5), action.retries - 1, action.action)
end
end
end
-- Go back to sleep.
schedule()
end
local function createChildDevices()
-- Create child devices.
-- Use information collected from previous runs.
local childCount = luup.variable_get(ServiceId, "ChildCount", Device)
if (childCount == nil) then
luup.variable_set(ServiceId, "ChildCount", "0", Device)
childCount = 0
else
childCount = tonumber(childCount)
end
debug("Creating up to " .. childCount .. " children", 2)
local children = g_appendPtr
for child = 1, childCount do
-- UPnP device type.
local childType = luup.variable_get(ServiceId, "Child" .. child .. "Type", Device)
if (childType and childType ~= "") then
-- This was the device's Friendly Name at creation time.
local childName = luup.variable_get(ServiceId, "Child" .. child .. "Name", Device)
local childParameters = ""
-- Child may be at a fixed IP address.
local childAddress = luup.variable_get(ServiceId, "Child" .. child .. "Host", Device)
-- Use the device's IP address (if it's static) or
-- (otherwise) its UPnP device's USN (UDN) for the unique Id.
local childUSN
if (childAddress and childAddress ~= "") then
childParameters = childParameters .. ServiceId .. ",Host=" .. childAddress
childUSN = childAddress
else
childUSN = luup.variable_get(ServiceId, "Child" .. child .. "USN", Device)
end
-- Keep local munged copies of the device's UPnP files,
-- because we need additional elements (<staticJson>) and
-- want to filter out services we can't use.
local isUI7 = luup.variable_get(ServiceId, "UI7Check", Device) or ""
if isUI7 == "" then
luup.variable_set(ServiceId, "UI7Check", "false", Device)
isUI7 = "false"
end
if isUI7 == "true" then
local childDeviceFile = TypeDeviceFileMap_UI7[childType]
debug("Creating child " .. childUSN .. " (" .. childName .. ") as " .. childType, 2)
luup.chdev.append(Device, children, childUSN, childName, "", childDeviceFile, "I_WeMo1.xml", childParameters, false)
else
local childDeviceFile = TypeDeviceFileMap[childType]
debug("Creating child " .. childUSN .. " (" .. childName .. ") as " .. childType, 2)
luup.chdev.append(Device, children, childUSN, childName, "", childDeviceFile, "I_WeMo1.xml", childParameters, false)
end
end
end
end
-- initialize(lul_device)
-- Entry point for the plugin.
-- Parameters:
-- lul_device: The top-level device Id.
function initialize(lul_device)
debug("Starting WeMo plugin (device " .. lul_device .. ")", 0)
-- Set main Wemo device to failure to false
luup.set_failure(false, lul_device)
Device = lul_device
-- Check/Update plugin version.
luup.variable_set(ServiceId, "Version", Version, Device)
-- Check UI version.
checkVersion()
-- Go quiet with debug messages unless debugging enabled.
Debug = luup.variable_get(ServiceId, "Debug", Device) or ""
if (Debug == "") then
Debug = 0
luup.variable_set(ServiceId, "Debug", "0", Device)
else
Debug = tonumber(Debug)
end
-- Initialise settings for managing loop for checking Insight parameters
local report = luup.variable_get(ServiceId, "Report", Device) or ""
if (report == "") then
luup.variable_set(ServiceId, "Report", "0", Device)
end
local reportTimer = luup.variable_get(ServiceId, "ReportTimer", Device) or ""
if (reportTimer == "") then
luup.variable_set(ServiceId, "ReportTimer", "0", Device)
end
g_appendPtr = luup.chdev.start(Device)
createChildDevices()
luup.chdev.sync(Device, g_appendPtr)
-- If list of child devices changed, Luup engine will restart here.
-- Build child list.
debug("Roll call of child devices", 2)
for i, d in pairs(luup.devices) do
if (d.device_num_parent == Device) then
local usn = d.id
UsnChildMap[usn] = i
ChildDevices[i] = {}
ChildDevices[i].currentParameters = {}
debug("MiOS child device " .. i .. " has unique id " .. usn, 2)
end
end
-- Sync up with UPnP devices and match them to children.
-- First probe devices that are at fixed IP addresses.
-- These are probed explicitly so that they are found even
-- if they don't respond to multicast discovery (or if
-- multicast discovery is off).
for d, childDevice in pairs(ChildDevices) do
local host = luup.variable_get(ServiceId, "Host", d)
if (host and host ~= "") then
debug("Reconnecting to device at fixed address " .. host, 2)
local ssdpResponse = ssdpSearch(nil, 5, host)
for location, info in pairs(ssdpResponse) do
debug("Reconnected at " .. location, 2)
childDevice.host = host
childDevice.port = info.port
childDevice.location = location
childDevice.found = true
local upnpDevice = upnpGetDevice(location, 5)
if (upnpDevice) then
childDevice.serviceType = upnpDevice.serviceList["urn:Belkin:serviceId:basicevent1"].serviceType
childDevice.controlURL = upnpDevice.serviceList["urn:Belkin:serviceId:basicevent1"].controlURL
childDevice.eventSubURL = upnpDevice.serviceList["urn:Belkin:serviceId:basicevent1"].eventSubURL
if (upnpDevice.serviceList["urn:Belkin:serviceId:insight1"]) then
debug("Service list for Wemo Insight Switch", 2)
childDevice.insightServiceType = upnpDevice.serviceList["urn:Belkin:serviceId:insight1"].serviceType
childDevice.insightControlURL = upnpDevice.serviceList["urn:Belkin:serviceId:insight1"].controlURL
childDevice.insightEventSubURL = upnpDevice.serviceList["urn:Belkin:serviceId:insight1"].eventSubURL
end
end
end
if (not childDevice.found) then
debug("No response from " .. host, 1)
end
end
end
-- Now do a multicast search for any other devices.
local enableMulticast = luup.variable_get(ServiceId, "EnableMulticast", Device)
if (not enableMulticast) then
enableMulticast = "1"
luup.variable_set(ServiceId, "EnableMulticast", enableMulticast, Device)
end
if (enableMulticast == "1") then
local unknownDevices = {}
debug("Searching for UPnP devices...", 2)
-- Search at any address.
local allUpnp = ssdpSearch(nil, 5)
debug("Searching complete", 2)
for location, info in pairs(allUpnp) do
debug("UPnP location " .. location, 2)
debug("UPnP udn " .. info.uuid, 2)
local knownChild = UsnChildMap[info.host]
if (knownChild == nil) then
-- Dynamic device, perhaps.
knownChild = UsnChildMap[info.uuid]
end
if (knownChild ~= nil) then
if (ChildDevices[knownChild].found) then
-- Already created with a static address.
debug("Skipping " .. info.uuid .. " because it has already been found at " .. location, 2)
else
-- Known device, may be at a different IP address now because of DHCP.
debug("Uuid " .. info.uuid .. " is child device " .. knownChild .. " at " .. location, 2)
ChildDevices[knownChild].host = info.host
ChildDevices[knownChild].port = info.port
ChildDevices[knownChild].location = location
ChildDevices[knownChild].found = true
local upnpDevice = upnpGetDevice(location, 5)
if (upnpDevice) then
ChildDevices[knownChild].serviceType = upnpDevice.serviceList["urn:Belkin:serviceId:basicevent1"].serviceType
ChildDevices[knownChild].controlURL = upnpDevice.serviceList["urn:Belkin:serviceId:basicevent1"].controlURL
ChildDevices[knownChild].eventSubURL = upnpDevice.serviceList["urn:Belkin:serviceId:basicevent1"].eventSubURL
if(upnpDevice.serviceList["urn:Belkin:serviceId:insight1"]) then
debug("Service list for Wemo Insight Switch", 2)
ChildDevices[knownChild].insightServiceType = upnpDevice.serviceList["urn:Belkin:serviceId:insight1"].serviceType
ChildDevices[knownChild].insightControlURL = upnpDevice.serviceList["urn:Belkin:serviceId:insight1"].controlURL
ChildDevices[knownChild].insightEventSubURL = upnpDevice.serviceList["urn:Belkin:serviceId:insight1"].eventSubURL
end
end
end
else
-- Unrecognized UUID, perhaps a new device?
debug("Unknown uuid " .. info.uuid .. ", identifying ...", 2)
local upnpDevice = upnpGetDevice(location, 5)
if (upnpDevice) then
-- Discovered new WeMo device.
upnpDevice.location = location
upnpDevice.uuid = info.uuid
upnpDevice.host = info.host
debug("Noting details of unknown device " .. info.uuid, 2)
table.insert(unknownDevices, upnpDevice)
end
end
end
-- Any new UPnP devices found?
local unknownDeviceCount = 0
for _, d in pairs(unknownDevices) do
unknownDeviceCount = unknownDeviceCount + 1
luup.variable_set(ServiceId, "UnknownDevice" .. unknownDeviceCount .. "Type", d.deviceType, Device)
luup.variable_set(ServiceId, "UnknownDevice" .. unknownDeviceCount .. "USN", d.uuid, Device)
luup.variable_set(ServiceId, "UnknownDevice" .. unknownDeviceCount .. "Host", d.host, Device)
luup.variable_set(ServiceId, "UnknownDevice" .. unknownDeviceCount .. "Name", d.friendlyName .. " (" .. d.serialNumber .. ")", Device)
end
luup.variable_set(ServiceId, "UnknownDeviceCount", unknownDeviceCount, Device)
end
-- Any existing children not accounted for?
local unaccountedDevices = 0
for i, d in pairs(ChildDevices) do
if (not d.found) then
unaccountedDevices = unaccountedDevices + 1
end
luup.set_failure(not d.found, i)
end
if (unaccountedDevices > 0) then
-- return false, "Previously found WeMo devices not found.", string.format("%s[%d]", luup.devices[Device].description, Device)
end
-- Ask all devices to tell the UPnP proxy process when their state changes.
subscribeToAllDevices()
-- Start scheduler for future actions.
schedule()
return true
end
-- upnpCallAction(location, serviceType, action, parameters, values)
-- Perform a UPnP POST to the given control URL, and parse the response.
-- Parameters:
-- location: Control URL (absolute URL in string)
-- serviceType: Service type for this action, string
-- action: Name of action to invoke, string
-- parameters: array of parameters expected by the action (in the order given in the service file)
-- values: array of parameter values expected by the action (in the same order)
function upnpCallAction(location, serviceType, action, parameters, values)
local replyServiceType = (action =="GetInsightParams") and "urn:Belkin:service:metainfo:1" or serviceType
local envelopeXPath = "/http://schemas.xmlsoap.org/soap/envelope/|Envelope"
local bodyXPath = envelopeXPath .. "/http://schemas.xmlsoap.org/soap/envelope/|Body"
local responseXPath = bodyXPath .. "/" .. replyServiceType .. "|" .. action .. "Response"
-- Look for these paths in the response XML.
local xPathTargets = {}
for i = 1, #parameters do
table.insert(xPathTargets, responseXPath .. "/" .. parameters[i])
end
local xpathParser = createXpathParser(xPathTargets)
-- Create a socket with a timeout.
local sock = function()
local s = socket.tcp()
s:settimeout(5)
return s
end