Mirror of CollapseOS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
2.6KB

  1. #include <stdlib.h>
  2. #include <unistd.h>
  3. #include <termios.h>
  4. #include <errno.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. void mread(int fd, char *s, int count)
  8. {
  9. while (count) {
  10. while (read(fd, s, 1) == 0);
  11. s++;
  12. count--;
  13. }
  14. }
  15. void sendcmd(int fd, char *cmd)
  16. {
  17. char junk[2];
  18. while (*cmd) {
  19. write(fd, cmd, 1);
  20. read(fd, &junk, 1);
  21. cmd++;
  22. // The other side is sometimes much slower than us and if we don't let
  23. // it breathe, it can choke.
  24. usleep(1000);
  25. }
  26. write(fd, "\r", 1);
  27. mread(fd, junk, 2); // sends back \r\n
  28. usleep(1000);
  29. }
  30. // Send a cmd and also read the "> " prompt
  31. void sendcmdp(int fd, char *cmd)
  32. {
  33. char junk[2];
  34. sendcmd(fd, cmd);
  35. mread(fd, junk, 2);
  36. }
  37. // from https://stackoverflow.com/a/6947758
  38. // discussion from https://stackoverflow.com/a/26006680 is interesting,
  39. // but we don't want POSIX compliance.
  40. int set_interface_attribs(int fd, int speed, int parity)
  41. {
  42. struct termios tty;
  43. if (tcgetattr (fd, &tty) != 0) {
  44. fprintf(stderr, "error %d from tcgetattr", errno);
  45. return -1;
  46. }
  47. if (speed) {
  48. cfsetospeed (&tty, speed);
  49. cfsetispeed (&tty, speed);
  50. }
  51. tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
  52. // disable IGNBRK for mismatched speed tests; otherwise receive break
  53. // as \000 chars
  54. tty.c_iflag &= ~IGNBRK; // disable break processing
  55. tty.c_lflag = 0; // no signaling chars, no echo,
  56. // no canonical processing
  57. tty.c_oflag = 0; // no remapping, no delays
  58. tty.c_cc[VMIN] = 0; // read doesn't block
  59. tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
  60. tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
  61. tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
  62. // enable reading
  63. tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
  64. tty.c_cflag |= parity;
  65. tty.c_cflag &= ~CSTOPB;
  66. tty.c_cflag &= ~CRTSCTS;
  67. if (tcsetattr (fd, TCSANOW, &tty) != 0) {
  68. fprintf(stderr, "error %d from tcsetattr", errno);
  69. return -1;
  70. }
  71. return 0;
  72. }
  73. void set_blocking(int fd, int should_block)
  74. {
  75. struct termios tty;
  76. memset(&tty, 0, sizeof tty);
  77. if (tcgetattr (fd, &tty) != 0) {
  78. fprintf(stderr, "error %d from tggetattr", errno);
  79. return;
  80. }
  81. tty.c_cc[VMIN] = should_block ? 1 : 0;
  82. tty.c_cc[VTIME] = 1; // 0.1 seconds read timeout
  83. if (tcsetattr (fd, TCSANOW, &tty) != 0) {
  84. fprintf(stderr, "error %d setting term attributes", errno);
  85. }
  86. }