#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#define STANDARD_BAUDRATE B115200
#define MODEM_TTY "/dev/ttyS0"
static int open_port(void)
{
int fd;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyS0 - ");
}
else
fcntl(fd, F_SETFL, 0);
return (fd);
}
static int sendModemChars(int fd, char *phone, char *msg)
{
char buffer[255], *bufptr, foo[255];
int nbytes, msgLen;
const char byte = 26;
memset(buffer, 0x00, sizeof(buffer));
memset(foo, 0x00, sizeof(foo));
msgLen = strlen(msg);
if (write(fd, "AT\r", 3) < 3)
{
printf("command AT failed!\n");
return -1;
}
/* ler os caracteres retornado pelo MODEM */
bufptr = buffer;
while ( ( nbytes = read( fd, bufptr, (255 - 1) ) ) > 0 )
bufptr += nbytes;
*bufptr = '\0';
nbytes = strlen(buffer);
printf("command: %s\n", buffer);
if (strncmp(&buffer[nbytes-4], "OK", 2) != 0)
{
printf("MODEM NOT_OK!!");
return (-1);
}
printf("MODEM OK!!\n");
sprintf(foo, "AT+CMGS=\"%s\"\r", phone);
/* enviar comando para SMS do mondem */
if (write(fd, foo, 25) < 25)
{
printf("comando AT+CMGS=\"%s\" falied!\n", phone);
return -1;
}
memset(buffer, 0x00, sizeof(buffer));
bufptr = buffer;
while ( ( nbytes = read( fd, bufptr, (255 - 1) ) ) > 0 )
bufptr += nbytes;
*bufptr = '\0';
nbytes = strlen(buffer);
if (strncmp(&buffer[nbytes+5], ">", 1) == 0)
{
memset(foo, 0x00, sizeof(foo));
sprintf(foo, "%s%c", msg, byte);
if (write(fd, foo, (msgLen+1)) < (msgLen+1))
{
printf("msg Buffer failed.\n");
return -1;
}
while ( ( nbytes = read( fd, bufptr, (255 - 1) ) ) > 0 ) /*just read*/
sleep(2);
memset(buffer, 0x00, sizeof(buffer));
bufptr = buffer;
while ( ( nbytes = read( fd, bufptr, (255 - 1) ) ) > 0 )
bufptr += nbytes;
*bufptr = '\0';
nbytes = strlen(buffer);
if (strncmp(&buffer[nbytes-4], "OK", 2) == 0)
{
printf("%s\n", buffer);
return (0);
}
else return (-1);
}
return (-1);
}
int main( int argc, char *argv[] )
{
int fd, ret;
struct termios options;
char phone[12+1], msg[160+1];
memset(phone, 0x00, sizeof(phone));
memset(msg, 0x00, sizeof(msg));
memcpy(msg, "TEST SMS", 8);
if(argc < 2 || argc > 2)
{
printf("Oops.. phone number??\n");
exit(EXIT_FAILURE);
}
memcpy(phone, argv[1], strlen(argv[1]));
fd = open_port();
if ( fd < 0 )
{
perror(MODEM_TTY);
exit(-1);
}
/* get the current options */
tcgetattr(fd, &options);
/* set raw input, 1 second timeout */
options.c_cflag |= ( CLOCAL | CREAD );
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 10;
/* set the options */
tcsetattr(fd, TCSANOW, &options);
ret = sendModemChars(fd, phone, msg);
if ( ret == -1 )
printf("modem NOK!!\n");
close(fd);
return 0;
}