alios things IOT_Linkkit_Query查詢時間

在alios things中我們經常需要用到時間,比如在智能插座開發中,開發倒計時或者本地定時功能時就會用到時間,所以這次我們說說使用IOT_Linkkit_Query獲取時間的步驟:

注意:先決條件是要連上阿里雲平臺

一、註冊一個接收時間的回調函數

static void set_time(time_t time)//用於同步本地RTC時鐘
{
    mico_rtc_time_t  set_time;
    struct tm *ptr = localtime( &time );//時間戳轉時間
    set_time.year = ptr->tm_year - 70;
    set_time.month = ptr->tm_mon +1;
    set_time.date  = ptr->tm_mday;

    set_time.hr      = ptr->tm_hour+8;
    set_time.min     = ptr->tm_min;
    set_time.sec     = ptr->tm_sec;
    MicoRtcSetTime( &set_time );//這個是MICO裏面的時間同步,在alios上請用相應的函數
}
static time_t replace(char *str) //這個函數用於把13位的字符串轉成10位的長整型時間戳
{
    int s=0;
    time_t sum=0;
    int len = 10;
    while(len--) //當str[i]不爲\0時執行循環
    {
        s = *str++ - '0';
        sum = sum*10 + s;
    }
    return(sum);
}
static void ntp_reply_handler(char *ntp_offset_time_ms)
{
    time_t ntp_ms = replace(ntp_offset_time_ms);//字符串轉長整型
    set_time(ntp_ms);//同步本地rtc時鐘
}
IOT_RegisterCallback(ITE_TIMESTAMP_REPLY, ntp_reply_handler);//註冊回調函數,用於接收時間

二、使用IOT_Linkkit_Query查詢時間(查到的是13位的時間戳)

IOT_Linkkit_Query(user_example_ctx->master_devid, ITM_MSG_QUERY_TIMESTAMP,NULL, 0);

三、時間戳轉時間

/*struct tm {
   int tm_sec;         // 秒,範圍從 0 到 59
   int tm_min;         // 分,範圍從 0 到 59
   int tm_hour;        // 小時,範圍從 0 到 23
   int tm_mday;        // 一月中的第幾天,範圍從 1 到 31
   int tm_mon;         // 月份,範圍從 0 到 11
   int tm_year;        // 自 1900 起的年數
   int tm_wday;        // 一週中的第幾天,範圍從 0 到 6
   int tm_yday;        // 一年中的第幾天,範圍從 0 到 365
   int tm_isdst;       // 夏令時
};*/
struct tm *ptr = localtime( &time );//參數是10位的長整型數據,返回的是時間結構體

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章