-
Notifications
You must be signed in to change notification settings - Fork 2
/
serial.cc
401 lines (306 loc) · 9.93 KB
/
serial.cc
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
/*
* A library for working with DVSI's AMBE vocoder chips
*
* Copyright (C) 2019-2020 Internet Real-Time Lab, Columbia University
*
* This program is free 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, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#include "serial.h"
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/serial.h>
#include "api.h"
#include <iostream>
using namespace std::placeholders;
using namespace std;
using namespace ambe;
static bool lockFile(int fd) {
struct flock lock;
lock.l_type = F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0;
if (fcntl(fd, F_SETLK, &lock) == -1) {
if (errno == EACCES || errno == EAGAIN) return false;
throw system_error(errno, system_category());
}
return true;
}
static void setNonblocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) goto error;
flags |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) < 0) goto error;
return;
error:
throw system_error(errno, system_category());
}
/**
* Configure low-latency mode for a serial port
*
* Some USB-to-serial adapters such as FT232 add about 16 ms of delay to bytes
* coming from the serial port by default. This delay reduces the load on the
* USB subsystem and the host CPU. Linux provides a special ioctl that can be
* used to lower this delay. This function can be used to enable or disable a
* so-called low-latency mode. In low-latency mode, the delay added to incoming
* data is set to 1 ms instead of 16 ms.
*
* An FT232-based USB-to-serial adapter is built into all DVSI's USB-based
* devices.
*
* This function is Linux-specific.
*/
static void setLowLatency(int fd, bool yesno) {
struct serial_struct serial;
if (ioctl(fd, TIOCGSERIAL, &serial) < 0) goto error;
if (yesno) serial.flags |= ASYNC_LOW_LATENCY;
else serial.flags &= ~ASYNC_LOW_LATENCY;
if (ioctl(fd, TIOCSSERIAL, &serial) < 0) goto error;
return;
error:
cerr << "setLowLatency: " << strerror(errno) << endl;
throw system_error(errno, system_category());
}
static void initTTY(int fd, int baudrate) {
struct termios tty;
if (tcgetattr(fd, &tty) < 0) goto error;
if (cfsetspeed(&tty, (speed_t)baudrate) < 0) goto error;
// The following settings configure the terminal in raw (non-canonical) mode
tty.c_cflag |= (CLOCAL | CREAD); // Enable local mode (there is no modem)
tty.c_cflag &= ~CSIZE; // Clear character size related bits
tty.c_cflag |= CS8; // 8 bits per character
tty.c_cflag &= ~PARENB; // No parity bit
tty.c_cflag &= ~CSTOPB; // 1 stop bit
tty.c_cflag |= CRTSCTS; // Enable hardware flow control
tty.c_iflag &= ~(IGNBRK | BRKINT); // Flush queues on BREAK, do not generate SIGINT
tty.c_iflag &= ~(IGNPAR | PARMRK); // Output '\0' character for framing or parity errors
tty.c_iflag &= ~(INLCR | IGNCR | ICRNL); // No CR LF translation
tty.c_iflag &= ~(IXON | IXOFF); // disable XON/XOFF flow control
tty.c_oflag &= ~OPOST; // Disable any special output processing
tty.c_lflag &= ~ICANON; // Disable canonical mode
tty.c_lflag &= ~(ECHO | ECHONL); // Do not echo input characters
tty.c_lflag &= ~ISIG; // Do not generate signals
tty.c_lflag &= ~IEXTEN; // Disable any special input processing
// Fetch individual bytes as soon as they become available
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 0;
if (tcsetattr(fd, TCSANOW, &tty) != 0) goto error;
return;
error:
cerr << "initTTY: " << strerror(errno) << endl;
throw system_error(errno, system_category());
}
/**
* Make sure that all given data have been written to fd
*
* Invoke the write system call repeatedly until all data have been written to
* the given file descriptor or an unrecoverable error has been encountered.
*
* Returns the number of characters written. An error was encountered if the
* returned number is smaller than n.
*/
static size_t writeAll(int fd, const void* buffer, size_t n) {
size_t len;
ssize_t rc;
len = 0;
while(len < n) {
do {
rc = write(fd, (char*)buffer + len, n - len);
} while (rc < 0 && errno == EINTR);
if (rc <= 0) break;
len += rc;
}
return len;
}
static void flushBuffers(int fd) {
if (tcflush(fd, TCIOFLUSH) < 0) {
cerr << "tcflush: " << strerror(errno) << endl;
throw system_error(errno, system_category());
}
}
UartDevice::UartDevice(const string& pathname, int baudrate) : pathname(pathname) {
this->baudrate = baudrate;
recv = nullptr;
}
void UartDevice::start() {
int pipefd[2];
if (pipe(pipefd) > 0)
throw system_error(errno, system_category());
rpipe = pipefd[0];
wpipe = pipefd[1];
rfd = -1;
wfd = -1;
try {
cout << "Opening serial port " << pathname
<< " (baud rate " << baudrate << ")"
<< endl;
wfd = open(pathname.c_str(), O_RDWR | O_NOCTTY | O_SYNC);
if (wfd < 0) throw system_error(errno, system_category());
if (!lockFile(wfd)) {
cerr << "Error: Failed to lock serial port " << pathname
<< " (another process using it?)"
<< endl;
throw runtime_error("Failed to lock serial port");
}
initTTY(wfd, baudrate);
rfd = dup(wfd);
if (rfd < 0) throw system_error(errno, system_category());
setNonblocking(rfd);
// Enable low latency mode on the serial port (Linux only)
setLowLatency(rfd, true);
// Discard any data in the ports input and output buffer before starting
// reader/writer threads.
//
// The following wait time is a kludge needed to discard any data in
// input/output buffers of USB-to-serial adapters. Unfortunately, with
// USB-to-serial devices there is no bullet-proof way to implement the
// flushing.
//
// See: https://bugzilla.kernel.org/show_bug.cgi?id=5730
usleep(1000);
if (tcflush(wfd, TCIOFLUSH) < 0) {
cerr << "tcflush: " << strerror(errno) << endl;
throw system_error(errno, system_category());
}
receiver = thread(&UartDevice::packetReceiver, this);
} catch(...) {
close(rpipe);
close(wpipe);
if (rfd >= 0) {
try {
setLowLatency(rfd, false);
} catch(...) {}
close(rfd);
}
if (wfd >= 0) close(wfd);
throw;
}
}
void UartDevice::stop() {
if (write(wpipe, "Q", 1) <= 0)
cerr << "[" << pathname << "] Error while stopping packet receiver thread: " << strerror(errno) << endl;
receiver.join();
setLowLatency(rfd, false);
close(rfd);
close(wfd);
close(rpipe);
close(wpipe);
}
FifoCallback UartDevice::setCallback(FifoCallback recv) {
FifoCallback old = this->recv;
this->recv = recv;
return old;
}
void UartDevice::send(const string& packet) {
// If we fail to write the packet to the device for some reason,
// terminate the program. A failure to write a packet typically
// indicates a serious problem and it may take a device reset and
// full re-initialization to recover from it.
unsigned int len = packet.length();
if (writeAll(wfd, packet.c_str(), len) != len)
throw system_error(errno, system_category());
}
void UartDevice::packetReceiver(void) {
string buffer;
try {
while (readPacket(buffer)) {
if (recv) recv(buffer);
}
} catch(...) {
cout << "[" << pathname << "] Packet receiver thread terminated with an exception" << endl;
throw;
}
}
bool UartDevice::readPacket(string& buffer) {
Header *h;
// Read the packet incrementally. First, read the input byte by byte until
// we find a start byte. Then read the fixed-size header to obtain the total
// length of the packet. Finally, read the rest of the packet based on the
// length attribute in the header.
do {
buffer.clear();
if (!safeCancellableRead(buffer, 1)) return false;
h = (Header*)buffer.c_str();
} while(h->start_byte != START_BYTE);
if (!safeCancellableRead(buffer, sizeof(Header) - 1))
return false;
h = (Header*)buffer.c_str();
uint16_t len = h->getLength();
if (!safeCancellableRead(buffer, len)) return false;
return true;
}
bool UartDevice::safeCancellableRead(string& buffer, size_t n) {
size_t len;
ssize_t rc;
fd_set fds;
len = buffer.length();
buffer.resize(buffer.length() + n);
char* start = (char*)buffer.c_str() + len;
int maxfd = (rfd > rpipe ? rfd : rpipe) + 1;
FD_ZERO(&fds);
FD_SET(rfd, &fds);
FD_SET(rpipe, &fds);
len = 0;
while(len < n) {
do {
rc = select(maxfd, &fds, NULL, NULL, NULL);
} while (rc == -1 && errno == EINTR);
if (rc == -1)
throw system_error(errno, system_category());
// Main thread requesting termination
if (FD_ISSET(rpipe, &fds)) return false;
do {
rc = read(rfd, start + len, n - len);
} while (rc < 0 && errno == EINTR);
if (rc <= 0) {
if (errno == EWOULDBLOCK) continue;
return false;
}
len += rc;
}
return true;
}
Usb3003::Usb3003(const string& pathname) : UartDevice(pathname, 921600) {
}
int Usb3003::channels() const {
return 3;
}
void Usb3003::reset() {
flushBuffers(wfd);
// USB-3003 dongles support hardware reset of the AMBE chip. To reset the
// chip, we signal a break on the serial port. Upon reset, the chip will
// send an AMBE_READY packet. Hardware reset will only work on USB-3003.
// Other dongle variants don't seem to support it.
if (tcsendbreak(wfd, 0) < 0)
throw system_error(errno, system_category());
}
Usb3000::Usb3000(const string& pathname) : UartDevice(pathname, 460800) {
}
int Usb3000::channels() const {
return 1;
}