-
Notifications
You must be signed in to change notification settings - Fork 314
/
Copy pathserial_port.c
451 lines (337 loc) · 10.5 KB
/
serial_port.c
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
445
446
447
448
449
450
451
// TODO: Needs more clean up and testing of error conditions.
// TODO: use this in place of other similar code.
//
// This file is part of Dire Wolf, an amateur radio packet TNC.
//
// Copyright (C) 2014, 2015 John Langner, WB2OSZ
//
// 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 2 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 <http://www.gnu.org/licenses/>.
//
//#define DEBUG 1
/*------------------------------------------------------------------
*
* Module: serial.c
*
* Purpose: Interface to serial port, hiding operating system differences.
*
*---------------------------------------------------------------*/
#include <stdio.h>
#if __WIN32__
#include <stdlib.h>
#include <windows.h>
#else
#define __USE_XOPEN2KXSI 1
#define __USE_XOPEN 1
#include <stdlib.h>
#include <ctype.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/errno.h>
#endif
#include <assert.h>
#include <string.h>
#include "direwolf.h"
#include "textcolor.h"
#include "serial_port.h"
/*-------------------------------------------------------------------
*
* Name: serial_port_open
*
* Purpose: Open serial port.
*
* Inputs: devicename - For Windows, usually like COM5.
* For Linux, usually /dev/tty...
* "COMn" also allowed and converted to /dev/ttyS(n-1)
*
* baud - Speed. 4800, 9600, etc.
*
* Returns Handle for serial port or MYFDERROR for error.
*
*---------------------------------------------------------------*/
MYFDTYPE serial_port_open (char *devicename, int baud)
{
#if __WIN32__
MYFDTYPE fd;
DCB dcb;
int ok;
char bettername[50];
#if DEBUG
text_color_set(DW_COLOR_DEBUG);
dw_printf ("serial_port_open ( '%s', %d )\n", devicename, baud);
#endif
// Reference: http://www.robbayer.com/files/serial-win.pdf
// Need to use FILE_FLAG_OVERLAPPED for full duplex operation.
// Without it, write blocks when waiting on read.
// Read http://support.microsoft.com/kb/156932
// Bug fix in release 1.1 - Need to munge name for COM10 and up.
// http://support.microsoft.com/kb/115831
strlcpy (bettername, devicename, sizeof(bettername));
if (strncasecmp(devicename, "COM", 3) == 0) {
int n;
n = atoi(devicename+3);
if (n >= 10) {
strlcpy (bettername, "\\\\.\\", sizeof(bettername));
strlcat (bettername, devicename, sizeof(bettername));
}
}
fd = CreateFile(bettername, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
if (fd == MYFDERROR) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("ERROR - Could not open serial port %s.\n", devicename);
return (MYFDERROR);
}
/* Reference: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363201(v=vs.85).aspx */
memset (&dcb, 0, sizeof(dcb));
dcb.DCBlength = sizeof(DCB);
ok = GetCommState (fd, &dcb);
if (! ok) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("serial_port_open: GetCommState failed.\n");
}
/* http://msdn.microsoft.com/en-us/library/windows/desktop/aa363214(v=vs.85).aspx */
dcb.DCBlength = sizeof(DCB);
switch (baud) {
case 1200: dcb.BaudRate = CBR_1200; break;
case 2400: dcb.BaudRate = CBR_2400; break;
case 4800: dcb.BaudRate = CBR_4800; break;
case 9600: dcb.BaudRate = CBR_9600; break;
case 19200: dcb.BaudRate = CBR_19200; break;
case 38400: dcb.BaudRate = CBR_38400; break;
case 57600: dcb.BaudRate = CBR_57600; break;
case 115200: dcb.BaudRate = CBR_115200; break;
default: text_color_set(DW_COLOR_ERROR);
dw_printf ("serial_port_open: Unsupported speed %d. Using 4800.\n", baud);
dcb.BaudRate = CBR_4800;
break;
}
dcb.fBinary = 1;
dcb.fParity = 0;
dcb.fOutxCtsFlow = 0;
dcb.fOutxDsrFlow = 0;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = 0;
dcb.fOutX = 0;
dcb.fInX = 0;
dcb.fErrorChar = 0;
dcb.fNull = 0; /* Don't drop nul characters! */
dcb.fRtsControl = 0;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
ok = SetCommState (fd, &dcb);
if (! ok) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("serial_port_open: SetCommState failed.\n");
}
//text_color_set(DW_COLOR_INFO);
//dw_printf("Successful serial port open on %s.\n", devicename);
#else
/* Linux version. */
int fd;
struct termios ts;
int e;
char linuxname[50];
#if DEBUG
text_color_set(DW_COLOR_DEBUG);
dw_printf ("serial_port_open ( '%s' )\n", devicename);
#endif
/* Translate Windows device name into Linux name. */
/* COM1 -> /dev/ttyS0, etc. */
strlcpy (linuxname, devicename, sizeof(linuxname));
if (strncasecmp(devicename, "COM", 3) == 0) {
int n = atoi (devicename + 3);
text_color_set(DW_COLOR_INFO);
dw_printf ("Converted serial port name '%s'", devicename);
if (n < 1) n = 1;
snprintf (linuxname, sizeof(linuxname), "/dev/ttyS%d", n-1);
dw_printf (" to Linux equivalent '%s'\n", linuxname);
}
fd = open (linuxname, O_RDWR);
if (fd == MYFDERROR) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("ERROR - Could not open serial port %s.\n", linuxname);
return (MYFDERROR);
}
e = tcgetattr (fd, &ts);
if (e != 0) { perror ("tcgetattr"); }
cfmakeraw (&ts);
ts.c_cc[VMIN] = 1; /* wait for at least one character */
ts.c_cc[VTIME] = 0; /* no fancy timing. */
switch (baud) {
case 1200: cfsetispeed (&ts, B1200); cfsetospeed (&ts, B1200); break;
case 2400: cfsetispeed (&ts, B2400); cfsetospeed (&ts, B2400); break;
case 4800: cfsetispeed (&ts, B4800); cfsetospeed (&ts, B4800); break;
case 9600: cfsetispeed (&ts, B9600); cfsetospeed (&ts, B9600); break;
case 19200: cfsetispeed (&ts, B19200); cfsetospeed (&ts, B19200); break;
case 38400: cfsetispeed (&ts, B38400); cfsetospeed (&ts, B38400); break;
case 57600: cfsetispeed (&ts, B57600); cfsetospeed (&ts, B57600); break;
case 115200: cfsetispeed (&ts, B115200); cfsetospeed (&ts, B115200); break;
default: text_color_set(DW_COLOR_ERROR);
dw_printf ("serial_port_open: Unsupported speed %d. Using 4800.\n", baud);
cfsetispeed (&ts, B4800); cfsetospeed (&ts, B4800);
break;
}
e = tcsetattr (fd, TCSANOW, &ts);
if (e != 0) { perror ("tcsetattr"); }
//text_color_set(DW_COLOR_INFO);
//dw_printf("Successfully opened serial port %s.\n", devicename);
#endif
return (fd);
}
/*-------------------------------------------------------------------
*
* Name: serial_port_write
*
* Purpose: Send characters to serial port.
*
* Inputs: fd - Handle from open.
* str - Pointer to array of bytes.
* len - Number of bytes to write.
*
* Returns Number of bytes written. Should be the same as len.
* -1 if error.
*
*---------------------------------------------------------------*/
int serial_port_write (MYFDTYPE fd, char *str, int len)
{
if (fd == MYFDERROR) {
return (-1);
}
#if __WIN32__
DWORD nwritten;
/* Without this, write blocks while we are waiting on a read. */
static OVERLAPPED ov_wr;
memset (&ov_wr, 0, sizeof(ov_wr));
if ( ! WriteFile (fd, str, len, &nwritten, &ov_wr))
{
int err = GetLastError();
if (err != ERROR_IO_PENDING)
{
text_color_set(DW_COLOR_ERROR);
dw_printf ("Error writing to serial port. Error %d.\n\n", err);
}
}
else if (nwritten != len)
{
text_color_set(DW_COLOR_ERROR);
dw_printf ("Error writing to serial port. Only %d of %d written.\n\n", (int)nwritten, len);
}
return (nwritten);
#else
int written;
written = write (fd, str, (size_t)len);
if (written != len)
{
text_color_set(DW_COLOR_ERROR);
dw_printf ("Error writing to serial port. err=%d\n\n", written);
return (-1);
}
return (written);
#endif
} /* serial_port_write */
/*-------------------------------------------------------------------
*
* Name: serial_port_get1
*
* Purpose: Get one byte from the serial port. Wait if not ready.
*
* Inputs: fd - Handle from open.
*
* Returns: Value of byte in range of 0 to 255.
* -1 if error.
*
*--------------------------------------------------------------------*/
int serial_port_get1 (MYFDTYPE fd)
{
unsigned char ch;
#if __WIN32__ /* Native Windows version. */
DWORD n;
static OVERLAPPED ov_rd;
memset (&ov_rd, 0, sizeof(ov_rd));
ov_rd.hEvent = CreateEvent (NULL, TRUE, FALSE, NULL);
/* Overlapped I/O makes reading rather complicated. */
/* See: http://msdn.microsoft.com/en-us/library/ms810467.aspx */
/* It seems that the read completes OK with a count */
/* of 0 every time we send a message to the serial port. */
n = 0; /* Number of characters read. */
while (n == 0) {
if ( ! ReadFile (fd, &ch, 1, &n, &ov_rd))
{
int err1 = GetLastError();
if (err1 == ERROR_IO_PENDING)
{
/* Wait for completion. */
if (WaitForSingleObject (ov_rd.hEvent, INFINITE) == WAIT_OBJECT_0)
{
if ( ! GetOverlappedResult (fd, &ov_rd, &n, 1))
{
int err3 = GetLastError();
text_color_set(DW_COLOR_ERROR);
dw_printf ("Serial Port GetOverlappedResult error %d.\n\n", err3);
}
else
{
/* Success! n should be 1 */
}
}
}
else
{
text_color_set(DW_COLOR_ERROR);
dw_printf ("Serial port read error %d.\n", err1);
return (-1);
}
}
} /* end while n==0 */
CloseHandle(ov_rd.hEvent);
if (n != 1) {
text_color_set(DW_COLOR_ERROR);
dw_printf ("Serial port failed to get one byte. n=%d.\n\n", (int)n);
}
#else /* Linux version */
int n;
n = read(fd, &ch, (size_t)1);
if (n != 1) {
text_color_set(DW_COLOR_DEBUG);
dw_printf ("serial_port_get1(%d) returns -1 for error.\n", fd);
return (-1);
}
#endif
#if DEBUGx
text_color_set(DW_COLOR_DEBUG);
if (isprint(ch)) {
dw_printf ("serial_port_get1(%d) returns 0x%02x = '%c'\n", fd, ch, ch);
}
else {
dw_printf ("serial_port_get1(%d) returns 0x%02x\n", fd, ch);
}
#endif
return (ch);
}
/*-------------------------------------------------------------------
*
* Name: serial_port_close
*
* Purpose: Close the device.
*
* Inputs: fd - Handle from open.
*
* Returns: None.
*
*--------------------------------------------------------------------*/
// TODO:
/* end serial_port.c */