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