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.

103 lines
2.7KB

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