Last active
August 29, 2015 14:01
-
-
Save fab13n/25ac23c01a03e4a656fa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sched' | |
require 'web.server' | |
require 'web.template' | |
require 'serial' | |
telnet = require 'shell.telnet' | |
uart = serial.open('/dev/ttyAMA0', { baudrate=19200 }) | |
-- Read enough data from the UART to extract two consecutive frames. | |
function get_raw_data() | |
return uart:read(400) | |
end | |
-- Return the checksum of the frame between chars #a and #b included. | |
function frame_checksum(frame, a, b) | |
local bytes = { frame:byte(a,b) } | |
local sum = 0 | |
for i=1,#bytes do sum=sum+bytes[i] end | |
return sum%256 | |
end | |
-- Extracts and verifies two consecutive BMV frames from serial data. | |
function get_frames() | |
local REGEXP = '\13\10Checksum\t.()' | |
local raw_data = get_raw_data() | |
local checksums = { } | |
-- find 3 consecutive checksum lines in `raw_data` | |
local last_position = 1 | |
for i=1,3 do | |
local next_position = string.match(raw_data, REGEXP, last_position) | |
checksums[i] = next_position | |
last_position = next_position | |
end | |
assert(frame_checksum(raw_data, checksums[1], checksums[2]-1)==0) | |
assert(frame_checksum(raw_data, checksums[2], checksums[3]-1)==0) | |
return raw_data :sub (checksums[1], checksums[3]-1) | |
end | |
-- Converts a pair of frames into a Lua record. | |
function get_record() | |
local frame = get_frames() | |
local record = { } | |
for line in frame :gmatch "[^\10\13]+" do | |
local label, value = line :match '(..-)\t(.+)' | |
if label~='Checksum' then | |
record[label] = value | |
end | |
end | |
return record | |
end | |
-- Serves it as a very crude web page. | |
web.site[''] = web.template 'default' { | |
title = [[Data Monitoring: Elorn's batteries]], | |
body = [[ | |
<table> | |
<% for label, value in pairs(get_record()) do %> | |
<tr> | |
<th><%=label%></th> | |
<td><%=value%></td> | |
</tr> | |
<% end %> | |
</table> | |
<p><a href=''>Refresh</a></p> | |
]]} | |
function main() | |
telnet.init{ address='0.0.0.0', port=3000, editmode='edit', historysize=64 } | |
web.start(9000) | |
end | |
-- Launch the main Lua thread. | |
sched.run(main) | |
sched.loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment