-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinuxHandler.go
More file actions
444 lines (410 loc) · 9.53 KB
/
linuxHandler.go
File metadata and controls
444 lines (410 loc) · 9.53 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//go:build linux
package gxserial
// --------------------------------------------------------------------------
//
// Gurux Ltd
//
// Filename: $HeadURL$
//
// Version: $Revision$,
//
// $Date$
// $Author$
//
// # Copyright (c) Gurux Ltd
//
// ---------------------------------------------------------------------------
//
// DESCRIPTION
//
// This file is a part of Gurux Device Framework.
//
// Gurux Device Framework is Open Source software; you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; version 2 of the License.
// Gurux Device Framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// More information of Gurux products: https://www.gurux.org
//
// This code is licensed under the GNU General Public License v2.
// Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt
// ---------------------------------------------------------------------------
import (
"errors"
"fmt"
"os"
"path/filepath"
"github.com/Gurux/gxcommon-go"
"golang.org/x/sys/unix"
)
type port struct {
f *os.File
fd int
r *os.File
w *os.File
}
// toUnitBaudrate maps a baud rate to the corresponding constant in the unix package.
var toUnitBaudrate = map[int]uint32{
0: unix.B0,
50: unix.B50,
75: unix.B75,
110: unix.B110,
134: unix.B134,
150: unix.B150,
200: unix.B200,
300: unix.B300,
600: unix.B600,
1200: unix.B1200,
1800: unix.B1800,
2400: unix.B2400,
4800: unix.B4800,
9600: unix.B9600,
19200: unix.B19200,
38400: unix.B38400,
57600: unix.B57600,
115200: unix.B115200,
230400: unix.B230400,
460800: unix.B460800,
921600: unix.B921600,
}
func applyTermiosSpeed(t *unix.Termios, speed uint32) {
t.Cflag &^= unix.CBAUD
t.Cflag |= speed
t.Ispeed = speed
t.Ospeed = speed
}
func isInterruptedSyscall(err error) bool {
return errors.Is(err, unix.EINTR)
}
func (p *port) isOpen() bool {
return p.f != nil
}
// getPortNames returns a list of available serial port device paths on Linux.
func getPortNames() ([]string, error) {
patterns := []string{
"/dev/ttyS*",
"/dev/ttyUSB*",
"/dev/ttyXRUSB*",
"/dev/ttyACM*",
"/dev/ttyAMA*",
"/dev/rfcomm*",
"/dev/ttyAP*",
}
var devices []string
for _, pattern := range patterns {
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
for _, device := range matches {
name := filepath.Base(device)
sysPath := filepath.Join("/sys/class/tty", name, "device")
if _, err := os.Stat(sysPath); err == nil {
devices = append(devices, device)
}
}
}
return devices, nil
}
func openPort(cfg *GXSerial) error {
fd, err := unix.Open(cfg.Port, unix.O_RDWR|unix.O_NOCTTY|unix.O_NONBLOCK, 0666)
if err != nil {
return err
}
f := os.NewFile(uintptr(fd), cfg.Port)
cfg.s = port{f: f, fd: fd}
// (iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = tcgetattr
t, err := unix.IoctlGetTermios(fd, unix.TCGETS)
if err != nil {
cfg.s.close()
return err
}
t.Cflag |= unix.CLOCAL | unix.CREAD
t.Lflag &^= unix.ICANON | unix.ECHO | unix.ECHOE | unix.ECHOK | unix.ECHONL | unix.ISIG | unix.IEXTEN
t.Oflag &^= unix.OPOST | unix.ONLCR | unix.OCRNL
t.Iflag &^= unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IGNBRK
// Baud rate.
speed, ok := toUnitBaudrate[int(cfg.baudRate)]
if !ok || speed == unix.B0 {
cfg.s.close()
return fmt.Errorf("open failed. unsupported baud: %d", cfg.baudRate)
}
applyTermiosSpeed(t, speed)
// Databits:
t.Cflag &^= unix.CSIZE
switch cfg.dataBits {
case 5:
t.Cflag |= unix.CS5
case 6:
t.Cflag |= unix.CS6
case 7:
t.Cflag |= unix.CS7
case 8:
t.Cflag |= unix.CS8
default:
cfg.s.close()
return errors.New("invalid databits (must be 5..8)")
}
// Stop bits
switch cfg.stopBits {
case 1:
t.Cflag &^= unix.CSTOPB
case 2:
t.Cflag |= unix.CSTOPB
default:
cfg.s.close()
return errors.New("invalid stopbits (must be 1 or 2)")
}
// setup parity
t.Iflag &^= unix.INPCK | unix.ISTRIP
const CMSPAR = 0x40000000
hasCMSPAR := true
t.Cflag &^= unix.PARENB | unix.PARODD
if hasCMSPAR {
t.Cflag &^= CMSPAR
}
switch cfg.parity {
case gxcommon.ParityNone:
// No parity: parity bit off, no parity checking
case gxcommon.ParityEven:
t.Cflag |= unix.PARENB
t.Cflag &^= unix.PARODD
if hasCMSPAR {
t.Cflag &^= CMSPAR
}
case gxcommon.ParityOdd:
t.Cflag |= unix.PARENB | unix.PARODD
if hasCMSPAR {
t.Cflag &^= CMSPAR
}
case gxcommon.ParityMark:
if !hasCMSPAR {
cfg.s.close()
return errors.New("mark parity requested but CMSPAR not supported")
}
t.Cflag |= unix.PARENB | CMSPAR | unix.PARODD
case gxcommon.ParitySpace:
if !hasCMSPAR {
cfg.s.close()
return errors.New("space parity requested but CMSPAR not supported")
}
t.Cflag |= unix.PARENB | CMSPAR
t.Cflag &^= unix.PARODD
default:
cfg.s.close()
return errors.New("invalid parity")
}
t.Iflag &^= unix.IXON | unix.IXOFF
t.Cflag &^= unix.CRTSCTS
if err := unix.IoctlSetTermios(fd, unix.TCSETS, t); err != nil {
cfg.s.close()
return err
}
if err := unix.IoctlSetInt(fd, unix.TCFLSH, unix.TCIFLUSH); err != nil {
return err
}
cfg.s.r, cfg.s.w, err = os.Pipe()
if err != nil {
cfg.s.close()
return err
}
_ = unix.SetNonblock(int(cfg.s.r.Fd()), true)
return nil
}
func (p *port) close() error {
if p == nil {
return nil
}
if p.r != nil {
_ = p.r.Close()
}
if p.w != nil {
_ = p.w.Close()
}
if p.f != nil {
err := p.f.Close()
p.f = nil
p.fd = 0
return err
}
return nil
}
func (p *port) ensureOpen() error {
if p == nil || p.f == nil {
return errors.New("serial port not open")
}
return nil
}
func (p *port) getTermios() (*unix.Termios, error) {
if err := p.ensureOpen(); err != nil {
return nil, err
}
t, err := unix.IoctlGetTermios(p.fd, unix.TCGETS)
if err != nil {
return nil, fmt.Errorf("tcgetattr failed: %w", err)
}
return t, nil
}
func (p *port) setTermios(value *unix.Termios) error {
if err := p.ensureOpen(); err != nil {
return err
}
if err := unix.IoctlSetTermios(p.fd, unix.TCSETS, value); err != nil {
return fmt.Errorf("tcsetattr failed: %w", err)
}
return nil
}
func (p *port) setBaudRate(value gxcommon.BaudRate) error {
t, err := p.getTermios()
if err != nil {
return fmt.Errorf("setBaudRate failed. %w", err)
}
u, ok := toUnitBaudrate[int(value)]
if !ok || u == unix.B0 {
return fmt.Errorf("setBaudRate failed. unsupported baud: %d", value)
}
applyTermiosSpeed(t, u)
return p.setTermios(t)
}
func (p *port) setDataBits(value int) error {
t, err := p.getTermios()
if err != nil {
return fmt.Errorf("setDataBits failed. %w", err)
}
t.Cflag &^= unix.CSIZE
switch value {
case 5:
t.Cflag |= unix.CS5
case 6:
t.Cflag |= unix.CS6
case 7:
t.Cflag |= unix.CS7
case 8:
t.Cflag |= unix.CS8
default:
return fmt.Errorf("setDataBits failed. invalid databits: %d", value)
}
return p.setTermios(t)
}
func (p *port) setParity(value gxcommon.Parity) error {
t, err := p.getTermios()
if err != nil {
return fmt.Errorf("setParity failed. %w", err)
}
t.Cflag &^= unix.PARENB | unix.PARODD
switch value {
case gxcommon.ParityNone:
// nothing
case gxcommon.ParityEven:
t.Cflag |= unix.PARENB
case gxcommon.ParityOdd:
t.Cflag |= unix.PARENB | unix.PARODD
case gxcommon.ParityMark, gxcommon.ParitySpace:
return fmt.Errorf("mark/space parity not supported on this system")
}
return p.setTermios(t)
}
func (p *port) setStopBits(value gxcommon.StopBits) error {
t, err := p.getTermios()
if err != nil {
return fmt.Errorf("setStopBits failed. %w", err)
}
switch value {
case gxcommon.StopBitsOne:
t.Cflag &^= unix.CSTOPB
case gxcommon.StopBitsTwo:
t.Cflag |= unix.CSTOPB
default:
return fmt.Errorf("setStopBits failed. invalid value: %d (use StopBitsOne or StopBitsTwo)", value)
}
return p.setTermios(t)
}
func (p *port) getBytesToRead() (int, error) {
if err := p.ensureOpen(); err != nil {
return 0, err
}
n, err := unix.IoctlGetInt(p.fd, unix.TIOCINQ)
if err != nil {
return 0, fmt.Errorf("getBytesToRead failed: %w", err)
}
return n, nil
}
func (p *port) getBytesToWrite() (int, error) {
if err := p.ensureOpen(); err != nil {
return 0, err
}
n, err := unix.IoctlGetInt(p.fd, unix.TIOCOUTQ)
if err != nil {
return 0, fmt.Errorf("getBytesToWrite failed: %w", err)
}
return n, nil
}
func (p *port) read() ([]byte, error) {
if err := p.ensureOpen(); err != nil {
return nil, err
}
if p.r == nil {
return nil, errors.New("read not initialized: closedR is nil")
}
pfds := []unix.PollFd{
{Fd: int32(p.fd), Events: unix.POLLIN},
{Fd: int32(p.r.Fd()), Events: unix.POLLIN},
}
var err error
for {
_, err = unix.Poll(pfds, -1)
if err == nil {
break
}
if isInterruptedSyscall(err) {
continue
}
return nil, err
}
if (pfds[1].Revents & unix.POLLIN) != 0 {
return nil, nil
}
cnt, _ := p.getBytesToRead()
if cnt <= 0 {
cnt = 1
}
buf := make([]byte, cnt)
n := 0
for {
n, err = p.f.Read(buf)
if err == nil {
break
}
if isInterruptedSyscall(err) {
continue
}
return nil, err
}
cnt, _ = p.getBytesToRead()
if cnt != 0 {
ret, err := p.read()
if err != nil {
return nil, err
}
return append(buf[:n], ret...), nil
}
return buf[:n], nil
}
func (p *port) write(data []byte) (int, error) {
if err := p.ensureOpen(); err != nil {
return 0, err
}
for {
n, err := p.f.Write(data)
if err == nil {
return n, nil
}
if isInterruptedSyscall(err) {
continue
}
return n, err
}
}