从4G模组读取实时时间代码

1、嵌入式软件研发硬件,当没有RTC时,有4G网络或者有线网络,从网络上获取时间。

2、因目前做一款设备,偶尔服务器不在线,授时不成功,设备是4G设备,那么从4G上获取当前时间显得有些必要。

3、今天简单写了个测试程序,主要部分代码如下:

#include 
#include 
#include 
#include "serial.h"

int getChars(char* source, char* buf)
{
    int i=0,j=0,flag=0;
    while(source[i]!='\0')
    {
        if(flag==0 && source[i]=='\"')
        {
            flag=1;
        }
        else if(flag==1 && source[i]=='\"')
        {
            buf[j]='\0';
            return 1;
        }
        else if(flag==1 && source[i]!='\"')
        {
            buf[j++]=source[i];
        }
        i++;
    }
    return 0;
}
int Buf2Data(char *s, char *time)
{
	int buf_len,j;

	buf_len = strlen(s);
	//如果分解的字符串为空或者长度小于6,则返回 
	if( (s == NULL) || (buf_len <17 ))
	{ 
	   return -1;
 	 }
	char *p = s;
	char *str[2];
	char *str1[3];
	char *q;
	char *l;
	q = strtok(s,",");
	for(j=0;j<2;j++)
	{
	     str[j] = q;
		 q =strtok(NULL,"|");
		 printf("str[%d] is %s\n",j,str[j]);
	}
	l = strtok(str[0],"/");
	
	for(j=0;j<3;j++)
	{			
		 str1[j] = l;
		 l = strtok(NULL,"/");
	}
	for(j=0;j<3;j++)
		{
		time[j] = atoi(str1[j]);
	}
	l = strtok(str[1],":");
	for(j=0;j<3;j++)
	{			
		 str1[j] = l;
		 l = strtok(NULL,":");
	}

	time[3] = atoi(str1[0])+8;
	
	time[4] = atoi(str1[1]);
	time[5] = atoi(str1[2]);

	return 0;
}

int get_Time(char * com_port,int baud)
{
	int tty_fd;
	int readBytes;
	char bufGet[32];
	char time[6];
	tty_fd = InitCom(com_port);
	if(tty_fd < 0)
	{
		printf("open tty error:%s\n",com_port);
		return -1;	
	}
	SetConfig(tty_fd,baud,8,'N',1);
	char buf[512];
	memset(buf,0,512);
	sprintf(buf,"%s","AT+CCLK?\r");
	write(tty_fd,buf,strlen(buf));
	sleep(1);
	memset(buf,0,512);
	readBytes = read(tty_fd,buf,512);
	//printf("the readBytes is %d\n",readBytes);
	close(tty_fd);
	if(getChars(buf,bufGet) < 0)
		return -1;
	
	Buf2Data(bufGet,time);
	printf("get chars is : %s,time:%d %d %d %d %d %d\n",bufGet,time[0],time[1],time[2],time[3],time[4],time[5]);
	return 0;
}

int main(int argc, char *argv[])
{
	if(argc < 2)
		{
		printf("./exec comName baud\n");
		return -1;
		}
	get_Time(argv[1],atoi(argv[2]));
	return 0;
}

4、上面代码只是部分,串口操作部分需要自己去写,或者网上有好多关于串口配置的代码。

你可能感兴趣的:(4G模组获取时间)