toybox/toys/net/microcom.c
<<
>>
Prefs
   1/* microcom.c - Simple serial console.
   2 *
   3 * Copyright 2017 The Android Open Source Project.
   4
   5USE_MICROCOM(NEWTOY(microcom, "<1>1s#=115200X", TOYFLAG_USR|TOYFLAG_BIN))
   6
   7config MICROCOM
   8  bool "microcom"
   9  default y
  10  help
  11    usage: microcom [-s SPEED] [-X] DEVICE
  12
  13    Simple serial console.
  14
  15    -s  Set baud rate to SPEED (default 115200)
  16    -X  Ignore ^@ (send break) and ^] (exit)
  17*/
  18
  19#define FOR_microcom
  20#include "toys.h"
  21
  22GLOBALS(
  23  long s;
  24
  25  int fd;
  26  struct termios original_stdin_state, original_fd_state;
  27)
  28
  29// TODO: tty_sigreset outputs ansi escape sequences, how to disable?
  30static void restore_states(int i)
  31{
  32  tcsetattr(0, TCSAFLUSH, &TT.original_stdin_state);
  33  tcsetattr(TT.fd, TCSAFLUSH, &TT.original_fd_state);
  34}
  35
  36void microcom_main(void)
  37{
  38  struct pollfd fds[2];
  39  int i;
  40
  41  // Open with O_NDELAY, but switch back to blocking for reads.
  42  TT.fd = xopen(*toys.optargs, O_RDWR | O_NOCTTY | O_NDELAY);
  43  if (-1==(i = fcntl(TT.fd, F_GETFL, 0)) || fcntl(TT.fd, F_SETFL, i&~O_NDELAY))
  44    perror_exit_raw(*toys.optargs);
  45
  46  // Set both input and output to raw mode.
  47  xset_terminal(TT.fd, 1, TT.s, &TT.original_fd_state);
  48  set_terminal(0, 1, 0, &TT.original_stdin_state);
  49  // ...and arrange to restore things, however we may exit.
  50  sigatexit(restore_states);
  51
  52  fds[0].fd = TT.fd;
  53  fds[1].fd = 0;
  54  fds[0].events = fds[1].events = POLLIN;
  55
  56  while (poll(fds, 2, -1) > 0) {
  57
  58    // Read from connection, write to stdout.
  59    if (fds[0].revents) {
  60      if (0 < (i = read(TT.fd, toybuf, sizeof(toybuf)))) xwrite(0, toybuf, i);
  61      else break;
  62    }
  63
  64    // Read from stdin, write to connection.
  65    if (fds[1].revents) {
  66      if (read(0, toybuf, 1) != 1) break;
  67      if (!FLAG(X)) {
  68        if (!*toybuf) {
  69          tcsendbreak(TT.fd, 0);
  70          continue;
  71        } else if (*toybuf == (']'-'@')) break;
  72      }
  73      xwrite(TT.fd, toybuf, 1);
  74    }
  75  }
  76}
  77