Open a serial port
#include <sys/modem.h>
int modem_open( char* device,
speed_t baud );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The modem_open() function opens a serial port identified by device. The device is set to raw mode by changing the control flags using tcgetattr() and tcsetattr() as follows:
termio.c_cflag = CS8|IHFLOW|OHFLOW|CREAD|HUPCL; termio.c_iflag = BRKINT; termio.c_lflag = IEXTEN; termio.c_oflag = 0;
Any pending input or output characters are discarded.
If baud is nonzero, then the baud rate is changed to that value.
An open file descriptor, or -1 on failure (errno is set).
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/modem.h>
#include <stdio.h>
#include <errno.h>
/*
curstate curflags newstate newflags newtimeout
newquiet retvalue pattern response
*/
struct modem_script table[] ={
{1, 0, 1, 0, 2, 5, 0, NULL, "ATZ\\r\\P0a"},
{1, 0, 2, 0, 30, 5, 0, "*ok*", "ATDT5910934"},
{2, MODEM_BAUD, 3, MODEM_LASTLINE, 10, 5, 0, "*connect*", NULL},
{3, 0, 4, 0, 8, 5, 0, "*login:*", "guest"},
{4, MODEM_NOECHO, 5, 0, 15, 5, 0, "*password:*", "xxxx"},
{5, 0, 0, 0, 0, 0, 0, "*$ *", NULL},
{0, 0, 0, 0, 0, 0, 1, "*no carrier*", NULL},
{0, 0, 0, 0, 0, 0, 2, "*no answer*", NULL},
{0, 0, 0, 0, 0, 0, 3, "*no dialtone*", NULL},
{0, 0, 0, 0, 0, 0, 4, "*busy*", NULL},
{ NULL }
};
void io(char* progress, char* in, char* out) {
if(progress)
printf("progress: %s\n", progress);
if(in)
printf("input: %s\n", in);
if(out)
printf("output: %s\n", out);
}
int main(int argc, char* argv[]) {
int fd, status;
speed_t baud = -1;
if((fd = modem_open(argv[1], 0)) == -1) {
fprintf(stderr, "Unable to open %s: %s\n",
argv[1], strerror(errno));
exit(1);
}
status = modem_script( fd, table, &baud,
&io, NULL );
printf("status=%d baud=%d\n", status, baud);
exit(status);
}
| Safety: | |
|---|---|
| Cancellation point | Yes |
| Interrupt handler | No |
| Signal handler | Yes |
| Thread | Yes |