#include #include #include #include #include #include #include #include #include #define SUCCESS 0 #define ERROR_ARGS 1 #define ERROR_DEV 2 #define ERROR_CONN 3 long getbaudrate(int rate) { switch (rate) { case 115200: return B115200; case 57600: return B57600; case 38400: return B38400; case 19200: return B19200; case 9600: return B9600; case 2400: return B2400; case 1800: return B1800; case 1200: return B1200; case 600: return B600; case 300: return B300; case 200: return B200; default: fprintf(stderr, "Unsupported baudrate %d\n", rate); exit(ERROR_ARGS); } } int main(int argc, char **argv) { if (argc != 3) { printf("Usage: %s device speed\n", argv[0]); exit(ERROR_ARGS); } long ratebyte = getbaudrate(atoi(argv[2])); int fd; fd = open(argv[1], O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd < 0) { perror(argv[1]); exit(ERROR_DEV); } struct termios attr; tcgetattr(fd, &attr); attr.c_cflag |= CLOCAL | CS8 | ratebyte; tcflush(fd, TCIOFLUSH); tcsetattr(fd, TCSANOW, &attr); write(fd, "AT\r\n", 4); int state = 0; int endtime = time(NULL) + 2; while (time(NULL) < endtime) { usleep(100000); char buf; int count; count = read(fd, &buf, 1); if (count == 0 || (count == -1 && errno == EAGAIN)) continue; if (count == -1) { perror(argv[1]); close(fd); exit(ERROR_DEV); } if (count == 1) { if (state == 0 && buf == 'O') { state = 1; } else if (state == 1 && buf == 'K') { close(fd); exit(SUCCESS); } else if (state == 1) { state = 0; } } } close(fd); exit(ERROR_CONN); }