2 * bare bones 'talk to modem' program - similar to 'cu -l $device'
3 * inspired by mgetty's microcom
5 * Copyright (C) 2007 by Vladimir Dronnikov <dronnikov@gmail.ru>
7 * Licensed under GPLv2, see file LICENSE in this tarball for details.
11 int microcom_main(int argc, char **argv);
12 int microcom_main(int argc, char **argv)
15 #define sfd (pfd[1].fd)
16 char *device_lock_file = NULL;
18 const char *opt_s = "9600";
22 struct termios tio0, tiosfd, tio;
24 getopt32(argv, "s:", &opt_s);
31 // try to create lock file in /var/lock
32 s = bb_basename(argv[0]);
35 bb_perror_msg_and_die("can't lock device");
37 device_lock_file = xasprintf("/var/lock/LCK..%s", s);
38 sfd = open(device_lock_file, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0644);
40 if (ENABLE_FEATURE_CLEAN_UP)
41 free(device_lock_file);
42 device_lock_file = NULL;
44 bb_perror_msg_and_die("can't lock device");
45 // We don't abort on other errors: /var/lock can be
46 // non-writable or non-existent
48 // %4d to make mgetty happy. It treats 4-bytes lock files as binary,
49 // not text, PID. Making 5+ char file. Brrr...
50 s = xasprintf("%4d\n", getpid());
51 write(sfd, s, strlen(s));
52 if (ENABLE_FEATURE_CLEAN_UP)
58 sfd = open(argv[0], O_RDWR | O_NDELAY);
60 bb_perror_msg("can't open device");
63 fcntl(sfd, F_SETFL, O_RDWR); // why?
65 // put stdin to "raw mode", handle one character at a time
66 tcgetattr(STDIN_FILENO, &tio0);
68 tio.c_lflag &= ~(ICANON|ECHO);
69 tio.c_iflag &= ~(IXON|ICRNL);
70 tio.c_oflag &= ~(ONLCR);
73 if (tcsetattr(STDIN_FILENO, TCSANOW, &tio)) {
74 bb_perror_msg("can't tcsetattr for %s", "stdin");
78 /* same thing for modem (plus: set baud rate) - TODO: make CLI option */
79 tcgetattr(sfd, &tiosfd);
81 tio.c_lflag &= ~(ICANON|ECHO);
82 tio.c_iflag &= ~(IXON|ICRNL);
83 tio.c_oflag &= ~(ONLCR);
86 cfsetispeed(&tio, tty_value_to_baud(speed));
87 cfsetospeed(&tio, tty_value_to_baud(speed));
88 if (tcsetattr(sfd, TCSANOW, &tio)) {
89 bb_perror_msg("can't tcsetattr for %s", "device");
94 signal(SIGINT, SIG_IGN);
97 tcflush(STDIN_FILENO, TCIFLUSH);
98 printf("connected to '%s' (%d bps), exit with ctrl-X...\r\n", argv[0], speed);
100 // main loop: check with poll(), then read/write bytes across
101 pfd[0].fd = STDIN_FILENO;
102 pfd[0].events = POLLIN;
104 pfd[1].events = POLLIN;
107 while (-1 == poll(pfd, 2, -1) && EINTR == errno)
109 for (i = 0; i < 2; ++i) {
110 if (pfd[i].revents & POLLIN) {
111 len = read(pfd[i].fd, bb_common_bufsiz1, COMMON_BUFSIZE);
113 if (!i && 24 == bb_common_bufsiz1[0])
114 goto done; // ^X exits
115 write(pfd[1-i].fd, bb_common_bufsiz1, len);
121 tcsetattr(sfd, TCSANOW, &tiosfd);
122 tcsetattr(STDIN_FILENO, TCSANOW, &tio0);
123 tcflush(STDIN_FILENO, TCIFLUSH);
125 if (ENABLE_FEATURE_CLEAN_UP)
131 if (device_lock_file) {
132 unlink(device_lock_file);
133 if (ENABLE_FEATURE_CLEAN_UP)
134 free(device_lock_file);