2 * Simple serial terminal
4 * Copyright 2014, 2015, 2016, 2017, 2019 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>
53 #define STRINGIFY(val) #val
54 #define TOSTRING(val) STRINGIFY(val)
55 #define CHECK(cmd) ({ int ret = (cmd); if (ret == -1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ret; })
56 #define CHECKPTR(cmd) ({ void *ptr = (cmd); if (ptr == (void*)-1) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
57 #define CHECKNULL(cmd) ({ void *ptr = (cmd); if (ptr == NULL) { perror(#cmd " line " TOSTRING(__LINE__)); exit(1); }; ptr; })
59 #define VERBOSE(format, ...) do { if (verbose) fprintf(stderr, "sterm: " format, ##__VA_ARGS__); } while (0)
62 bool exit_on_escape = true;
64 struct termios stdin_tio_backup;
67 void rm_file(int status, void *arg)
75 void restore_stdin_term()
77 tcsetattr(0, TCSANOW, &stdin_tio_backup);
83 dev_unlock(dev, getpid());
87 void sighandler(int arg)
89 exit(0); /* Invoke exit handlers */
92 int dtr_rts_arg(const char option, const char *optarg)
98 val = strtol(optarg, &end, 10);
102 case '+': val = +1; break;
103 case '-': val = -1; break;
105 fprintf(stderr, "Unknown -%c argument: %s\n", option, optarg);
113 void exit_on_escapeseq(const char *buf, int len)
115 static const char escseq[] = "\r~.";
116 static const char *state = escseq+1;
118 for (i = 0; i < len; i++) {
119 if (buf[i] == *state) {
125 if (buf[i] == *state)
131 void usage(const char* argv0)
133 fprintf(stderr, "Usage: %s [options] <device>\n", argv0);
136 " -b <duration> send break signal\n"
137 " -c enter command mode\n"
138 " -d[PULSE] make pulse on DTR\n"
139 " -e ignore '~.' escape sequence\n"
140 " -n do not switch stdin TTY to raw mode\n"
141 " -r[PULSE] make pulse on RTS\n"
145 "PULSE is a number specifying the pulse. Absolute value defines the\n"
146 "length of the pulse in milliseconds, sign determines the polarity of\n"
147 "the pulse. Alternatively, PULSE can be either '+' or '-', which\n"
148 "corresponds to +1 or -1.\n"
152 void pulse(int fd, int dtr, int rts)
155 /* tio.c_cflag &= ~HUPCL; */ /* Don't lower DTR/RTS on close */
157 CHECK(ioctl(fd, TIOCMGET, &status));
158 if (dtr > 0) { status &= ~TIOCM_DTR; ms = +dtr; }
159 if (dtr < 0) { status |= TIOCM_DTR; ms = -dtr; }
160 if (rts > 0) { status &= ~TIOCM_RTS; ms = +rts; }
161 if (rts < 0) { status |= TIOCM_RTS; ms = -rts; }
162 CHECK(ioctl(fd, TIOCMSET, &status));
166 if (dtr < 0) { status &= ~TIOCM_DTR; }
167 if (dtr > 0) { status |= TIOCM_DTR; }
168 if (rts < 0) { status &= ~TIOCM_RTS; }
169 if (rts > 0) { status |= TIOCM_RTS; }
170 CHECK(ioctl(fd, TIOCMSET, &status));
173 void handle_commands(int fd)
181 if (fgets(command, sizeof(command), stdin) == NULL) {
183 perror("Command read");
186 if (sscanf(command, "dtr %ms", &p1) == 1)
187 pulse(fd, dtr_rts_arg('d', p1), 0);
188 else if (sscanf(command, "rts %ms", &p1) == 1)
189 pulse(fd, 0, dtr_rts_arg('r', p1));
190 else if (sscanf(command, "break %d", &num) == 1)
191 CHECK(tcsendbreak(fd, num));
192 else if (strcmp(command, "go\n") == 0)
194 else if (strcmp(command, "exit\n") == 0)
197 fprintf(stderr, "Unknown command: %s\n", command);
205 int main(int argc, char *argv[])
210 int dtr = 0, rts = 0;
217 if ((stdin_tty = isatty(0))) {
218 CHECK(tcgetattr(0, &stdin_tio_backup));
219 atexit(restore_stdin_term);
222 while ((opt = getopt(argc, argv, "b:cnd::er::s:v")) != -1) {
224 case 'b': break_dur = atoi(optarg); break;
225 case 'c': cmd = true; break;
226 case 'd': dtr = dtr_rts_arg(opt, optarg); break;
227 case 'e': exit_on_escape = false; break;
228 case 'n': raw = false; break;
229 case 'r': rts = dtr_rts_arg(opt, optarg); break;
231 int s = atoi(optarg);
233 #define S(s) case s: speed = B##s; break;
267 fprintf(stderr, "Unknown baud rate %d\n", s);
285 fprintf(stderr, "No device specified\n");
290 signal(SIGINT, sighandler);
291 signal(SIGTERM, sighandler);
292 signal(SIGHUP, sighandler);
295 pid_t pid = dev_lock(dev);
297 fprintf(stderr, "%s is used by PID %d\n", dev, pid);
299 } else if (pid < 0) {
301 asprintf(&msg, "dev_lock('%s')", dev); /* No free() because we exit() immediately */
305 fprintf(stderr, "%s: Error\n", msg);
311 /* O_NONBLOCK is needed to not wait for the CDC signal. See tty_ioctl(4). */
312 if ((fd = open(dev, O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) {
316 /* Cancel the efect of O_NONBLOCK flag. */
317 int n = fcntl(fd, F_GETFL, 0);
318 fcntl(fd, F_SETFL, n & ~O_NDELAY);
323 CHECK(ioctl(fd, TIOCEXCL, NULL));
325 CHECK(tcgetattr(fd, &tio));
330 CHECK(cfsetospeed(&tio, speed));
331 CHECK(cfsetispeed(&tio, speed));
338 CHECK(tcsendbreak(fd, break_dur));
340 /* Disable flow control */
341 tio.c_cflag &= ~(CRTSCTS);
342 tio.c_iflag &= ~(IXON|IXOFF);
344 CHECK(tcsetattr(fd, TCSANOW, &tio));
345 } else if (speed || dtr || rts) {
346 fprintf(stderr, "Cannot set speed, DTR or RTS on non-terminal %s\n", dev);
350 VERBOSE("Connected.\r\n");
355 struct pollfd fds[2] = {
356 { .fd = 0, .events = POLLIN },
357 { .fd = fd, .events = POLLIN },
362 tio = stdin_tio_backup;
365 CHECK(tcsetattr(0, TCSANOW, &tio));
369 VERBOSE("Use '<Enter>~.' sequence to exit.\r\n");
373 CHECK(poll(fds, 2, -1));
374 if (fds[0].revents & POLLIN) {
375 r1 = CHECK(read(0, buf, sizeof(buf)));
377 VERBOSE("EOF on stdin\r\n");
381 exit_on_escapeseq(buf, r1);
382 r2 = CHECK(write(fd, buf, r1));
384 fprintf(stderr, "Not all data written to %s (%d/%d)\n", dev, r1, r2);
388 if (fds[0].revents & POLLHUP) {
389 VERBOSE("HUP on stdin\r\n");
392 if (fds[1].revents & POLLIN) {
393 r1 = CHECK(read(fd, buf, sizeof(buf)));
395 VERBOSE("EOF on %s\r\n", dev);
398 r2 = CHECK(write(1, buf, r1));
400 fprintf(stderr, "Not all data written to stdout (%d/%d)\n", r1, r2);