-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontrol-ws.lsp
71 lines (68 loc) · 2.28 KB
/
control-ws.lsp
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
<?lsp
local deconz = require "deconz"
local function createDeconzEventListener(listener)
return function(event)
if not listener.listening then
error "stopped listening"
end
if event.id then
local sock = listener.sock
if event.e == 'changed' and event.r and event.state then
sock:write(ba.json.encode({
id = event.id,
r = event.r,
type = 'changed',
state = event.state
}), true)
elseif event.e == 'deleted' then
sock:write(ba.json.encode({
id = event.id,
type = 'deleted'
}), true)
else
--trace('unknown event kind or missing data', ba.json.encode(event))
end
else
trace('ignoring event', ba.json.encode(event))
end
end
end
-- handle websocket requests
local function socketHandler(listener)
return function(sock)
while true do
local data = sock:read()
if not data then break end
trace('socketHandler handling data: ' .. data)
data = ba.json.decode(data)
local response
if data.id and data.r == 'lights' then
local res, err = deconz.setLightState(data.id, data)
if err then
response = ba.json.encode { error = err }
elseif #res == 1 and res[1].success then
response = '{"ok": true}'
else
response = ba.json.encode { error = ba.json.encode(res) }
end
else
response = '{"error":"unrecognized WebSocket command"}'
end
ba.thread.run(function() sock:write(response, true) end)
end
trace 'socketHandler end'
listener.listening = false
listener.sock = nil
end
end
if request:header "Sec-WebSocket-Key" then
local sock = ba.socket.req2sock(request)
if sock then
local listener = { listening = true, sock = sock }
table.insert(app.deconzListeners, createDeconzEventListener(listener))
sock:event(socketHandler(listener), "s")
request:abort()
end
end
response:senderror(403, "Invalid request")
?>