#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
//#define ATPORT "/dev/ttyUSB0"
#define BUFSIZE 1000
#define BAUDRATE B115200
    char ATPORT[1024];
int open_port(char *port)
{
struct termios options;
int fd;
fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
printf("%s: Unable to open the port - \r\n",__func__);
} else {
fcntl(fd, F_SETFL, FNDELAY);
tcgetattr( fd, &options );
cfsetispeed( &options, BAUDRATE );
cfsetospeed( &options, BAUDRATE );
options.c_cflag |= ( CLOCAL | CREAD);
options.c_cflag &= ~(CSIZE | PARENB | CSTOPB | CSIZE);
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY | ICRNL | INLCR | IGNCR);
options.c_oflag &= ~OPOST;
if ( tcsetattr( fd, TCSANOW, &options ) == -1 ) {
printf ("Error with tcsetattr = %s\r\n", strerror ( errno ) );
} else {
printf ( "Open port %s succeed\r\n",ATPORT);
}
}
return (fd);
}

int send(int fd,char *str){
   
    printf("AT send :%s\r\n",str);
    write(fd,str,strlen(str));
    write(fd,"\r\n",2);
    return 0;
}

int receive(int fd){
    char buf[BUFSIZE] = {0};
    read(fd,buf, BUFSIZE);
    printf("AT receive: %s\r\n", buf);
    return 0;
}

int main(){
	system("ls  /dev/ttyUSB*");
	system("ls  /sys/class/net");
    printf("Please input port as /dev/ttyUSB0:\r\n");
    scanf("%s",ATPORT);
    char buf[1024];
    int fd = open_port(ATPORT);
    while(1){
    printf("Please input command:\r\n");
    scanf("%s",buf);
    send(fd,buf);
    sleep(1);
    receive(fd);
    }
    close(fd);
    return 0;
}

/*
int main()
{
int fd = open_port(ATPORT);
char at_cmd_all[50]="AT+GTUSBMODE?\r\n";
//ding yi buff 
char buf[BUFSIZE];
//clear buff 
memset(buf,0,BUFSIZE);
printf("AtSend: %s\r\n", at_cmd_ch_all);
scanf("%d",&at_cmd_ch);
write(fd, at_cmd_ch , strlen(at_cmd_ch_all));
//write
sleep(1);
read( fd, buf, BUFSIZE );
//read
printf("AtRecevie: %s\r\n", buf);
close(fd);
return 0;
}
*/
