forked from biomood/LuaSerial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathluaserialterm.lua
More file actions
executable file
·90 lines (72 loc) · 1.97 KB
/
luaserialterm.lua
File metadata and controls
executable file
·90 lines (72 loc) · 1.97 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/lua5.1
local serial = require("serial")
if arg[1] == "help" then
print('luaserialterm.lua "port-string"|"help" port-speed')
os.exit()
end
local serialport = arg[1] or "/dev/ttyUSB0"
-- connectspeed = 115200 -- ESP 19200 1284P forth
local connectspeed = arg[2] or 115200
local port_handle -- filedescriptor for the port used
local data_in = '' -- local global to ease passing around the read data
-- REPL trigger that says it is ready for input
local ready_prompt = "\n> "
local function port_open()
-- open connection to device
local msg
port_handle, msg = serial.open(serialport, connectspeed)
if port_handle == -1 then
error("Unable to open port - error: "..msg)
end
end
local function port_close()
-- close the connection
local c, msg = serial.close(port_handle)
if c < 0 then
error("Unable to close connection: "..msg)
end
end
local function port_TX(data)
-- send data to the opened port
local c, msg = serial.write(port_handle, data)
if c < 0 then
error("Unable to write: "..msg)
end
serial.usleep(100000)
end
local function port_RX()
-- read data from the opened port
data_in = ''
while true do
local c, msg = serial.readbytes(port_handle, 4096)
serial.usleep(10000)
if c < 0 then
error("Unable to read: "..msg)
elseif c > 0 then -- bytes have been read from the port
data_in = data_in .. msg
if (string.sub(data_in,-(#ready_prompt), -1) == ready_prompt) then
-- up to first "\n" is the echoed command
-- better way to fix?
local _, i = string.find(data_in, "\n")
data_in = string.sub(data_in, i+1, -1)
break
end
end
-- show progress for long wait
--io.write(". ")
end
end
port_open()
-- give controller time to spin up
serial.usleep(100000)
io.write("\nWelcome to LuaTerminal. <enter> to begin and '\\' to exit session.\n")
repeat
local data_out = io.read()
if data_out == '\\' then break
else port_TX(data_out.."\n")
end
serial.usleep(100000)
port_RX()
io.write(data_in)
until false
port_close()