Debian Codegraph @

serial_posix.go

raw symbols SCIP
1 // +build darwin linux freebsd openbsd netbsd
2
3 package serial
4
5 import (
6 "errors"
7 "fmt"
8 "log"
9 "os"
10 "syscall"
11 "time"
12 "unsafe"
13 )
14
15 // port implements Port interface.
16 type port struct {
17 fd int
18 oldTermios *syscall.Termios
19
20 timeout time.Duration
21 }
22
23 const (
24 rs485Enabled = 1 << 0
25 rs485RTSOnSend = 1 << 1
26 rs485RTSAfterSend = 1 << 2
27 rs485RXDuringTX = 1 << 4
28 rs485Tiocs = 0x542f
29 )
30
31 // rs485_ioctl_opts is used to configure RS485 options in the driver
32 type rs485_ioctl_opts struct {
33 flags uint32
34 delay_rts_before_send uint32
35 delay_rts_after_send uint32
36 padding [5]uint32
37 }
38
39 // New allocates and returns a new serial port controller.
40 func New() Port {
41 return &port{fd: -1}
42 }
43
44 // Open connects to the given serial port.
45 func (p *port) Open(c *Config) (err error) {
46 termios, err := newTermios(c)
47 if err != nil {
48 return
49 }
50 // See man termios(3).
51 // O_NOCTTY: no controlling terminal.
52 // O_NDELAY: no data carrier detect.
53 p.fd, err = syscall.Open(c.Address, syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_NDELAY|syscall.O_CLOEXEC, 0666)
54 if err != nil {
55 return
56 }
57 // Backup current termios to restore on closing.
58 p.backupTermios()
59 if err = p.setTermios(termios); err != nil {
60 // No need to restore termios
61 syscall.Close(p.fd)
62 p.fd = -1
63 p.oldTermios = nil
64 return err
65 }
66 if err = enableRS485(p.fd, &c.RS485); err != nil {
67 p.Close()
68 return err
69 }
70 p.timeout = c.Timeout
71 return
72 }
73
74 func (p *port) Close() (err error) {
75 if p.fd == -1 {
76 return
77 }
78 p.restoreTermios()
79 err = syscall.Close(p.fd)
80 p.fd = -1
81 p.oldTermios = nil
82 return
83 }
84
85 // Read reads from serial port. Port must be opened before calling this method.
86 // It is blocked until all data received or timeout after p.timeout.
87 func (p *port) Read(b []byte) (n int, err error) {
88 var rfds syscall.FdSet
89
90 fd := p.fd
91 fdset(fd, &rfds)
92
93 var tv *syscall.Timeval
94 if p.timeout > 0 {
95 timeout := syscall.NsecToTimeval(p.timeout.Nanoseconds())
96 tv = &timeout
97 }
98 for {
99 // If syscall.Select() returns EINTR (Interrupted system call), retry it
100 if err = syscallSelect(fd+1, &rfds, nil, nil, tv); err == nil {
101 break
102 }
103 if err != syscall.EINTR {
104 err = fmt.Errorf("serial: could not select: %v", err)
105 return
106 }
107 }
108 if !fdisset(fd, &rfds) {
109 // Timeout
110 err = ErrTimeout
111 return
112 }
113 n, err = syscall.Read(fd, b)
114 return
115 }
116
117 // Write writes data to the serial port.
118 func (p *port) Write(b []byte) (n int, err error) {
119 n, err = syscall.Write(p.fd, b)
120 return
121 }
122
123 func (p *port) setTermios(termios *syscall.Termios) (err error) {
124 if err = tcsetattr(p.fd, termios); err != nil {
125 err = fmt.Errorf("serial: could not set setting: %v", err)
126 }
127 return
128 }
129
130 // backupTermios saves current termios setting.
131 // Make sure that device file has been opened before calling this function.
132 func (p *port) backupTermios() {
133 oldTermios := &syscall.Termios{}
134 if err := tcgetattr(p.fd, oldTermios); err != nil {
135 // Warning only.
136 log.Printf("serial: could not get setting: %v\n", err)
137 return
138 }
139 // Will be reloaded when closing.
140 p.oldTermios = oldTermios
141 }
142
143 // restoreTermios restores backed up termios setting.
144 // Make sure that device file has been opened before calling this function.
145 func (p *port) restoreTermios() {
146 if p.oldTermios == nil {
147 return
148 }
149 if err := tcsetattr(p.fd, p.oldTermios); err != nil {
150 // Warning only.
151 log.Printf("serial: could not restore setting: %v\n", err)
152 return
153 }
154 p.oldTermios = nil
155 }
156
157 // Helpers for termios
158
159 func newTermios(c *Config) (termios *syscall.Termios, err error) {
160 termios = &syscall.Termios{}
161 flag := termios.Cflag
162 // Baud rate
163 if c.BaudRate == 0 {
164 // 19200 is the required default.
165 flag = syscall.B19200
166 } else {
167 var ok bool
168 flag, ok = baudRates[c.BaudRate]
169 if !ok {
170 err = fmt.Errorf("serial: unsupported baud rate %v", c.BaudRate)
171 return
172 }
173 }
174 termios.Cflag |= flag
175 // Input baud.
176 cfSetIspeed(termios, flag)
177 // Output baud.
178 cfSetOspeed(termios, flag)
179 // Character size.
180 if c.DataBits == 0 {
181 flag = syscall.CS8
182 } else {
183 var ok bool
184 flag, ok = charSizes[c.DataBits]
185 if !ok {
186 err = fmt.Errorf("serial: unsupported character size %v", c.DataBits)
187 return
188 }
189 }
190 termios.Cflag |= flag
191 // Stop bits
192 switch c.StopBits {
193 case 0, 1:
194 // Default is one stop bit.
195 // noop
196 case 2:
197 // CSTOPB: Set two stop bits.
198 termios.Cflag |= syscall.CSTOPB
199 default:
200 err = fmt.Errorf("serial: unsupported stop bits %v", c.StopBits)
201 return
202 }
203 switch c.Parity {
204 case "N":
205 // noop
206 case "O":
207 // PARODD: Parity is odd.
208 termios.Cflag |= syscall.PARODD
209 fallthrough
210 case "", "E":
211 // As mentioned in the modbus spec, the default parity mode must be Even parity
212 // PARENB: Enable parity generation on output.
213 termios.Cflag |= syscall.PARENB
214 // INPCK: Enable input parity checking.
215 termios.Iflag |= syscall.INPCK
216 default:
217 err = fmt.Errorf("serial: unsupported parity %v", c.Parity)
218 return
219 }
220 // Control modes.
221 // CREAD: Enable receiver.
222 // CLOCAL: Ignore control lines.
223 termios.Cflag |= syscall.CREAD | syscall.CLOCAL
224 // Special characters.
225 // VMIN: Minimum number of characters for noncanonical read.
226 // VTIME: Time in deciseconds for noncanonical read.
227 // Both are unused as NDELAY is we utilized when opening device.
228 return
229 }
230
231 // enableRS485 enables RS485 functionality of driver via an ioctl if the config says so
232 func enableRS485(fd int, config *RS485Config) error {
233 if !config.Enabled {
234 return nil
235 }
236 rs485 := rs485_ioctl_opts{
237 rs485Enabled,
238 uint32(config.DelayRtsBeforeSend / time.Millisecond),
239 uint32(config.DelayRtsAfterSend / time.Millisecond),
240 [5]uint32{0, 0, 0, 0, 0},
241 }
242
243 if config.RtsHighDuringSend {
244 rs485.flags |= rs485RTSOnSend
245 }
246 if config.RtsHighAfterSend {
247 rs485.flags |= rs485RTSAfterSend
248 }
249 if config.RxDuringTx {
250 rs485.flags |= rs485RXDuringTX
251 }
252
253 r, _, errno := syscall.Syscall(
254 syscall.SYS_IOCTL,
255 uintptr(fd),
256 uintptr(rs485Tiocs),
257 uintptr(unsafe.Pointer(&rs485)))
258 if errno != 0 {
259 return os.NewSyscallError("SYS_IOCTL (RS485)", errno)
260 }
261 if r != 0 {
262 return errors.New("serial: unknown error from SYS_IOCTL (RS485)")
263 }
264 return nil
265 }