01.10.2025, 12:08
Create a scheduled script that runs once per day during the night when there are no other scheduled scripts or tasks.
The supplied time is in UTC so make sure that LM has correct timezone set for the automatic conversion to work.
For testing purposes you can comment out os.sleep. It is needed so the script is not triggered again if the time is shifted.
The supplied time is in UTC so make sure that LM has correct timezone set for the automatic conversion to work.
For testing purposes you can comment out os.sleep. It is needed so the script is not triggered again if the time is shifted.
Code:
os.sleep(30)
require('serial')
port = serial.open('/dev/ttyACM0')
if not port then
log('port not found')
return
end
port:flush()
function settime(line)
local parts = line:split(',')
if parts[1] ~= '$GPRMC' then
return
end
local hour, min, sec = string.match(parts[2] or '', '^(%d%d)(%d%d)(%d%d)%.')
local day, month, year = string.match(parts[10] or '', '^(%d%d)(%d%d)(%d%d)$')
if not hour or not day then
return
end
local cmd = string.format('date -u -s "20%s-%s-%s %s:%s:%s"; hwclock -w',
year, month, day, hour, min, sec)
os.execute(cmd)
return true
end
buf = {}
lines = 0
while true do
char = port:read(1, 1)
if char then
if char == '\r' or char == '\n' then
if #buf > 0 then
line = table.concat(buf)
lines = lines + 1
if settime(line) then
log('time updated')
break
elseif lines > 20 then
log('could not update time')
break
end
buf = {}
end
else
buf[ #buf + 1 ] = char
end
end
end