serial.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. #include <unistd.h>
  2. #include <string.h>
  3. #include <fcntl.h>
  4. #include <sys/time.h>
  5. #include "serial.h"
  6. #if defined(__sun__) || \
  7. defined(__OpenBSD__) || \
  8. defined(__FreeBSD__) || \
  9. defined(__NetBSD__) || \
  10. defined(__APPLE__)
  11. static struct termios tios = { BRKINT, 0, B115200|CS8|CREAD, 0, { 0 } };
  12. #else
  13. static struct termios tios = { BRKINT, 0, B115200|CS8|CREAD, 0, 0 };
  14. #endif
  15. static struct speedmap {
  16. char *str;
  17. speed_t val;
  18. } speedmap[] = {
  19. { "50", B50 }, { "75", B75 }, { "110", B110 },
  20. { "134", B134 }, { "150", B150 }, { "200", B200 },
  21. { "300", B300 }, { "600", B600 }, { "1200", B1200 },
  22. { "1800", B1800 }, { "2400", B2400 }, { "4800", B4800 },
  23. { "9600", B9600 }, { "19200", B19200 }, { "38400", B38400 },
  24. { "57600", B57600 },
  25. #ifdef B76800
  26. { "76800", B76800 },
  27. #endif
  28. { "115200", B115200 },
  29. #ifdef B153600
  30. { "153600", B153600 },
  31. #endif
  32. { "230400", B230400 },
  33. #ifdef B307200
  34. { "307200", B307200 },
  35. #endif
  36. #ifdef B460800
  37. { "460800", B460800 }
  38. #endif
  39. };
  40. static int nspeeds = sizeof speedmap / sizeof speedmap[0];
  41. speed_t
  42. cvtspeed(char *str)
  43. {
  44. struct speedmap *smp = speedmap, *esmp = &speedmap[nspeeds];
  45. while (smp < esmp) {
  46. if (strcmp(str, smp->str) == 0)
  47. return (smp->val);
  48. smp++;
  49. }
  50. return B0;
  51. }
  52. int
  53. serialopen(char *device, speed_t speed)
  54. {
  55. int fd;
  56. if (cfsetospeed(&tios, speed) < 0)
  57. return -1;
  58. if ((fd = open(device, O_RDWR)) < 0)
  59. return -1;
  60. if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
  61. (void)close(fd);
  62. return -1;
  63. }
  64. return fd;
  65. }
  66. int
  67. serialreadchar(int fd, int timeout)
  68. {
  69. fd_set fds;
  70. struct timeval tv;
  71. int n;
  72. char ch;
  73. tv.tv_sec = timeout;
  74. tv.tv_usec = 0;
  75. FD_ZERO(&fds);
  76. FD_SET(fd, &fds);
  77. /* this is a fucking horrible quick hack - fix this */
  78. if ((n = select(fd + 1, &fds, 0, 0, &tv)) < 0)
  79. return SERIAL_ERROR;
  80. if (n == 0)
  81. return SERIAL_TIMEOUT;
  82. if ((n = read(fd, &ch, 1)) < 0)
  83. return SERIAL_ERROR;
  84. if (n == 0)
  85. return SERIAL_EOF;
  86. return ch;
  87. }
  88. int
  89. serialwrite(int fd, char *buf, int len)
  90. {
  91. int n;
  92. do {
  93. n = write(fd, buf, len);
  94. if (n < 0)
  95. return 1;
  96. len -= n;
  97. buf += n;
  98. } while (len > 0);
  99. return 0;
  100. }
  101. int
  102. serialclose(int fd)
  103. {
  104. return close(fd);
  105. }