| /* |
| * ntp_service.c |
| * |
| * NTP service source. |
| * |
| */ |
| /****************************************************************************** |
| |
| EDIT HISTORY FOR FILE |
| |
| WHEN WHO WHAT,WHERE,WHY |
| -------- -------- ------------------------------------------------------- |
| 2024/7/5 LiuBin Initial version |
| |
| ******************************************************************************/ |
| #include <stdio.h> |
| #include <stdlib.h> |
| #include <unistd.h> |
| #include <errno.h> |
| #include <pthread.h> |
| #include <cutils/properties.h> |
| #include <time.h> |
| #include <sys/time.h> |
| |
| #include "mbtk_type.h" |
| #include "mbtk_log.h" |
| #include "mbtk_ntp.h" |
| #include "mbtk_info_api.h" |
| |
| static bool is_first_boot = TRUE; |
| |
| |
| //int req_time_set(int type, char *time, int *cme_err); |
| static int metis_strptime(char *str_time) |
| { |
| struct tm stm; |
| char dateTime[30]; |
| struct timeval tv; |
| if(strptime(str_time, "%Y-%m-%d %H:%M:%S",&stm) != NULL) |
| { |
| time_t _t = mktime(&stm); |
| tv.tv_sec = _t; |
| if(settimeofday(&tv, NULL)) { |
| LOGE("Set time fail:%d", errno); |
| return -1; |
| } else { |
| LOGD("Set time to %s.", str_time); |
| return 0; |
| } |
| } else { |
| LOGE("Set time fail."); |
| return -1; |
| } |
| } |
| |
| static void* ntp_pthread_run(void* arg) |
| { |
| char time_type[10]; |
| while(1){ |
| memset(time_type, 0, 10); |
| property_get("persist.mbtk.time_type", time_type, "0"); |
| if(atoi(time_type) == MBTK_TIME_TYPE_NTP) // NTP time |
| { |
| char time_str[100] = {0}; |
| time_t time = 0; |
| while((time = (time_t)mbtk_at_systime()) == 0) { |
| usleep(100000); |
| } |
| struct tm *tm_t; |
| tm_t = localtime(&time); |
| strftime(time_str,128,"%F %T",tm_t); |
| |
| // NTP time |
| metis_strptime(time_str); |
| } else { |
| break; |
| } |
| |
| sleep(64); // Sleep 64s. |
| } |
| return NULL; |
| } |
| |
| static void ntp_thread_start() |
| { |
| pthread_t ntp_pid; |
| pthread_attr_t thread_attr; |
| pthread_attr_init(&thread_attr); |
| if(pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED)) |
| { |
| LOGE("pthread_attr_setdetachstate() fail."); |
| return; |
| } |
| |
| if(pthread_create(&ntp_pid, &thread_attr, ntp_pthread_run, NULL)) |
| { |
| LOGE("pthread_create() fail."); |
| } |
| } |
| |
| /** |
| * Called after starting the first time. |
| */ |
| int ntp_service_start() |
| { |
| if(!is_first_boot) { |
| LOGW("NTP has already been executed."); |
| return -1; |
| } |
| |
| is_first_boot = FALSE; |
| |
| char time_type[10]; |
| memset(time_type, 0, 10); |
| property_get("persist.mbtk.time_type", time_type, "0"); |
| if(atoi(time_type) == MBTK_TIME_TYPE_NTP) { // NTP time |
| LOGE("Start NTP thread."); |
| ntp_thread_start(); |
| } |
| |
| return 0; |
| } |