File: termios.lua

package info (click to toggle)
lua-posix 31-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,604 kB
  • ctags: 1,346
  • sloc: sh: 14,309; ansic: 4,794; perl: 76; makefile: 41
file content (67 lines) | stat: -rw-r--r-- 1,338 bytes parent folder | download | duplicates (3)
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
local p = require "posix"
local dev = arg[1] or "/dev/ttyUSB0"

-- Open serial port and do settings

local fds, err = p.open(dev, p.O_RDWR + p.O_NONBLOCK);
if not fds then
	print("Could not open serial port " .. dev .. ":", err)
	os.exit(1)
end

p.tcsetattr(fds, 0, {
	cflag = p.B115200 + p.CS8 + p.CLOCAL + p.CREAD,
	iflag = p.IGNPAR,
	oflag = p.OPOST,
	cc = {
		[p.VTIME] = 0,
		[p.VMIN] = 1
	}
})

-- Set stdin to non canonical mode. Save current settings

local save = p.tcgetattr(0)
p.tcsetattr(0, 0, {
	cc = {
		[p.VTIME] = 0,
		[p.VMIN] = 1
	}
})

-- Loop, reading and writing between ports. ^C stops

local set = {
	[0] = { events = { IN = true } },
	[fds] = { events = { IN = true } },
}

p.write(1, "Starting terminal, hit ^C to exit\r\n")

local function exit(msg)
	p.tcsetattr(0, 0, save)
	print("\n")
	print(msg)
	os.exit(0)
end

while true do
	local r = p.poll(set, -1)
	for fd, d in pairs(set) do
		if d.revents and d.revents.IN then
			if fd == 0 then
				local d, err = p.read(0, 1024)
				if not d then exit(err) end
				if d == string.char(3) then exit("Bye") end
				local ok, err = p.write(fds, d)
				if not ok then exit(err) end
			end
			if fd == fds then
				local d, err = p.read(fds, 1024)
				if not d then exit(err) end
				local ok, err = p.write(1, d)
				if not ok then exit(err) end
			end
		end
	end
end