blob: 7f37214fbe0762bc6c19636b8c69c0993d8170f3 [file] [log] [blame]
b.liu87afc4c2024-08-14 17:33:45 +08001/*
2* ntp_service.c
3*
4* NTP service source.
5*
6*/
7/******************************************************************************
8
9 EDIT HISTORY FOR FILE
10
11 WHEN WHO WHAT,WHERE,WHY
12-------- -------- -------------------------------------------------------
132024/7/5 LiuBin Initial version
14
15******************************************************************************/
16#include <stdio.h>
b.liudeb8e422024-12-14 17:36:56 +080017#include <stdint.h>
b.liu87afc4c2024-08-14 17:33:45 +080018#include <stdlib.h>
19#include <unistd.h>
20#include <errno.h>
21#include <pthread.h>
22#include <cutils/properties.h>
23#include <time.h>
24#include <sys/time.h>
25
26#include "mbtk_type.h"
27#include "mbtk_log.h"
28#include "mbtk_ntp.h"
29#include "mbtk_info_api.h"
30
31static bool is_first_boot = TRUE;
32
33
34//int req_time_set(int type, char *time, int *cme_err);
35static int metis_strptime(char *str_time)
36{
37 struct tm stm;
b.liu62240ee2024-11-07 17:52:45 +080038// char dateTime[30];
b.liu87afc4c2024-08-14 17:33:45 +080039 struct timeval tv;
40 if(strptime(str_time, "%Y-%m-%d %H:%M:%S",&stm) != NULL)
41 {
42 time_t _t = mktime(&stm);
43 tv.tv_sec = _t;
44 if(settimeofday(&tv, NULL)) {
45 LOGE("Set time fail:%d", errno);
46 return -1;
47 } else {
48 LOGD("Set time to %s.", str_time);
49 return 0;
50 }
51 } else {
52 LOGE("Set time fail.");
53 return -1;
54 }
55}
56
57static void* ntp_pthread_run(void* arg)
58{
59 char time_type[10];
60 while(1){
61 memset(time_type, 0, 10);
62 property_get("persist.mbtk.time_type", time_type, "0");
63 if(atoi(time_type) == MBTK_TIME_TYPE_NTP) // NTP time
64 {
65 char time_str[100] = {0};
66 time_t time = 0;
67 while((time = (time_t)mbtk_at_systime()) == 0) {
68 usleep(100000);
69 }
70 struct tm *tm_t;
71 tm_t = localtime(&time);
72 strftime(time_str,128,"%F %T",tm_t);
73
74 // NTP time
75 metis_strptime(time_str);
76 } else {
77 break;
78 }
79
80 sleep(64); // Sleep 64s.
81 }
82 return NULL;
83}
84
85static void ntp_thread_start()
86{
87 pthread_t ntp_pid;
88 pthread_attr_t thread_attr;
89 pthread_attr_init(&thread_attr);
90 if(pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED))
91 {
92 LOGE("pthread_attr_setdetachstate() fail.");
93 return;
94 }
95
96 if(pthread_create(&ntp_pid, &thread_attr, ntp_pthread_run, NULL))
97 {
98 LOGE("pthread_create() fail.");
99 }
100}
101
102/**
103* Called after starting the first time.
104*/
105int ntp_service_start()
106{
107 if(!is_first_boot) {
108 LOGW("NTP has already been executed.");
109 return -1;
110 }
111
112 is_first_boot = FALSE;
113
114 char time_type[10];
115 memset(time_type, 0, 10);
116 property_get("persist.mbtk.time_type", time_type, "0");
117 if(atoi(time_type) == MBTK_TIME_TYPE_NTP) { // NTP time
118 LOGE("Start NTP thread.");
119 ntp_thread_start();
120 }
121
122 return 0;
123}