Serial utils for lua
local sutil = {} | |
function sutil.getchar(ttyfile) | |
return ttyfile:read(1) | |
end | |
function sutil.readall_timeout(ttyfile, n, time) | |
local data = "" | |
local ret = true | |
local ctr = 0 | |
local start = os.time() | |
local timeout = false | |
while (ctr<n) do | |
local current = os.time() | |
if (current-start>time) then | |
print("Timeout [current: "..tostring(current).." start: "..tostring(start).." diff: "..tostring(current-start).."]") | |
timeout = true | |
break | |
end | |
local char = ttyfile:read(n-ctr) | |
if char ~= nil then | |
ctr=ctr+char:len() | |
-- print ("ret: "..tostring(ret).." char: "..tostring(char)) | |
data = data..char | |
end | |
end | |
return data, timeout | |
end | |
function sutil.set_line_params(dev, speed) | |
speed = tostring(speed) | |
os.execute("stty -F "..dev.." -echo cbreak ispeed "..speed.." ospeed "..speed.." min 0 time 3") | |
end | |
-- convert a 64-bit unsigned integer into a 8 bytes (network order) | |
function sutil.int64_to_bytes(n) | |
-- adjust for 2's complement | |
--n = (n < 0) and (4294967296 + n) or n | |
return string.char((math.modf(n/0x100000000000000))%256)..string.char((math.modf(n/0x1000000000000))%256)..string.char((math.modf(n/0x10000000000))%256)..string.char((math.modf(n/4294967296))%256)..string.char((math.modf(n/16777216))%256)..string.char((math.modf(n/65536))%256)..string.char((math.modf(n/256))%256)..string.char(n%256) | |
end | |
-- convert bytes (network order) to a 64-bit unsigned integer | |
function sutil.bytes_to_int64(s) | |
local n = string.byte(s, 1)*0x100000000000000 + string.byte(s, 2)*0x1000000000000 + string.byte(s, 3)*0x10000000000 + string.byte(s, 4)*0x100000000 + string.byte(s, 5)*0x1000000 + string.byte(s, 6)*0x10000 + string.byte(s, 7)*0x100 + string.byte(s, 8) | |
return n | |
end | |
-- convert a 64-bit two's complement integer into a 8 bytes (network order) | |
function sutil.int32_to_bytes(n) | |
-- adjust for 2's complement | |
--n = (n < 0) and (4294967296 + n) or n | |
return string.char((math.modf(n/16777216))%256)..string.char((math.modf(n/65536))%256)..string.char((math.modf(n/256))%256)..string.char(n%256) | |
end | |
-- convert bytes (network order) to a 64-bit two's complement integer | |
function sutil.bytes_to_int32(s) | |
local n = string.byte(s, 1)*0x1000000 + string.byte(s, 2)*0x10000 + string.byte(s, 3)*0x100 + string.byte(s, 4) | |
return n | |
end | |
function sutil.htonl(int_str) | |
return string.sub(int_str, 4, 4)..string.sub(int_str, 3, 3)..string.sub(int_str, 2, 2)..string.sub(int_str, 1, 1) | |
end | |
return sutil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment