aboutsummaryrefslogtreecommitdiff
path: root/clock.lua
diff options
context:
space:
mode:
Diffstat (limited to 'clock.lua')
-rw-r--r--clock.lua101
1 files changed, 101 insertions, 0 deletions
diff --git a/clock.lua b/clock.lua
new file mode 100644
index 0000000..a14e5fa
--- /dev/null
+++ b/clock.lua
@@ -0,0 +1,101 @@
+local httpd = require 'httpd'
+local config = require 'config'
+local button = config.loaded.button and require 'button'
+local hue = config.loaded.button and require 'hue'
+local alarm = config.loaded.alarm and require 'alarm'
+local display = require 'display'
+
+local clock = {}
+
+local last_output
+
+local ntp_server = nil
+local ntp_counter = 0
+local ntp_counter_max = 24
+
+function clock.output()
+ local time = rtctime.get()
+ local output
+ local tm
+ if time ~= 0 then
+ tm = rtctime.epoch2cal(time + config.loaded.tz_shift * 3600)
+ output = string.format('%2d:%02d', tm.hour, tm.min)
+ else
+ output = '--:--'
+ if wifi.sta.getip() ~= nil then
+ clock.ntp_sync()
+ end
+ end
+ if last_output ~= output then
+ display.output(output)
+ last_output = output
+ if time ~= 0 and alarm then alarm.test(tm) end
+ end
+end
+
+function clock.ntp_sync()
+ if ntp_counter == 0 then
+ sntp.sync(ntp_server,
+ function(sec, usec, server)
+ local tm = rtctime.epoch2cal(sec + config.loaded.tz_shift * 3600)
+ print(string.format('ntp sync %04d-%02d-%02d %02d:%02d:%02d',
+ tm.year, tm.mon, tm.day, tm.hour, tm.min, tm.sec))
+ clock.output()
+ end,
+ function(code, err)
+ print('NTP sync fail: ' .. tostring(err) .. ' ' .. tostring(code))
+ end)
+ ntp_counter = ntp_counter_max - 1
+ else
+ ntp_counter = ntp_counter - 1
+ end
+end
+
+local function httpd_process(method, path, headers, content)
+ if method == 'GET' and path == '/' then
+ local page = [[
+<html>
+<body>
+<form method="post">
+Change time zone shift :
+<input type="text" name="tz_shift" value="%d">
+<input type="submit">
+</form>
+</body>
+</html>
+]]
+ page = string.format(page, config.loaded.tz_shift)
+ return 200, 'OK', { ['Content-Type'] = 'text/html' }, page
+ elseif method == 'POST' and path == '/' then
+ local v = content:match('tz_shift=(%d*)')
+ config.loaded.tz_shift = tonumber(v)
+ config.save()
+ clock.output()
+ return 200, 'OK', {}, 'OK!\n'
+ elseif alarm and path == '/alarm' then
+ return alarm.httpd_process(method, path, headers, content)
+ elseif hue and path == '/hue' then
+ return hue.httpd_process(method, path, headers, content)
+ else
+ return httpd.upload(method, path, headers, content)
+ end
+end
+
+function clock.start()
+ display.init()
+ wifi.setmode(wifi.STATION)
+ wifi.sta.config{
+ ssid = config.loaded.ssid,
+ pwd = config.loaded.psk,
+ save = false,
+ }
+ if config.loaded.hostname then
+ wifi.sta.sethostname(config.loaded.hostname)
+ end
+ tmr.alarm(0, 3600 * 1000, 1, clock.ntp_sync)
+ tmr.alarm(1, 1000, 1, clock.output)
+ httpd.init(httpd_process)
+ if button then button.init() end
+end
+
+return clock