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

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

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

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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、上面代码只是部分,串口操作部分需要自己去写,或者网上有好多关于串口配置的代码。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值