liyuezong 1 год назад
Родитель
Сommit
29b7ba5143
7 измененных файлов с 483 добавлено и 135 удалено
  1. 104 60
      ip/src/app.c
  2. 14 13
      ip/src/appweb_handle.c
  3. 214 15
      ip/src/common.c
  4. 25 10
      ip/src/common.h
  5. 117 29
      ip/src/ntpclient.c
  6. 8 4
      ip/src/ntpclient.h
  7. 1 4
      ip/src/sqlite_handle.c

+ 104 - 60
ip/src/app.c

@@ -1109,47 +1109,121 @@ void* shm_thread(void *arg)
 	pthread_exit(NULL);
 }
 
-void* ntp_thread(void *arg)
+static void* ntp_thread(void *arg)
 {
-    time_t start_t, end_t;
+    int r=0,flag=0;
+    NTPClient  *pc=NULL;
+    time_t time1=0,time2=0,utc_time;
     thread_handle_t *h=(thread_handle_t*)arg;
+    NTPManager *pntp=&_globalNTPManager;
 
-    start_t = time(NULL);
-    while(h->quit==0)
+    #define NTP_TIMEOUT         5
+    #define NTP_INTERVAL_TIME   30
+    time1 = time(NULL);
+    while (h->quit == 0)
     {
-        if (end_t - start_t >= 1 && _globalNTPManager.mode == true)
+        if (pntp->mode > 0)
         {
-            globalNTPclient = createNTPClient(_globalNTPManager.ntpaddress, _globalNTPManager.port);
-
-            if (globalNTPclient ==NULL)
+            //printf("___ntp_sync_flag: %d, interval: %d\n",  ntp_sync_flag, abs(time1-time2));
+            if (ntp_sync_flag || (abs(time1 - time2) >= NTP_INTERVAL_TIME))
             {
-                log_e("Failed to Connect the NTP server.");
-                sleep(600);
-                continue;
-            }
-            
-            time_t current_time;  
-            if (getCurrentTimeFromNTP(globalNTPclient, &current_time) < 0)
-            {
-                log_e("Failed to get time from NTP server.");
-                sleep(600);
-                continue;
+                system("date");
+                if(pc==NULL) {
+                    pc = createNTPClient(pntp->ntpaddress, pntp->port, NTP_TIMEOUT);
+                }
+
+                if (pc)
+                {
+                    if (getCurrentTimeFromNTP(pc, &utc_time) == 0)
+                    {
+                        time_t host_time = time(NULL);
+                        log_d("host_time: %ld, ntp_time: %ld", host_time, utc_time);
+                        //if(host_time != utc_time) {
+                            set_utctime(utc_time);
+                            //set_utctime_zone(utc_time, pntp->tzone);
+                            log_i("setCurrentTimeFromNTP success!");
+                       // }
+                    }
+                    else
+                    {
+                        log_e("getCurrentTimeFromNTP failed!");
+                    }
+                    destroyNTPClient(pc);
+                    pc = NULL;
+                }
+                ntp_sync_flag = 0;
+                time2 = time1;
             }
-            time_t t = time(NULL);
-            struct tm *ptm = localtime(&t);
-            struct tm *pCurrenttm = gmtime(&current_time);
-            if (abs(t - current_time) >= 5)
-                set_local_timeandzone(pCurrenttm, _globalNTPManager.tzone);
-            end_t = start_t;
         }
-        end_t = time(NULL);
-
-        sleep(600); // 十分钟同步一次
+        time1 = time(NULL);
+        sleep(1);
     }
-    destroyNTPClient(globalNTPclient);
+    destroyNTPClient(pc);
 
     pthread_exit(NULL);
 }
