aboutsummaryrefslogtreecommitdiff
path: root/hue.lua
blob: 54a00e4c029815c391bff61748d4146511fbbe79 (plain)
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
local config = require 'config'
local httpd = require 'httpd'

local hue = { }

function hue.req(conf, t, cb)
    conf = conf or config.loaded.hue
    local conn = net.createConnection()
    conn:on('connection', function(conn)
        conn:on('receive', function(conn, pl)
            if cb then
                cb(pl:find('200') and true)
            end
        end)
        req = {
            string.format('PUT /api/%s/lights/%d/state HTTP/1.1',
                conf.user, conf.light),
            string.format('Host: %s', conf.addr),
            'Connection: close',
            string.format('Content-Length: %d', #t + 2),
            '',
            t,
            ''
        }
        conn:send(table.concat(req, '\r\n'))
    end)
    conn:connect(80, conf.addr)
end

function hue.on(conf, bri, cb)
    hue.req(conf, string.format(
        '{"on":true,"bri":%d}',
        bri or 255), cb)
end

function hue.off(conf, cb)
    hue.req(conf, '{"on":false}', cb)
end

function hue.httpd_process(method, path, headers, content)
    if path == '/hue' then
        if method == 'GET' then
            local page = [[
<html>
<body>
<form method="post">
<input type="checkbox" name="on">
<input type="submit">
</form>
</body>
</html>
]]
            return 200, 'OK', { ['Content-Type'] = 'text/html' }, page
        elseif method == 'POST' then
            local form = httpd.parse_form(content)
            local on = form['on'] and true or false
            if form['on'] then
                hue.on(nil, 128)
            else
                hue.off()
            end
            return 200, 'OK', {}, 'OK!\n'
        end
    end
end

return hue