2 * Simple serial terminal
4 * Copyright 2014, 2015, 2016, 2017, 2019, 2020 Michal Sojka <sojkam1@fel.cvut.cz>
6 * This program is free software: you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see
18 * <http://www.gnu.org/licenses/>.
22 * This is a minimalist terminal program like minicom or cu. The only
23 * thing it does is creating a bidirectional connection between
24 * stdin/stdout and a device (e.g. serial terminal). It can also set
25 * serial line baudrate and manipulate DTR/RTS modem lines.
27 * The -d and -r option create short pulse on DTR/RTS. The lines are
28 * always raised when the device is opened and those options lower the
29 * lines immediately after opening.
33 #define _DEFAULT_SOURCE
35 #include <sys/ioctl.h>
36 #include <sys/types.h>
55 #define STRINGIFY(val) #val
56 #define TOSTRING(val) STRINGIFY(val)
57 #define CHECK(cmd) ({ int ret = (cmd); if (ret == -1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ret; })
58 #define CHECKPTR(cmd) ({ void *ptr = (cmd); if (ptr == (void*)-1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
59 #define CHECKNULL(cmd) ({ void *ptr = (cmd); if (ptr == NULL) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
61 #define VERBOSE(format, ...) do { if (verbose) fprintf(stderr, "sterm: " format, ##__VA_ARGS__); } while (0)
63 #define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
66 bool exit_on_escape = true;
68 struct termios stdin_tio_backup;
71 void rm_file(int status, void *arg)
79 void restore_stdin_term()
81 tcsetattr(0, TCSANOW, &stdin_tio_backup);
87 dev_unlock(dev, getpid());
91 void sighandler(int arg)
93 exit(0); /* Invoke exit handlers */
96 int dtr_rts_arg(const char option, const char *optarg)
102 val = strtol(optarg, &end, 10);
106 case '+': val = +1; break;
107 case '-': val = -1; break;
109 fprintf(stderr, "Unknown -%c argument: %s\n", option, optarg);
117 // See DSR and CPR at
118 // https://en.wikipedia.org/wiki/ANSI_escape_code#Terminal_output_sequences
119 bool is_cpr_control_seq(char c)
121 static enum state { CSI_ESC, CSI_BRACKET, PAR_N, PAR_M, FIN_R } state;
124 case CSI_ESC: state = (c == 0x1b) ? CSI_BRACKET : CSI_ESC; break;
125 case CSI_BRACKET: state = (c == '[') ? PAR_N : CSI_ESC; break;
126 case PAR_N: state = (c == ';') ? PAR_M : (c >= '0' && c <= '9' ? PAR_N : CSI_ESC); break;
127 case PAR_M: state = (c == 'R') ? FIN_R : (c >= '0' && c <= '9' ? PAR_M : CSI_ESC); break;
130 if (state == FIN_R) {
135 return state != CSI_ESC;
138 void exit_on_escapeseq(const char *buf, int len)
140 static const char escseq[] = "\r~.";
141 static const char *state = escseq+1;
143 for (i = 0; i < len; i++) {
144 if (is_cpr_control_seq(buf[i]))
146 if (buf[i] == *state) {
152 if (buf[i] == *state)
158 void usage(const char* argv0)
160 fprintf(stderr, "Usage: %s [options] <device>\n", argv0);
163 " -b <duration> send break signal\n"
164 " -c enter command mode\n"
165 " -d[PULSE] make pulse on DTR\n"
166 " -e ignore '~.' escape sequence\n"
167 " -n do not switch stdin TTY to raw mode\n"
168 " -r[PULSE] make pulse on RTS\n"
170 " -t <ms> minimum delay between two transmitted characters\n"
173 "PULSE is a number specifying the pulse. Absolute value defines the\n"
174 "length of the pulse in milliseconds, sign determines the polarity of\n"
175 "the pulse. Alternatively, PULSE can be either '+' or '-', which\n"
176 "corresponds to +1 or -1.\n"
180 void pulse(int fd, int dtr, int rts)
183 /* tio.c_cflag &= ~HUPCL; */ /* Don't lower DTR/RTS on close */
185 CHECK(ioctl(fd, TIOCMGET, &status));
186 if (dtr > 0) { status &= ~TIOCM_DTR; ms = +dtr; }
187 if (dtr < 0) { status |= TIOCM_DTR; ms = -dtr; }
188 if (rts > 0) { status &= ~TIOCM_RTS; ms = +rts; }
189 if (rts < 0) { status |= TIOCM_RTS; ms = -rts; }
190 CHECK(ioctl(fd, TIOCMSET, &status));
194 if (dtr < 0) { status &= ~TIOCM_DTR; }
195 if (dtr > 0) { status |= TIOCM_DTR; }
196 if (rts < 0) { status &= ~TIOCM_RTS; }
197 if (rts > 0) { status |= TIOCM_RTS; }
198 CHECK(ioctl(fd, TIOCMSET, &status));
201 void handle_commands(int fd)
209 if (fgets(command, sizeof(command), stdin) == NULL) {
211 perror("Command read");
214 if (sscanf(command, "dtr %ms", &p1) == 1)
215 pulse(fd, dtr_rts_arg('d', p1), 0);
216 else if (sscanf(command, "rts %ms", &p1) == 1)
217 pulse(fd, 0, dtr_rts_arg('r', p1));
218 else if (sscanf(command, "break %d", &num) == 1)
219 CHECK(tcsendbreak(fd, num));
220 else if (strcmp(command, "go\n") == 0)
222 else if (strcmp(command, "exit\n") == 0)
225 fprintf(stderr, "Unknown command: %s\n", command);
233 static int64_t now_us()
236 CHECK(clock_gettime(CLOCK_MONOTONIC, &ts));
237 return ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
240 int main(int argc, char *argv[])
245 int dtr = 0, rts = 0;
253 if ((stdin_tty = isatty(0))) {
254 CHECK(tcgetattr(0, &stdin_tio_backup));
255 atexit(restore_stdin_term);
258 while ((opt = getopt(argc, argv, "b:cnd::er::s:vt:")) != -1) {
260 case 'b': break_dur = atoi(optarg); break;
261 case 'c': cmd = true; break;
262 case 'd': dtr = dtr_rts_arg(opt, optarg); break;
263 case 'e': exit_on_escape = false; break;
264 case 'n': raw = false; break;
265 case 'r': rts = dtr_rts_arg(opt, optarg); break;
267 int s = atoi(optarg);
269 #define S(s) case s: speed = B##s; break;
303 fprintf(stderr, "Unknown baud rate %d\n", s);
309 tx_delay_ms = atoi(optarg);
324 fprintf(stderr, "No device specified\n");
329 signal(SIGINT, sighandler);
330 signal(SIGTERM, sighandler);
331 signal(SIGHUP, sighandler);
334 pid_t pid = dev_lock(dev);
336 fprintf(stderr, "%s is used by PID %d\n", dev, pid);
338 } else if (pid < 0) {
340 asprintf(&msg, "dev_lock('%s')", dev); /* No free() because we exit() immediately */
344 fprintf(stderr, "%s: Error\n", msg);
350 /* O_NONBLOCK is needed to not wait for the CDC signal. See tty_ioctl(4). */
351 if ((fd = open(dev, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) {
355 /* Cancel the efect of O_NONBLOCK flag. */
356 int n = fcntl(fd, F_GETFL, 0);
357 fcntl(fd, F_SETFL, n & ~O_NDELAY);
362 CHECK(ioctl(fd, TIOCEXCL, NULL));
364 CHECK(tcgetattr(fd, &tio));
369 CHECK(cfsetospeed(&tio, speed));
370 CHECK(cfsetispeed(&tio, speed));
377 CHECK(tcsendbreak(fd, break_dur));
379 /* Disable flow control */
380 tio.c_cflag &= ~(CRTSCTS);
381 tio.c_iflag &= ~(IXON|IXOFF);
383 CHECK(tcsetattr(fd, TCSANOW, &tio));
384 } else if (speed || dtr || rts) {
385 fprintf(stderr, "Cannot set speed, DTR or RTS on non-terminal %s\n", dev);
389 VERBOSE("Connected.\r\n");
396 struct pollfd fds[2] = {
397 [STDIN] = { .fd = STDIN_FILENO, .events = POLLIN },
398 [DEV] = { .fd = fd, .events = POLLIN },
402 tio = stdin_tio_backup;
405 CHECK(tcsetattr(0, TCSANOW, &tio));
409 VERBOSE("Use '<Enter>~.' sequence to exit.\r\n");
412 int buf_len = 0, buf_idx = 0;
413 int64_t last_tx_us = 0;
415 int timeout = (tx_delay_ms == 0 || buf_len == 0)
417 : MAX(0, tx_delay_ms - (now_us() - last_tx_us) / 1000);
419 CHECK(poll(fds, 2, timeout));
420 if (fds[STDIN].revents & POLLIN && buf_len == 0) {
421 buf_len = CHECK(read(STDIN_FILENO, buf2dev, sizeof(buf2dev)));
423 VERBOSE("EOF on stdin\r\n");
428 exit_on_escapeseq(buf2dev, buf_len);
432 bool short_write = false;
433 if (tx_delay_ms == 0) {
434 wlen = CHECK(write(fd, buf2dev, buf_len));
435 short_write = wlen != buf_len;
438 int64_t now = now_us();
439 if (now - last_tx_us >= tx_delay_ms * 1000) {
440 wlen = CHECK(write(fd, &buf2dev[buf_idx], 1));
441 short_write = wlen != 1;
446 fprintf(stderr, "Not all data written to %s (%d/%d)\n", dev, buf_len, wlen);
450 if (buf_idx >= buf_len)
453 if (fds[STDIN].revents & POLLHUP) {
454 VERBOSE("HUP on stdin\r\n");
457 if (fds[DEV].revents & POLLIN) {
460 rlen = CHECK(read(fd, buf, sizeof(buf)));
462 VERBOSE("EOF on %s\r\n", dev);
465 wlen = CHECK(write(STDOUT_FILENO, buf, rlen));
467 fprintf(stderr, "Not all data written to stdout (%d/%d)\n", wlen, rlen);