-
Notifications
You must be signed in to change notification settings - Fork 10
/
serial.c
706 lines (586 loc) · 16 KB
/
serial.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
/* -*- C -*-
* File: serial.c (~jb/serialport/serial.c)
* Author: Johan Bevemyr
* Created: Fri Oct 18 09:59:34 1996
* Purpose: Provide Erlang with access to the serial port.
*/
/* This program communicates through the following protocoll when
* run with -erlang:
*
* (all messages starts with a two byte header containing the
* size of the message)
*
* SEND DATA
* Transmits DATA on the currently open tty
*
* CONNECT
* Reopens a disconnected connection.
*
* DISCONNECT
* Hangs up an open serial line
*
* OPEN path
* Opens a new tty, closing the old (but not disconnecting). It
* is possible to alternate between two connections.
*
* SPEED inspeed outspeed
* Sets the input and output speeds. New connections will
* have these speeds. It is also possible to change speed
* on the fly.
*
* PARITY ODD/EVEN
* Sets the parity of the current connection.
*
* BREAK
* Sends break.
*
* usage: serial [-cbreak] [-erlang] [-speed <bit rate>] [-tty <dev>]
* bit rate is one of
* 50 75 110
* 134 150 200
* 300 600 1200
* 1800 2400 4800
* 9600 19200 38400
* 57600 76800 115200
* 153600 230400 307200
* 460800
*/
#include <stdlib.h>
#include <stdio.h>
#include <termios.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "serial.h"
int errno;
#define MAXSPEED 23
bit_rate bitrate_table[MAXSPEED] = {
{0 , B0 },
{50 , B50 },
{75 , B75 },
{110 , B110 },
{134 , B134 },
{150 , B150 },
{200 , B200 },
{300 , B300 },
{600 , B600 },
{1200 , B1200 },
{1800 , B1800 },
{2400 , B2400 },
{4800 , B4800 },
{9600 , B9600 },
{19200 , B19200 },
{38400 , B38400 },
{57600 , B57600 },
{76800 , B76800 },
{115200 , B115200 },
#ifndef __FreeBSD__
#ifndef __APPLE__
{153600 , B153600 },
#endif
#endif
{230400 , B230400 },
#ifndef __FreeBSD__
#ifndef __APPLE__
{307200 , B307200 },
{460800 , B460800 }
#endif
#endif
};
/**********************************************************************
* Name: get_speed
*
* Desc: Returns the speed_t value associated with a given bit_rate
* according to the bitrate_table. B0 is returned if no matching entry
* is found.
*/
speed_t get_speed(int speed)
{
int i;
for(i=0 ; i < MAXSPEED ; i++)
{
if (speed == bitrate_table[i].rate)
break;
}
if (i == MAXSPEED)
return B0;
else
return bitrate_table[i].speed;
}
/**********************************************************************
* Name: set_raw_tty_mode
*
* Desc: Configures the given tty for raw-mode.
*/
void set_raw_tty_mode(int fd)
{
struct termios ttymodes;
/* Get ttymodes */
if (tcgetattr(fd,&ttymodes) < 0)
{
perror("tcgetattr");
exit(1);
}
cfmakeraw(&ttymodes);
/* Configure for raw mode (see man termios) */
// ttymodes.c_cc[VMIN] = 1; /* at least one character */
// ttymodes.c_cc[VTIME] = 0; /* do not wait to fill buffer */
// ttymodes.c_iflag &= ~(ICRNL | /* disable CR-to-NL mapping */
// INLCR | /* disable NL-to-CR mapping */
// IGNCR | /* disable ignore CR */
// ISTRIP | /* disable stripping of eighth bit */
// IXON | /* disable output flow control */
// BRKINT | /* disable generate SIGINT on brk */
// IGNPAR |
// PARMRK |
// IGNBRK |
// INPCK); /* disable input parity detection */
// ttymodes.c_lflag &= ~(ICANON | /* enable non-canonical mode */
// ECHO | /* disable character echo */
// ECHOE | /* disable visual erase */
// ECHOK | /* disable echo newline after kill */
// ECHOKE | /* disable visual kill with bs-sp-bs */
// ECHONL | /* disable echo nl when echo off */
// ISIG | /* disable tty-generated signals */
// IEXTEN); /* disable extended input processing */
ttymodes.c_cflag |= CS8; /* enable eight bit chars */
ttymodes.c_cflag &= ~PARENB; /* disable input parity check */
// ttymodes.c_oflag &= ~OPOST; /* disable output processing */
/* roland */
ttymodes.c_cflag |= CLOCAL;
/* Apply changes */
if (tcsetattr(fd, TCSANOW, &ttymodes) < 0)
{
perror("tcsetattr");
exit(1);
}
}
/**********************************************************************
* Name: set_tty_speed
*
* Desc: set input and output speeds of a given connection.
*/
void set_tty_speed(int fd, speed_t new_ispeed, speed_t new_ospeed)
{
struct termios ttymodes;
/* Get ttymodes */
if (tcgetattr(fd,&ttymodes) < 0)
{
perror("tcgetattr");
exit(1);
}
if (cfsetispeed(&ttymodes,new_ispeed) < 0)
{
perror("cfsetispeed");
exit(1);
}
if (cfsetospeed(&ttymodes,new_ospeed) < 0)
{
perror("cfsetospeed");
exit(1);
}
/* Apply hanges */
if (tcsetattr(fd, TCSANOW, &ttymodes) < 0)
{
perror("tcsetattr");
exit(1);
}
}
/**********************************************************************
* Name: get_tbh_size
* Desc: returns the size of a two_byte_header message (from Erlang).
*/
int get_tbh_size(char buf[])
{
return (((int) buf[0]) << 8) + ((int) buf[1]);
}
/**********************************************************************
* Name: set_tbh_size
* Desc: sets the first two bytes of the buffer to its size
*/
void set_tbh_size(char buf[], int size)
{
buf[1] = (char) (size & 0xff);
buf[0] = (char) ((size >> 8) & 0xff);
return;
}
/**********************************************************************
* Name: tbh_write
* Desc: writes the buffer to a file descriptor, adding size info
* at the beginning.
*/
void tbh_write(int fd, char buf[], int buffsize)
{
char header_buf[TBHSIZE];
Debug1("tbh_write: send message of size %d\r\n", buffsize);
/* First, write two byte header */
set_tbh_size(header_buf, buffsize);
write(fd,header_buf,TBHSIZE);
/* Second, write original buffer */
write(fd,buf,buffsize);
return;
}
/**********************************************************************
* Name: tbh_read
* Desc: Reads one message with two-byte-header, filling buffer.
* Returns the number of elements used in the buffer, or 0
* if the input file has been closed.
*
*/
int tbh_read(int fd, char buf[], int buffsize)
{
int remaining, msgsize;
if (read_at_least(fd,buf,TBHSIZE) != TBHSIZE)
return 0;
remaining = get_tbh_size(buf);
Debug1("tbh_read: got message of size %d\r\n",remaining);
msgsize = read_at_least(fd, &buf[TBHSIZE],
Min(remaining,(buffsize-TBHSIZE)));
if (msgsize == 0)
return 0;
else
return msgsize + TBHSIZE;
}
/**********************************************************************
* Name: read_at_least(fd,buf,nr)
* Desc: Read at least nr bytes and put them into buf. Return the number
* of bytes read, i.e. nr.
* Returns: The number of bytes read, or 0 if stream closed.
*/
int read_at_least(int fd, char buf[], int nr)
{
int remaining = nr;
int nr_read = 0;
while(remaining > 0)
{
int read_this_time;
read_this_time = read(fd, &buf[nr_read], remaining);
if (read_this_time == 0) /* Input stream closed? */
return 0;
nr_read += read_this_time;
remaining -= read_this_time;
}
return nr_read;
}
/**********************************************************************
* Name: write_to_tty
* Desc: write a number of bytes found in the buffer to the tty,
* filling the buffer from the given fillfd if neccessary.
*
*/
void write_to_tty(int ttyfd, int fillfd, int totalsize, int buffsize,
char buf[], int buffmaxsize)
{
write(ttyfd,buf,buffsize);
totalsize -= buffsize;
while(totalsize > 0)
{
int readmax;
readmax = Min(totalsize,buffmaxsize);
buffsize = read(fillfd,buf,readmax);
write(ttyfd,buf,buffsize);
totalsize -= buffsize;
}
return;
}
/**********************************************************************/
main(int argc, char *argv[])
{
int ttyfd = -1; /* terminal file descriptor */
int stdinfd; /* user file descriptor */
int stdoutfd; /* user out file descriptor */
boolean cbreak=FALSE; /* cbreak flag */
boolean erlang=FALSE; /* talking to erlang flag */
speed_t in_speed=B9600; /* default in speed */
speed_t out_speed=B9600; /* default out speed */
char ttyname[MAXPATHLEN]; /* terminal name */
#ifdef __FreeBSD__ /* roland */
strcpy(ttyname,"/dev/cuaa1");
#else
strcpy(ttyname,"/dev/ttya");
#endif
/****************************************
* Process command line arguments
*/
{
int i;
for(i = 1 ; i < argc ; i++)
{
if (strcmp(argv[i],"-cbreak") == 0) /* -cbreak */
{
cbreak = TRUE;
}
else if (strcmp(argv[i],"-speed") == 0) /* -speed */
{
i += 1;
if (i < argc)
{
out_speed = in_speed = get_speed(atoi(argv[i]));
if (in_speed == B0)
goto error_usage;
}
else
goto error_usage;
}
else if (strcmp(argv[i],"-tty") == 0) /* -tty */
{
i += 1;
if (i < argc)
{
strncpy(ttyname,argv[i],MAXPATHLEN-1);
}
else
goto error_usage;
}
else if (strcmp(argv[i],"-erlang") == 0) /* -erlang */
{
erlang = TRUE;
}
else
goto error_usage;
}
}
/****************************************
* Configure serial port (tty)
*/
if (!erlang)
{
ttyfd = open(ttyname,O_RDWR|O_NOCTTY|O_NONBLOCK);
if (!TtyOpen(ttyfd))
{
fprintf(stderr,"Cannot open terminal %s for read and write\n",
ttyname);
exit(1);
}
ioctl(ttyfd, TIOCEXCL);
fcntl(ttyfd, F_SETFL, 0);
set_raw_tty_mode(ttyfd);
set_tty_speed(ttyfd,in_speed,out_speed);
}
/****************************************
* Configure user port
*/
stdinfd = fileno(stdin);
stdoutfd = fileno(stdout);
if (cbreak)
{
sigset_t sig, savesig;
/* Use non-cononical mode for input */
set_raw_tty_mode(stdinfd);
fprintf(stderr,"Entering non-canonical mode, exit with ---\n");
}
/****************************************
* Start processing loop
*/
{
fd_set readfds; /* file descriptor bit field for select */
int maxfd; /* max file descriptor for select */
char buf[MAXLENGTH]; /* buffer for transfer between serial-user */
int escapes; /* number of consecutive escapes in cbreak */
/* Set up initial bit field for select */
maxfd = Max(stdinfd,ttyfd);
FD_ZERO(&readfds);
/* no escapes encountered yet */
escapes = 0;
while (TRUE)
{
int i;
if(TtyOpen(stdinfd))
FD_SET(stdinfd, &readfds);
if(TtyOpen(ttyfd))
FD_SET(ttyfd, &readfds);
i = select(maxfd+1, &readfds, NULLFDS, NULLFDS, NULLTV);
if (i <= 0)
{
perror("select");
exit(1);
}
/******************************
* Data from TTY
*/
if (TtyOpen(ttyfd) &&
FD_ISSET(ttyfd,&readfds)) /* from serial port */
{
int nr_read;
Debug("receiving from TTY\r\n");
FD_CLR(ttyfd,&readfds);
nr_read = read(ttyfd,buf,MAXLENGTH);
if (nr_read <= 0)
{
fprintf(stderr,"problem reading from tty\n");
exit(1);
}
if (erlang)
tbh_write(stdoutfd,buf,nr_read);
else
write(stdoutfd,buf,nr_read);
}
/******************************
* Data from controlling process
*/
if (TtyOpen(stdinfd) &&
FD_ISSET(stdinfd,&readfds)) /* from user */
{
int nr_read;
int i;
FD_CLR(stdinfd,&readfds);
/********************
* check for escape in cbreak mode
*/
if (cbreak)
{
nr_read = read(stdinfd,buf,MAXLENGTH);
for(i=0 ; i<nr_read ; i++)
{
if(buf[i] == '-')
{
escapes++;
if(escapes == 3)
{
close(ttyfd);
exit(1);
}
}
else
{
escapes=0;
}
}
if (TtyOpen(ttyfd))
write(ttyfd,buf,nr_read);
}
/********************
* Erlang mode
*/
else if (erlang)
{
/* Messages from Erlang are structured as:
* Length:16
* PacketType:8
* DATA
*/
nr_read = tbh_read(stdinfd,buf,MAXLENGTH);
/* Check if stdin closed, i.e. controlling
* process terminated.
*/
if (nr_read == 0)
exit(1);
/* Interpret packets from Erlang
*/
switch(PacketType(buf))
{
case SEND: /******************************/
Debug("received SEND\r\n");
if (TtyOpen(ttyfd))
{
write_to_tty(ttyfd, stdinfd,
get_tbh_size(buf) - COMMANDSIZE,
nr_read - HEADERSIZE,
&(buf[HEADERSIZE]),
MAXLENGTH-HEADERSIZE);
}
Debug("finished SEND\n");
break;
case CONNECT: /******************************/
Debug("received CONNECT\r\n");
/* Reopen the current terminal */
goto open;
break;
case DISCONNECT: /******************************/
Debug("received DISCONNECT\r\n");
if (TtyOpen(ttyfd))
set_tty_speed(ttyfd,B0,B0);
goto close;
break;
case OPEN: /******************************/
Debug("received OPEN ");
/* Terminate string */
buf[nr_read] = (char) 0;
strcpy(ttyname,&buf[HEADERSIZE]);
open:
Debug1("opening %s \r\n",ttyname);
if (TtyOpen(ttyfd))
close(ttyfd);
ttyfd = open(ttyname,O_RDWR|O_NOCTTY|O_NONBLOCK);
maxfd = Max(stdinfd,ttyfd);
if (!TtyOpen(ttyfd))
{
fprintf(stderr,"Cannot open terminal %s for read ",
&buf[HEADERSIZE]);
fprintf(stderr,"and write\n");
exit(1);
}
ioctl(ttyfd, TIOCEXCL);
fcntl(ttyfd, F_SETFL, 0);
set_raw_tty_mode(ttyfd);
set_tty_speed(ttyfd,in_speed,out_speed);
Debug("Finished opening\n");
break;
case CLOSE: /******************************/
Debug("received CLOSE\r\n");
close:
if (TtyOpen(ttyfd))
close(ttyfd);
ttyfd = -1;
break;
case SPEED: /******************************/
{
int off;
in_speed = get_speed(atoi(&buf[HEADERSIZE]));
/* Null-terminate string */
buf[nr_read] = (char) 0;
/* Find start of second speed */
for(off=HEADERSIZE ;
isdigit(buf[off]) && (off < MAXLENGTH) ;
off += 1);
out_speed = get_speed(atoi(&buf[off]));
Debug1(" raw SPEED %s\r\n",&buf[HEADERSIZE]);
Debug2("received SPEED %d %d\r\n",in_speed,out_speed);
if(TtyOpen(ttyfd))
set_tty_speed(ttyfd, in_speed, out_speed);
break;
}
case PARITY_ODD: /******************************/
break;
case PARITY_EVEN:/******************************/
break;
case BREAK: /******************************/
if (TtyOpen(ttyfd))
(void) tcsendbreak(ttyfd,BREAKPERIOD);
break;
default:
fprintf(stderr,"%s: unknown command from Erlang\n",
argv[0]);
break;
}
}
else
{
nr_read = read(stdinfd,buf,MAXLENGTH);
write(ttyfd,buf,nr_read);
}
if (nr_read <= 0)
{
fprintf(stderr,"problem reading from stdin\n");
exit(0);
}
}
}
}
/****************************************
* Usage errors
*/
error_usage:
fprintf(stderr,"usage: %s [-cbreak] [-erlang] [-speed <bit rate>] [-tty <dev>]\n",argv[0]);
fprintf(stderr,"\tbit rate is one of \n\t\t50\t75\t110\n\t\t");
fprintf(stderr,"134\t150\t200\n\t\t300\t");
fprintf(stderr,"600\t1200\n\t\t1800\t2400\t4800\n\t\t");
fprintf(stderr,"9600\t19200\t38400\n\t\t57600\t");
fprintf(stderr,"76800\t115200\n\t\t153600\t230400\t");
fprintf(stderr,"307200\n\t\t460800\n");
exit(0);
}