+int ntp_config(NTPManager *nm)
+{
+    int r=0;
+
+#ifdef USE_NTPD
+    if(nm->mode==1) {
+        char cmd[400];
+        char *conf="/etc/ntp.conf";
+
+        sprintf(cmd, "sed -e /^server.*$/d -e \"$ a server %s minpoll 4 maxpoll 5\" -i %s", nm->ntpaddress, conf);
+        printf("___cmd: %s\n", cmd);
+        r = system(cmd);
+        system("/etc/init.d/S49ntp restart");
+    }
+    else {
+        system("/etc/init.d/S49ntp stop");
+    }
+#else
+    //system("/etc/init.d/S49ntp stop");
+    if(nm->mode==1) {
+        ntp_sync_flag = 1;
+    }
+#endif
+
+    return r;
+}
+static int ntp_init(void)
+{
+    int r=0,flag=0;
+    time_t time1=0,time2=0,utc_time;
+    GlobalDeviceManager *dm=&__globalDeviceManage;
+    NTPManager *pntp=&_globalNTPManager;
+    
+    r = dev_get_ntp_info(dm->db,  pntp);
+    if (r) {
+        pntp->mode = 1;
+        strcpy(pntp->ntpaddress, "cn.pool.ntp.org");
+        strcpy(pntp->ntpName, "cn-pool");
+        pntp->port = 123;
+        pntp->product_id = dm->_globalDevInfo.product_id;
+        time_t t = time(NULL);
+        struct tm* ptm = localtime(&t);
+        sprintf(pntp->time, "%04d-%02d-%02d %02d:%02d:%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
+        struct tm* ptm_gm = gmtime(&t);
+        pntp->tzone = 8;
+        pntp->weekday = (ptm->tm_wday == 0) ? 7 : ptm->tm_wday;
+        if (dev_insert_ntp_info(dm->db,  pntp)) {
+            log_e("insert npt info failed");
+        }
+    }
+    else {
+        log_d("get ntp info from database succeeded");
+    }
+
+    ntp_config(pntp);
+#ifndef USE_NTPD
+    thread_start(THREAD_ID_NTP, ntp_thread, NULL, 10 * MB, 0);
+#endif
+
+    return 0;
+}
+
 
 void* snmp_thread(void *arg)
 {
@@ -1416,38 +1490,8 @@ int _global_device_manage_init(GlobalDeviceManager* _globalDeviceManager)
 #endif
     //创建传感器采集控制线程
 
-    _globalNTPManager.ntpaddress = malloc(128);
-    _globalNTPManager.ntpName = malloc(128);
-    _globalNTPManager.time = malloc(22);
-    ret = dev_get_ntp_info(_globalDeviceManager->db,  &_globalNTPManager);
-    if (ret == -1)
-    {
-        log_e("get ntp info from database failed");
-    }
-    else if (ret == -2)
-    {
-        _globalNTPManager.mode = 1;
-        strcpy(_globalNTPManager.ntpaddress, "119.28.183.184");
-        strcpy(_globalNTPManager.ntpName, "百度NTP");
-        _globalNTPManager.port = 123;
-        _globalNTPManager.product_id = _globalDeviceManager->_globalDevInfo.product_id;
-        time_t t = time(NULL);
-        struct tm* ptm = localtime(&t);
-        sprintf(_globalNTPManager.time, "%04d-%02d-%02d %02d:%02d:%02d", ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
-        struct tm* ptm_gm = gmtime(&t);
-        _globalNTPManager.tzone = 8;//ptm_gm->tm_hour - ptm->tm_hour;
-        _globalNTPManager.weekday = (ptm->tm_wday == 0) ? 7 : ptm->tm_wday;
-        if (dev_insert_ntp_info(_globalDeviceManager->db,  &_globalNTPManager))
-        {
-            log_e("insert npt info failed");
-        }
-    }
-    else
-    {
-        log_d("get ntp info from database succeeded");
-    }
 
-    //thread_start(THREAD_ID_NTP, ntp_thread, NULL, 10 * MB, 0);
+     ntp_init();
     dev_Alarm_Run_message(_globalDeviceManager, language_alarm_Init_Success[0], "NTP");
 
 #ifndef USE_NETSWITCH

+ 14 - 13
ip/src/appweb_handle.c

@@ -3602,13 +3602,10 @@ static void serviceManagement(void *conn)
     else if(strcmp(_serviceManageRequestInfo.type,"NtpSave")==0)
     {
         _globalNTPManager.mode = atoi(_serviceManageRequestInfo._ntp_info.mode);
-       _globalNTPManager.ntpaddress= malloc(64);
         strcpy(_globalNTPManager.ntpaddress, _serviceManageRequestInfo._ntp_info.ntpaddress);
-        _globalNTPManager.ntpName= malloc(64);
         strcpy(_globalNTPManager.ntpName, _serviceManageRequestInfo._ntp_info.ntpName);
         _globalNTPManager.port = atoi(_serviceManageRequestInfo._ntp_info.port);
         _globalNTPManager.product_id = __globalDeviceManage._globalDevInfo.product_id;
-         _globalNTPManager.time= malloc(64);
         strcpy(_globalNTPManager.time, _serviceManageRequestInfo._ntp_info.time);
         const char* key = "GMT/UTC";
         char* p = strstr(_serviceManageRequestInfo._ntp_info.tzone, key);
@@ -3624,7 +3621,7 @@ static void serviceManagement(void *conn)
         {
             char buf[128];
             memset(buf, 0, sizeof(buf));
-            sprintf(buf, "product id = %d timezone err.", _globalNTPManager.product_id);
+            sprintf(buf, "product id = %d timezone: %d, timezone err.", _globalNTPManager.product_id, value);
             log_e(buf);
             return;
         }      
@@ -3645,7 +3642,6 @@ static void serviceManagement(void *conn)
         }
         if (_globalNTPManager.mode == 0)
         {
-            time_t t;
             memset(tempstr, 0, sizeof(tempstr));
             p = strstr(_globalNTPManager.time, "-");
             if (p == NULL)
@@ -3656,7 +3652,7 @@ static void serviceManagement(void *conn)
             memset(tempstr, 0, sizeof(tempstr));
             memcpy(tempstr, _globalNTPManager.time, p - _globalNTPManager.time);
             struct tm tm_new;
-            tm_new.tm_year = atoi(tempstr) - 1900;
+            tm_new.tm_year = atoi(tempstr);
             char* p1 = strstr(&p[1], "-");
             if (p1 == NULL)
             {
@@ -3666,7 +3662,7 @@ static void serviceManagement(void *conn)
             int nSize= p1 - p - 1;
             memset(tempstr, 0, sizeof(tempstr));
             memcpy(tempstr, &p[1],nSize);
-            tm_new.tm_mon = atoi(tempstr) - 1;
+            tm_new.tm_mon = atoi(tempstr);
             p = p1;
             p1 = strstr(&p[2], " ");//个位数第一位有可能是空格所以需要找空格后一个
             if (p1 == NULL)
@@ -3713,8 +3709,15 @@ static void serviceManagement(void *conn)
             memset(tempstr, 0, sizeof(tempstr));
             memcpy(tempstr, &p[0], 2);
             tm_new.tm_sec = atoi(tempstr);
-            t = mktime(&tm_new);
-            set_local_timeandzone(&tm_new, _globalNTPManager.tzone);
+
+            set_time_zone(&tm_new, _globalNTPManager.tzone);
+        }
+        else if (_globalNTPManager.mode == 1)
+        {
+            set_zone(_globalNTPManager.tzone);
+            sleep(1);
+            extern int ntp_config(NTPManager *nm);
+            ntp_config(&_globalNTPManager);
         }
 
         char temp[100];
@@ -5137,8 +5140,6 @@ static int webSetCallback(void)
 
 int appweb_init(void)
 {
-    thread_start(THREAD_ID_WEB, web_thread, &__globalDeviceManage, 16*MB, 0);
-    
+    thread_start(THREAD_ID_WEB, web_thread, &__globalDeviceManage, 16*MB, 0);  
     return 0;
-}
-
+}

+ 214 - 15
ip/src/common.c

@@ -8,20 +8,23 @@
 #include <net/if.h>
 #include <arpa/inet.h>
 #include <sys/vfs.h>
+#include <sys/ioctl.h>
+#include <linux/rtc.h>
 
 #undef LOG_TAG
 #define LOG_TAG    "main"
 
 
-GlobalDeviceManager __globalDeviceManage;
-GlobalDeviceManager __globalDeviceManage2;
+GlobalDeviceManager __globalDeviceManage={0};
+GlobalDeviceManager __globalDeviceManage2={0};
 
+int ntp_sync_flag=0;
 unsigned long __globalSxIdx;
-NTPClient* globalNTPclient;
 _User_Log _GlobalUserLoginInfo;
 UserInfo _GlobalUserInfoNew;
 char _GlobalUserToken[64];
 MenuAuthority _GlobalMenuAuthority;
+NTPManager _globalNTPManager;
 
 void printf_global_device_info(GlobalDeviceInfo* _globalDeviceInfo)
 {
@@ -273,10 +276,122 @@ void get_disk_occupy(char ** reused)
     return;
 }
 
-int set_local_timeandzone(struct tm* t, int zone)
+
+static int set_rtc(time_t t)
+{
+    /*
+    int r=0,fd;
+    struct rtc_time *rtc;
+
+    struct tm *tm = gmtime(&t);
+    fd = open("/dev/rtc0", O_RDONLY);
+    if (fd < 0) {
+        perror("open rtc failed\n");
+        return -1;
+    }
+ 
+    rtc = (struct rtc_time*)tm;
+    if (ioctl(fd, RTC_SET_TIME, rtc) < 0) {
+        perror("ioctl RTC_SET_TIME failed\n");
+        r = -1;
+    }
+    else {
+        printf("set rtc ok!\n");
+    }
+    close(fd);
+    
+    return r;
+    */
+    system("hwclock -w -f /dev/rtc0");
+    return 0;
+    
+}
+
+#define MY_MINUTE  60
+#define MY_HOUR    (60*MY_MINUTE)
+#define MY_DAY     (24*MY_HOUR)
+#define MY_YEAR    (365*MY_DAY)
+static int my_month[12] = {
+    0,
+    MY_DAY*(31),
+    MY_DAY*(31+29),
+    MY_DAY*(31+29+31),
+    MY_DAY*(31+29+31+30),
+    MY_DAY*(31+29+31+30+31),
+    MY_DAY*(31+29+31+30+31+30),
+    MY_DAY*(31+29+31+30+31+30+31),
+    MY_DAY*(31+29+31+30+31+30+31+31),
+    MY_DAY*(31+29+31+30+31+30+31+31+30),
+    MY_DAY*(31+29+31+30+31+30+31+31+30+31),
+    MY_DAY*(31+29+31+30+31+30+31+31+30+31+30)
+};
+time_t mktime2(struct tm *t, int zone)
+{
+    time_t res,year;
+
+    year = t->tm_year - 70;
+    /* magic offsets (y+1) needed to get leapyears right.*/
+    res = MY_YEAR*year + MY_DAY*((year+1)/4);
+    res += my_month[t->tm_mon];
+    /* and (y+2) here. If it wasn't a leap-year, we have to adjust */
+    if (t->tm_mon>1 && ((year+2)%4))
+        res -= MY_DAY;
+    res += MY_DAY*(t->tm_mday-1);
+    res += MY_HOUR*t->tm_hour;
+    res += MY_MINUTE*t->tm_min;
+    res += t->tm_sec;
+
+    res -= zone*3600;
+
+    return res;
+}
+time_t mktime0(void)
+{
+    struct tm t;
+
+    t.tm_year = 70;
+    t.tm_mon = 0;
+    t.tm_mday = 1;
+    t.tm_hour = 0;
+    t.tm_min = 0;
+    t.tm_sec = 0;
+    return mktime(&t);
+}
+
+
+int set_time(struct tm *t, int zone)
+{
+    if(!t) {
+        return -1;
+    }
+    t->tm_year -= 1900;
+    t->tm_mon -= 1;
+    time_t utc = mktime2(t, zone);
+    stime(&utc);
+    set_rtc(utc);
+    return 0;
+}
+
+
+int set_utctime(time_t t)
+{
+    stime(&t);
+    set_rtc(t);
+    sleep(1);
+    //system("hwclock -w -f /dev/rtc0");
+    //system("hwclock -w");
+    system("hwclock --show");
+    
+    system("hwclock -s");
+    
+    return 0;
+    
+}
+
+
+int set_zone(int zone)
 {
     char buf[256];
-    struct timeval tv;
 
 #if 0
     switch(zone) {
@@ -356,19 +471,80 @@ int set_local_timeandzone(struct tm* t, int zone)
             return -1;
     }
 #else
-    sprintf(buf, "ln -sf /usr/share/zoneinfo/Etc/GMT%s%d /etc/localtime", (zone<0)?"+":"-", abs(zone));
+    sprintf(buf, "ln -sf /usr/share/zoneinfo/GMT%s%d /etc/localtime", (zone<0)?"+":"-", abs(zone));
 #endif
-    system(buf);
 
-    //t += zone * 3600;
-    //struct tm* ptm = localtime(&t);
-    memset(buf, 0, sizeof(buf));
-    //sprintf(buf, "echo \"Hello\"");
-    sprintf(buf, "date -s \"%04d-%02d-%02d %02d:%02d:%02d\" && hwclock -w -f /dev/rtc0 ", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
-    log_i("%s",buf);
-    system(buf);
+    log_i("set_zone: %s", buf);
+    return system(buf);
+}
 
-    return 0;
+
+void print_time(char *s, struct tm *tm)
+{
+    printf("___%s___, %04d-%02d-%02d %02d:%02d:%02d\n", s, tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
+}
+
+void print_utc(char *s, time_t t)
+{
+    struct tm *tm=gmtime(&t);
+
+    tm->tm_year += 1900;
+    tm->tm_mon += 1;
+    print_time(s, tm);
+}
+
+
+int set_time_zone(struct tm *t, int zone)
+{
+    int r;
+
+    if(!t) {
+        return -1;
+    }
+
+    r = set_zone(zone);
+    if(r) {
+        log_e("__1__ set_zone failed\n");
+    }
+
+    print_time("111", t);
+    r = set_time(t, zone);
+    if(r) {
+        log_e("__1__ set_time failed\n");
+    }
+    print_utc("222", time(NULL));
+
+    return r;
+}
+
+
+int set_utctime_zone(time_t t, int zone)
+{
+    int r;
+
+    r = set_zone(zone);
+    if(r) {
+        log_e("__2__ set_zone failed\n");
+    }
+
+    r = set_utctime(t);
+    if(r) {
+        log_e("__2__ set_time failed\n");
+    }
+    
+    return r;
+}
+
+int get_time_str(char *s, int len, time_t t)
+{
+    struct tm *tm=localtime(&t);
+    return snprintf(s, len, "%04d-%02d-%02d %02d:%02d:%02d.000",tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
+}
+
+int get_time_str2(char *s, int len, time_t t)
+{
+    struct tm *tm=localtime(&t);
+    return snprintf(s, len, "%04d%02d%02d%02d%02d%02d", tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);
 }
 
 char* getUserNamebyToken(char* Token)
@@ -396,6 +572,29 @@ char* getUserNamebyToken(char* Token)
 }
 
 
+typedef struct {
+    uint16_t     year;
+    uint8_t      mon;
+    uint8_t      day;
+    uint8_t      hour;
+    uint8_t      min;
+    uint8_t      sec;
+}datetime_t;
+int get_bldtime(char *buf, int len)
+{
+    char mon[10]={0};
+    datetime_t dt;
+    char *mon2[12]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
+
+    sscanf(__DATE__, "%s %hhu %hu", mon,&dt.day,&dt.year);
+    sscanf(__TIME__, "%hhu:%hhu:%hhu", &dt.hour,&dt.min,&dt.sec);
+    for(int i=0;i<12;i++) {
+        if(strcmp(mon, mon2[i])==0) {
+            dt.mon = i+1; break;
+        }
+    }
+    return snprintf(buf,len,"%04hu/%02hhu/%02hhu %02hhu:%02hhu:%02hhu",dt.year,dt.mon,dt.day,dt.hour,dt.min,dt.sec);
+}
 
 
 int is_process_running(const char *process_name)

+ 25 - 10
ip/src/common.h

@@ -353,14 +353,14 @@ typedef struct
 
 typedef struct
 {
-    int                 product_id;
-    int                 mode;
-    char*               ntpName;
-    char*               ntpaddress;
-    int                 port;
-    char*               time;
-    int                 weekday;
-    int                 tzone;
+    int product_id;
+    int mode;
+    char ntpName[64];
+    char ntpaddress[64];
+    int port;
+    char time[64];
+    int weekday;
+    int tzone;
 }NTPManager;
 NTPManager _globalNTPManager;
 
@@ -1043,13 +1043,14 @@ typedef struct
 extern GlobalDeviceManager __globalDeviceManage;
 extern GlobalDeviceManager __globalDeviceManage2;
 
-extern NTPClient* globalNTPclient;
+extern int ntp_sync_flag;
 extern unsigned long __globalSxIdx;
 
 extern _User_Log _GlobalUserLoginInfo;//全局用户登录信息
 extern UserInfo _GlobalUserInfoNew;////最近登录的信息
 extern char _GlobalUserToken[64];////最近登录的信息
 extern MenuAuthority _GlobalMenuAuthority;////角色菜单权限
+extern NTPManager _globalNTPManager;
 
 void initLogger(void);
 
@@ -1067,7 +1068,21 @@ int getTotalMemorySize(unsigned int* totalSize);
 char* getLocalIpAddress(char* dev);
 char* get_mac_address(const char *iface_name) ;
 void get_disk_occupy(char ** reused);
-int set_local_timeandzone(struct tm* t, int zone);
+
+int set_zone(int zone);
+int set_time(struct tm *t, int zone);
+int set_utctime(time_t t);
+int set_time_zone(struct tm *t, int zone);
+int set_utctime_zone(time_t t, int zone);
+
+time_t mktime0(void);
+time_t mktime2(struct tm *t, int zone);
+int get_time_str(char *s, int len, time_t t);
+int get_time_str2(char *s, int len, time_t t);
+int get_bldtime(char *buf, int len);
+void print_time(char *s, struct tm *tm);
+void print_utc(char *s, time_t t);
+
 char* getUserNamebyToken(char* Token);
 int is_process_running(const char *process_name);
 bool CheckLoginStatus(char* Token);

+ 117 - 29
ip/src/ntpclient.c

@@ -1,5 +1,11 @@
-
+#define _GNU_SOURCE
+#include <netdb.h>
+#include <signal.h>
+#include <unistd.h>
+#include <unistd.h>
+#include <fcntl.h>
 #include "ntpclient.h"
+#include "thread.h"
   
 #define NTP_PORT 123  
 #define NTP_PACKET_SIZE 48  
@@ -8,7 +14,7 @@
 static int sendNTPRequest(NTPClient* client) {  
     client->ntp_packet[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (client)  
     ssize_t sentBytes = sendto(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,  
-                               (struct sockaddr *)&client->server_addr, sizeof(client->server_addr));  
+                               &client->server_addr, sizeof(client->server_addr));  
     if (sentBytes < 0) {  
         perror("sendto failed");  
         return -1;  
@@ -17,10 +23,10 @@ static int sendNTPRequest(NTPClient* client) {
 }  
   
 // 接收NTP响应  
-static int receiveNTPResponse(NTPClient* client) {  
-    socklen_t len = sizeof(client->server_addr);  
+static int receiveNTPResponse(NTPClient* client) {
+    socklen_t len = sizeof(client->server_addr);
     ssize_t receivedBytes = recvfrom(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,  
-                              (struct sockaddr *)&client->server_addr, &len);  
+                              &client->server_addr, &len);  
     if (receivedBytes < 0) {  
         perror("recvfrom failed");  
         return -1;  
@@ -35,32 +41,114 @@ static time_t parseNTPResponse(const char* ntp_packet) {
     double frac = frac_sec * 2.0e-32;  
     return (time_t)(sec_since_1900 - 2208988800U) + (time_t)frac;  
 }  
-  
-// 创建NTP客户端实例  
-NTPClient* createNTPClient(const char* ntp_server, int port) {  
+
+typedef struct {
+    char     ip[64];
+    uint16_t port;
+}ipaddr_t;
+static int get_addr(ipaddr_t *addr, struct addrinfo *info)
+{
+    addr->ip[0] = 0; addr->port = 0;
+    if(info->ai_family==AF_INET) {
+        struct sockaddr_in* p=(struct sockaddr_in*)(info->ai_addr);
+        addr->port = htons(p->sin_port);
+        inet_ntop(p->sin_family, &p->sin_addr, addr->ip, sizeof(addr->ip));
+    }
+    else if(info->ai_family==AF_INET6) {
+        struct sockaddr_in6* p=(struct sockaddr_in6*)(info->ai_addr);
+        addr->port = htons(p->sin6_port);
+        inet_ntop(p->sin6_family, &p->sin6_addr, addr->ip, sizeof(addr->ip));
+    }
+    else {
+        return -1;
+    }
+    return 0;
+}
+static void *tmp_thread(void *arg)
+{
+    ipaddr_t ipa;
+    int r,fd=-1,err;
+    struct addrinfo hints;
+    struct addrinfo *rp;
+    NTPClient *pc=(NTPClient*)arg;
+    char tmp[32];
+
+    memset(&hints, 0, sizeof hints);
+    hints.ai_family   = AF_UNSPEC;
+    hints.ai_socktype = SOCK_DGRAM;
+    hints.ai_protocol = 0;//IPPROTO_UDP;
+
+    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
+    pthread_testcancel();
+
+    sprintf(tmp, "%d", pc->port);
+    printf("___getaddrinfo in\n");
+    err = getaddrinfo(pc->server, tmp, &hints, &pc->res);
+    if(err){
+        printf("___getaddrinfo from %s failed, %s\n", pc->server, gai_strerror(err));
+        pthread_exit(NULL);
+    }
+    printf("___getaddrinfo out\n");
+
+    for(rp=pc->res; rp; rp=rp->ai_next){
+        get_addr(&ipa, rp);
+        printf("socket to %s:%d ", ipa.ip, ipa.port);
+
+        fd = socket(rp->ai_family, rp->ai_socktype, 0);
+        if (fd>=0) {
+            pc->sockfd = fd;
+            pc->server_addr = *rp->ai_addr;
+            printf("ok!\n");
+            break;
+        }
+        printf("failed!\n");
+    }
+    if(fd>=0) {
+        pc->flag = 1;
+    }
+    else {
+        pc->flag = -1;
+    }
+
+    pthread_exit(NULL);
+}
+NTPClient* createNTPClient(const char* ntp_server, int port, int timeout_sec) {  
     NTPClient* client = (NTPClient*)malloc(sizeof(NTPClient));  
     if (!client) {  
-        perror("malloc failed");  
-        return NULL;  
-    }  
-  
-    // 创建UDP套接字  
-    if ((client->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {  
-        perror("socket creation failed");  
-        free(client);  
-        return NULL;  
-    }  
-  
-    // 设置NTP服务器地址  
-    memset(&client->server_addr, 0, sizeof(client->server_addr));  
-    client->server_addr.sin_family = AF_INET;  
-    client->server_addr.sin_port = htons(port);  
-    if (inet_aton(ntp_server, &client->server_addr.sin_addr) == 0) {  
-        fprintf(stderr, "Invalid address/Address not supported\n");  
-        close(client->sockfd);  
-        free(client);  
+        perror("createNTPClient, malloc failed\n");  
         return NULL;  
-    }  
+    } 
+
+    pthread_t tid;
+    client->server = (char*)ntp_server;
+    client->port = port;
+    client->res = NULL;
+    client->flag = 0;
+    pthread_create(&tid, NULL, tmp_thread, client);
+    for(int i=0; i<timeout_sec; i++) {
+        if(client->flag) {
+            break;
+        }
+        sleep(1);
+    }
+    if(client->flag!=1) {
+        if(client->flag==0) {
+            printf("___getaddrinfo timeout, cancel thread %lu\n", (unsigned long)tid);
+            pthread_cancel(tid);//SIGTERM
+            pthread_join(tid, NULL);
+            printf("___cancel ok!\n");
+        }
+        if(client->res) freeaddrinfo(client->res);
+        free(client); return NULL;
+    }
+    if(client->res) freeaddrinfo(client->res);
+
+    struct timeval tv;
+    tv.tv_sec = timeout_sec;
+    tv.tv_usec = 0;
+    setsockopt(client->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const void*)&tv, sizeof(tv));
+
+    printf("___createNTPClient ok!\n");
   
     return client;  
 }  
@@ -77,7 +165,7 @@ void destroyNTPClient(NTPClient* client) {
 int getCurrentTimeFromNTP(NTPClient* client, time_t* current_time) {  
     if (sendNTPRequest(client) < 0) {  
         return -1;  
-    }  
+    }
   
     if (receiveNTPResponse(client) < 0) {  
         return -1;  

+ 8 - 4
ip/src/ntpclient.h

@@ -13,14 +13,18 @@
     
 #define NTP_PORT 123  
 #define NTP_PACKET_SIZE 48  
-// 定义NTP客户端类  
+
 typedef struct NTPClient_s {  
     int sockfd;  
-    struct sockaddr_in server_addr;  
-    char ntp_packet[NTP_PACKET_SIZE];  
+    struct sockaddr server_addr;  
+    char ntp_packet[NTP_PACKET_SIZE];
+    struct addrinfo *res;
+    int  flag; 
+    char *server;
+    int  port;
 } NTPClient;  
     
-NTPClient* createNTPClient(const char* ntp_server, int port);
+NTPClient* createNTPClient(const char* ntp_server, int port, int timeout_sec);
 
 // 销毁NTP客户端实例  
 void destroyNTPClient(NTPClient* client) ;

+ 1 - 4
ip/src/sqlite_handle.c

@@ -2997,13 +2997,10 @@ int dev_get_ntp_info(sqlite3 *db,NTPManager* _globalNTPInfo)
 
     //获取ID
     _globalNTPInfo->product_id = atoi(pResult[rowIndex*ncolumn+0]); 
-    _globalNTPInfo->mode = atoi(pResult[rowIndex*ncolumn+1]); 
-   _globalNTPInfo->ntpName= malloc(64);
+    _globalNTPInfo->mode = atoi(pResult[rowIndex*ncolumn+1]);
     strcpy(_globalNTPInfo->ntpName,pResult[rowIndex*ncolumn+2]);
-    _globalNTPInfo->ntpaddress= malloc(64);
     strcpy(_globalNTPInfo->ntpaddress ,pResult[rowIndex*ncolumn+3]);
     _globalNTPInfo->port = atoi(pResult[rowIndex*ncolumn+4]); 
-     _globalNTPInfo->time= malloc(64);
     strcpy(_globalNTPInfo->time,pResult[rowIndex*ncolumn+5]);
     _globalNTPInfo->weekday = atoi(pResult[rowIndex*ncolumn+6]); 
     _globalNTPInfo->tzone = atoi(pResult[rowIndex*ncolumn+7]);