diff --git a/3partys/allwinner/libpv1comm-linux.so b/3partys/allwinner/libpv1comm-linux.so new file mode 100755 index 0000000..84eaf58 Binary files /dev/null and b/3partys/allwinner/libpv1comm-linux.so differ diff --git a/3partys/allwinner/libpv1comm-r16.so b/3partys/allwinner/libpv1comm-r16.so new file mode 100755 index 0000000..521f1a0 Binary files /dev/null and b/3partys/allwinner/libpv1comm-r16.so differ diff --git a/3partys/allwinner/libpv1comm-r311.so b/3partys/allwinner/libpv1comm-r311.so new file mode 100755 index 0000000..044eaed Binary files /dev/null and b/3partys/allwinner/libpv1comm-r311.so differ diff --git a/Example/main.c b/Example/main.c index 5a378ab..0e57a87 100644 --- a/Example/main.c +++ b/Example/main.c @@ -1909,7 +1909,7 @@ void test_nl80211(void) nl_recvmsgs_default(sk); } #endif - +#include int main(int argc, char **argv) { @@ -1922,7 +1922,7 @@ int main(int argc, char **argv) struct tm tm; - + memset(&tm, 0, sizeof(struct tm)); strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm); strftime(buf, sizeof(buf), "%d %b %Y %H:%M", &tm); @@ -2001,6 +2001,7 @@ int main(int argc, char **argv) return 0; } + SetHBLAutoExit(TRUE); //SysPointMarkInit(NULL, -1, -1); //test_task_new(__uvThreadSysPointUpload, NULL); @@ -2202,7 +2203,7 @@ int main(int argc, char **argv) if(modIdx == 18) { SkinInit(); - //SkinIsVerifyRes(TRUE); + SkinIsVerifyRes(TRUE); #if 0 char* path = "/mnt/UDISK/skinupgrade.txt"; char* pUpgCmd = "[{\"createTime\":1517832224000,\"enable\":1,\"id\":170," @@ -2237,8 +2238,9 @@ int main(int argc, char **argv) } #else //const char* GetSkinsResource(const char [in] *pKeyName, int [out] *pResType, int [out] *pVersion, const char [out] **pComeFrom) + //fprintf(stdout, "[v401] = {%s}\n", GetSkinsResource("v401", NULL, NULL, NULL)); +#if 0 - fprintf(stdout, "[v401] = {%s}\n", GetSkinsResource("v401", NULL, NULL, NULL)); fprintf(stdout, "[v109] = {%s}\n", GetSkinsResource("v109", NULL, NULL, NULL)); fprintf(stdout, "[v311] = {%s}\n", GetSkinsResource("v311", NULL, NULL, NULL)); fprintf(stdout, "[v401] = {%s}\n", GetSkinsResource("v401", NULL, NULL, NULL)); @@ -2253,6 +2255,7 @@ int main(int argc, char **argv) fprintf(stdout, "[v401] = {%s}\n", GetSkinsResource("v401", NULL, NULL, NULL)); test_task_new(__uvTestSkin, NULL); +#endif #endif } #endif diff --git a/Framework/Fifo/fifo.c b/Framework/Fifo/fifo.c deleted file mode 100644 index 5fd3753..0000000 --- a/Framework/Fifo/fifo.c +++ /dev/null @@ -1,554 +0,0 @@ -/* - * A generic kernel FIFO implementation - * - * Copyright (C) 2009/2010 Stefani Seibold - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. - * - */ -#if 0 -#include -#include -#include -#include -#include -#include -#include -#endif - -#include -#include -#include -#include - -#include "fifo.h" - -#define is_power_of_2(x) ((x) != 0 && (((x) & ((x) - 1)) == 0)) -#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) -#define min(x,y) ({ \ - typeof(x) _x = (x); \ - typeof(y) _y = (y); \ - (void) (&_x == &_y); \ - _x < _y ? _x : _y; }) - -#define max(x,y) ({ \ - typeof(x) _x = (x); \ - typeof(y) _y = (y); \ - (void) (&_x == &_y); \ - _x > _y ? _x : _y; }) - -//#define EINVAL (1) -//#define ENOMEM (2) - -static inline int fls(int x); - -#if defined(PLATFORM_R16) || defined(PLATFORM_R311) -static inline int constant_fls(int x) -{ - int r = 32; - - if (!x) - return 0; - if (!(x & 0xffff0000u)) { - x <<= 16; - r -= 16; - } - if (!(x & 0xff000000u)) { - x <<= 8; - r -= 8; - } - if (!(x & 0xf0000000u)) { - x <<= 4; - r -= 4; - } - if (!(x & 0xc0000000u)) { - x <<= 2; - r -= 2; - } - if (!(x & 0x80000000u)) { - x <<= 1; - r -= 1; - } - return r; -} - -static int fls64(unsigned long long x) -{ - unsigned int h = x >> 32; - if (h) - return fls(h) + 32; - return fls(x); -} - -static inline int fls(int x) -{ - int ret; - - if (__builtin_constant_p(x)) - return constant_fls(x); - - asm("clz\t%0, %1" : "=r" (ret) : "r" (x)); - ret = 32 - ret; - return ret; -} -#endif - -#ifdef PLATFORM_CPU -#define __fls(x) (fls(x) - 1) -static __always_inline int fls64(unsigned long x) -{ - if (x == 0) - return 0; - return __fls(x) + 1; -} - -static inline int fls(int x) -{ - int r; - - long tmp = -1; - asm("bsrl %1,%0" - : "=r" (r) - : "rm" (x), "0" (tmp)); -#if 0 -#ifdef CONFIG_X86_64 - /* - * AMD64 says BSRL won't clobber the dest reg if x==0; Intel64 says the - * dest reg is undefined if x==0, but their CPU architect says its - * value is written to set it to the same as before, except that the - * top 32 bits will be cleared. - * - * We cannot do this on 32 bits because at the very least some - * 486 CPUs did not behave this way. - */ - long tmp = -1; - asm("bsrl %1,%0" - : "=r" (r) - : "rm" (x), "0" (tmp)); -#elif defined(CONFIG_X86_CMOV) - asm("bsrl %1,%0\n\t" - "cmovzl %2,%0" - : "=&r" (r) : "rm" (x), "rm" (-1)); -#else - asm("bsrl %1,%0\n\t" - "jnz 1f\n\t" - "movl $-1,%0\n" - "1:" : "=r" (r) : "rm" (x)); -#endif -#endif - return r + 1; -} -#endif -/* - * internal helper to calculate the unused elements in a fifo - */ -static inline unsigned int kfifo_unused(struct __kfifo *fifo) -{ - return (fifo->mask + 1) - (fifo->in - fifo->out); -} - -static inline unsigned fls_long(unsigned long l) -{ - if (sizeof(l) == 4) - return fls(l); - return fls64(l); -} - -unsigned long roundup_pow_of_two(unsigned long n) -{ - return 1UL << (fls_long(n)); -} - -int __kfifo_alloc(struct __kfifo *fifo, unsigned int size, unsigned int esize) -{ - /* - * round down to the next power of 2, since our 'let the indices - * wrap' technique works only in this case. - */ - if (!is_power_of_2(size)) - size = roundup_pow_of_two(size); - - fprintf(stdout, "+++++++++++kfifo malloc size = %u\n", size); - - fifo->in = 0; - fifo->out = 0; - fifo->esize = esize; - - if (size < 2) { - fifo->data = NULL; - fifo->mask = 0; - return -EINVAL; - } - - fifo->data = malloc(size * esize); - - if (!fifo->data) { - fifo->mask = 0; - return -ENOMEM; - } - fifo->mask = size - 1; - uv_mutex_init(&fifo->lock); - - return 0; -} - -void __kfifo_free(struct __kfifo *fifo) -{ - free(fifo->data); - fifo->in = 0; - fifo->out = 0; - fifo->esize = 0; - fifo->data = NULL; - fifo->mask = 0; -} - -int __kfifo_init(struct __kfifo *fifo, void *buffer, - unsigned int size, unsigned int esize) -{ - size /= esize; - - if (!is_power_of_2(size)) - size = roundup_pow_of_two(size); - - fifo->in = 0; - fifo->out = 0; - fifo->esize = esize; - fifo->data = buffer; - - if (size < 2) { - fifo->mask = 0; - return -EINVAL; - } - fifo->mask = size - 1; - uv_mutex_init(&fifo->lock); - - return 0; -} - -static void kfifo_copy_in(struct __kfifo *fifo, const void *src, - unsigned int len, unsigned int off) -{ - unsigned int size = fifo->mask + 1; - unsigned int esize = fifo->esize; - unsigned int l; - - off &= fifo->mask; - if (esize != 1) { - off *= esize; - size *= esize; - len *= esize; - } - l = min(len, size - off); - - memcpy(fifo->data + off, src, l); - memcpy(fifo->data, src + l, len - l); - /* - * make sure that the data in the fifo is up to date before - * incrementing the fifo->in index counter - */ -// smp_wmb(); -} - -unsigned int __kfifo_in(struct __kfifo *fifo, - const void *buf, unsigned int len) -{ - unsigned int l; - - l = kfifo_unused(fifo); - if (len > l) - len = l; - - kfifo_copy_in(fifo, buf, len, fifo->in); - fifo->in += len; - return len; -} - -static void kfifo_copy_out(struct __kfifo *fifo, void *dst, - unsigned int len, unsigned int off) -{ - unsigned int size = fifo->mask + 1; - unsigned int esize = fifo->esize; - unsigned int l; - - off &= fifo->mask; - if (esize != 1) { - off *= esize; - size *= esize; - len *= esize; - } - l = min(len, size - off); - - if (dst) { - memcpy(dst, fifo->data + off, l); - memcpy(dst + l, fifo->data, len - l); - } - /* - * make sure that the data is copied before - * incrementing the fifo->out index counter - */ -// smp_wmb(); -} - -unsigned int __kfifo_out_peek(struct __kfifo *fifo, - void *buf, unsigned int len) -{ - unsigned int l; - - l = fifo->in - fifo->out; - if (len > l) - len = l; - - kfifo_copy_out(fifo, buf, len, fifo->out); - return len; -} - -unsigned int __kfifo_out(struct __kfifo *fifo, - void *buf, unsigned int len) -{ - len = __kfifo_out_peek(fifo, buf, len); - fifo->out += len; - return len; -} - -#if 0 -static unsigned long kfifo_copy_from_user(struct __kfifo *fifo, - const void *from, unsigned int len, unsigned int off, - unsigned int *copied) -{ - unsigned int size = fifo->mask + 1; - unsigned int esize = fifo->esize; - unsigned int l; - unsigned long ret; - - off &= fifo->mask; - if (esize != 1) { - off *= esize; - size *= esize; - len *= esize; - } - l = min(len, size - off); - - ret = memcpy(fifo->data + off, from, l); - if (unlikely(ret)) - ret = DIV_ROUND_UP(ret + len - l, esize); - else { - ret = memcpy(fifo->data, from + l, len - l); - if (unlikely(ret)) - ret = DIV_ROUND_UP(ret, esize); - } - /* - * make sure that the data in the fifo is up to date before - * incrementing the fifo->in index counter - */ -// smp_wmb(); - *copied = len - ret; - /* return the number of elements which are not copied */ - return ret; -} - -int __kfifo_from_user(struct __kfifo *fifo, const void __user *from, - unsigned long len, unsigned int *copied) -{ - unsigned int l; - unsigned long ret; - unsigned int esize = fifo->esize; - int err; - - if (esize != 1) - len /= esize; - - l = kfifo_unused(fifo); - if (len > l) - len = l; - - ret = kfifo_copy_from_user(fifo, from, len, fifo->in, copied); - if (unlikely(ret)) { - len -= ret; - err = -EFAULT; - } else - err = 0; - fifo->in += len; - return err; -} - -static unsigned long kfifo_copy_to_user(struct __kfifo *fifo, void __user *to, - unsigned int len, unsigned int off, unsigned int *copied) -{ - unsigned int l; - unsigned long ret; - unsigned int size = fifo->mask + 1; - unsigned int esize = fifo->esize; - - off &= fifo->mask; - if (esize != 1) { - off *= esize; - size *= esize; - len *= esize; - } - l = min(len, size - off); - - ret = memcpy(to, fifo->data + off, l); - if (unlikely(ret)) - ret = DIV_ROUND_UP(ret + len - l, esize); - else { - ret = memcpy(to + l, fifo->data, len - l); - if (unlikely(ret)) - ret = DIV_ROUND_UP(ret, esize); - } - /* - * make sure that the data is copied before - * incrementing the fifo->out index counter - */ - //smp_wmb(); - *copied = len - ret; - /* return the number of elements which are not copied */ - return ret; -} - -int __kfifo_to_user(struct __kfifo *fifo, void __user *to, - unsigned long len, unsigned int *copied) -{ - unsigned int l; - unsigned long ret; - unsigned int esize = fifo->esize; - int err; - - if (esize != 1) - len /= esize; - - l = fifo->in - fifo->out; - if (len > l) - len = l; - ret = kfifo_copy_to_user(fifo, to, len, fifo->out, copied); - if (unlikely(ret)) { - len -= ret; - err = -EFAULT; - } else - err = 0; - fifo->out += len; - return err; -} -#endif - -unsigned int __kfifo_max_r(unsigned int len, unsigned int recsize) -{ - unsigned int max = (1 << (recsize << 3)) - 1; - - if (len > max) - return max; - return len; -} - -#define __KFIFO_PEEK(data, out, mask) \ - ((data)[(out) & (mask)]) -/* - * __kfifo_peek_n internal helper function for determinate the length of - * the next record in the fifo - */ -static unsigned int __kfifo_peek_n(struct __kfifo *fifo, unsigned int recsize) -{ - unsigned int l; - unsigned int mask = fifo->mask; - unsigned char *data = fifo->data; - - l = __KFIFO_PEEK(data, fifo->out, mask); - - if (--recsize) - l |= __KFIFO_PEEK(data, fifo->out + 1, mask) << 8; - - return l; -} - -#define __KFIFO_POKE(data, in, mask, val) \ - ( \ - (data)[(in) & (mask)] = (unsigned char)(val) \ - ) - -/* - * __kfifo_poke_n internal helper function for storeing the length of - * the record into the fifo - */ -static void __kfifo_poke_n(struct __kfifo *fifo, unsigned int n, unsigned int recsize) -{ - unsigned int mask = fifo->mask; - unsigned char *data = fifo->data; - - __KFIFO_POKE(data, fifo->in, mask, n); - - if (recsize > 1) - __KFIFO_POKE(data, fifo->in + 1, mask, n >> 8); -} - -unsigned int __kfifo_len_r(struct __kfifo *fifo, unsigned int recsize) -{ - return __kfifo_peek_n(fifo, recsize); -} - -unsigned int __kfifo_in_r(struct __kfifo *fifo, const void *buf, - unsigned int len, unsigned int recsize) -{ - if (len + recsize > kfifo_unused(fifo)) - return 0; - - __kfifo_poke_n(fifo, len, recsize); - - kfifo_copy_in(fifo, buf, len, fifo->in + recsize); - fifo->in += len + recsize; - return len; -} - -static unsigned int kfifo_out_copy_r(struct __kfifo *fifo, - void *buf, unsigned int len, unsigned int recsize, unsigned int *n) -{ - *n = __kfifo_peek_n(fifo, recsize); - - if (len > *n) - len = *n; - - kfifo_copy_out(fifo, buf, len, fifo->out + recsize); - return len; -} - -unsigned int __kfifo_out_peek_r(struct __kfifo *fifo, void *buf, - unsigned int len, unsigned int recsize) -{ - unsigned int n; - - if (fifo->in == fifo->out) - return 0; - - return kfifo_out_copy_r(fifo, buf, len, recsize, &n); -} - -unsigned int __kfifo_out_r(struct __kfifo *fifo, void *buf, - unsigned int len, unsigned int recsize) -{ - unsigned int n; - - if (fifo->in == fifo->out) - return 0; - - len = kfifo_out_copy_r(fifo, buf, len, recsize, &n); - fifo->out += n + recsize; - return len; -} - -void __kfifo_skip_r(struct __kfifo *fifo, unsigned int recsize) -{ - unsigned int n; - - n = __kfifo_peek_n(fifo, recsize); - fifo->out += n + recsize; -} diff --git a/Framework/Network/inet_api.c b/Framework/Network/inet_api.c deleted file mode 100644 index ee3a9db..0000000 --- a/Framework/Network/inet_api.c +++ /dev/null @@ -1,1396 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "inet_api.h" - -#define MAX_TIMEOUT_VALUE (10) -#define SSL_CA_FILE ("/etc/ssl/certs/ca-certificates.crt") - -typedef enum -{ - INET_HTTP_DOWNLOAD_FILE = 0, - INET_HTTP_WEBSERVICE_POST, -} INET_ACCESS_TYPE; - -typedef struct -{ - uv_poll_t uvPool; - curl_socket_t sock; -} CURL_CONTEXT_DATA, *PCURL_CONTEXT_DATA; - -typedef struct -{ - char* pReqUrl; - char sPath[MAX_PATH]; - char sDlPath[MAX_PATH]; - char* pTaskUuid; - INET_ACCESS_TYPE type; - unsigned int dlSize; - unsigned int lastTm; - unsigned int createTm; - uv_fs_t uvFsOpen; - uv_fs_t uvFsWrite; - uv_fs_t uvFsDataSync; - uv_fs_t uvFsClose; - uv_buf_t uvFsBuf; - OnProgressNotify onPrgCb; - OnHttpResponse onRspCb; - int isCancel; - CURL* pCurl; - void* pData; - int errCode; -} HTTP_REQ_PARAMS, *PHTTP_REQ_PARAMS; - -typedef struct -{ - char *pTaskUuid; - unsigned int uRetryTimes; - PHTTP_REQ_PARAMS pCurlItem; - - UT_hash_handle hh; ///< UT Hash handle -} CURL_HANDLE_TBL, *PCURL_HANDLE_TBL; - -static uv_timer_t g_uvCurlTm; -static uv_timer_t g_uvDlTm; -static CURLM* g_pCurl = NULL; -static uv_loop_t* g_pMainLoop = NULL; -static PCURL_HANDLE_TBL g_ReqHandleTbl = NULL; -static uv_rwlock_t g_uvHashRwLock; -static unsigned g_TotalDownloads = 0; - -static void __addReqIdToTable(const char* pTaskUuid, PHTTP_REQ_PARAMS pParams) -{ - PCURL_HANDLE_TBL pItem = NULL; - - HASH_FIND_STR(g_ReqHandleTbl, pTaskUuid, pItem); - - if(pItem == NULL) - { - pItem = (PCURL_HANDLE_TBL)malloc(sizeof(CURL_HANDLE_TBL)); - - memset(pItem, 0, sizeof(CURL_HANDLE_TBL)); - pItem->pTaskUuid = (char*)pTaskUuid; - - uv_rwlock_wrlock(&g_uvHashRwLock); - HASH_ADD_STR(g_ReqHandleTbl, pTaskUuid, pItem); - uv_rwlock_wrunlock(&g_uvHashRwLock); - } - - pItem->pCurlItem = pParams; - pItem->uRetryTimes++; -} - -static void __removeReqIdFromTable(const char* pTaskUuid) -{ - PCURL_HANDLE_TBL pItem = NULL; - - uv_rwlock_wrlock(&g_uvHashRwLock); - HASH_FIND_STR(g_ReqHandleTbl, pTaskUuid, pItem); - if(pItem != NULL) - { - HASH_DEL(g_ReqHandleTbl, pItem); - - if(pItem->pTaskUuid) - { - free(pItem->pTaskUuid); - } - - free(pItem); - } - uv_rwlock_wrunlock(&g_uvHashRwLock); -} - -static void __cancelDownloadTask(PHTTP_REQ_PARAMS pItem) -{ - if(pItem) - { - pItem->isCancel = TRUE; - } -} - -static void __uvFsCloseCb(uv_fs_t *puvFs) -{ - PHTTP_REQ_PARAMS pParams = (PHTTP_REQ_PARAMS)puvFs->data; - - if(puvFs->result < 0) - { - LOG_EX(LOG_Error, "[%s] Error: %d\n", __FUNCTION__, puvFs->result); - } - - uv_fs_req_cleanup(puvFs); - - if(pParams->type == INET_HTTP_DOWNLOAD_FILE) - { - if(strcmp(pParams->sDlPath, pParams->sPath) != 0) - { - CopyFile(pParams->sDlPath, pParams->sPath); - unlink(pParams->sDlPath); - } - - if(pParams->errCode == CURLE_ABORTED_BY_CALLBACK) - { - pParams->errCode = CURLE_OPERATION_TIMEDOUT; - } - - if(pParams->onRspCb && pParams->isCancel == FALSE) - { - pParams->onRspCb(NULL, pParams->dlSize, pParams->pReqUrl, pParams->sPath, - pParams->pTaskUuid, -pParams->errCode, pParams->pData); - } - } - - __removeReqIdFromTable(pParams->pTaskUuid); - - if(pParams->pReqUrl) - { - free(pParams->pReqUrl); - pParams->pReqUrl = NULL; - } - - free(pParams); - pParams = NULL; -} - -static void __uvFsDataSyncCb(uv_fs_t *puvFs) -{ - PHTTP_REQ_PARAMS pParams = (PHTTP_REQ_PARAMS)puvFs->data; - - if(puvFs->result < 0) - { - LOG_EX(LOG_Error, "[%s] Error: %d\n", __FUNCTION__, puvFs->result); - } - - uv_fs_req_cleanup(puvFs); - - uv_fs_close(g_pMainLoop, &pParams->uvFsClose, pParams->uvFsOpen.result, __uvFsCloseCb); -} - -static PCURL_CONTEXT_DATA __createCurlContext(curl_socket_t sock) -{ - PCURL_CONTEXT_DATA pContext = (PCURL_CONTEXT_DATA)malloc(sizeof(CURL_CONTEXT_DATA)); - - pContext->sock = sock; - - if(uv_poll_init_socket(g_pMainLoop, &pContext->uvPool, sock) != 0) - { - LOG_EX(LOG_Error, "uv_poll_init_socket Error\n"); - } - - pContext->uvPool.data = pContext; - - return (pContext); -} - -static void __uvCloseCb(uv_handle_t *puvPoll) -{ - PCURL_CONTEXT_DATA pContext = (PCURL_CONTEXT_DATA)puvPoll->data; - free(pContext); -} - -static void __destoryCurlContext(PCURL_CONTEXT_DATA pContext) -{ - uv_close((uv_handle_t *)&pContext->uvPool, __uvCloseCb); -} - -static void __checkMultiInfoTimeout(void) -{ - PHTTP_REQ_PARAMS pReq; - CURLMsg *pMsg = NULL; - int iPending; - - while((pMsg = curl_multi_info_read(g_pCurl, &iPending))) - { - switch(pMsg->msg) - { - case CURLMSG_DONE: - curl_easy_getinfo(pMsg->easy_handle, CURLINFO_PRIVATE, (void*)&pReq); - - LOG_EX(LOG_Debug, "Cleanup CURL: %p\n", pMsg->easy_handle); - - curl_multi_remove_handle(g_pCurl, pMsg->easy_handle); - curl_easy_cleanup(pMsg->easy_handle); - - if(pReq) - { - if(pReq->type == INET_HTTP_DOWNLOAD_FILE) - { - uv_fs_close(g_pMainLoop, &pReq->uvFsDataSync, pReq->uvFsOpen.result, NULL); - } - - if(pReq->onRspCb && pReq->isCancel == FALSE) - { - pReq->onRspCb(NULL, 0, pReq->pReqUrl, pReq->sPath, pReq->pTaskUuid, - -CURLE_OPERATION_TIMEDOUT, pReq->pData); - } - - if(pReq->pReqUrl) - { - free(pReq->pReqUrl); - pReq->pReqUrl = NULL; - } - - __removeReqIdFromTable(pReq->pTaskUuid); - - free(pReq); - pReq = NULL; - } - - break; - - default: - LOG_EX(LOG_Error, "pMsg->msg(%d) != CURLMSG_DONE\n", pMsg->msg); - return; - } - } -} - -static void __checkMultiInfo(void) -{ - PHTTP_REQ_PARAMS pReq; - CURLMsg *pMsg = NULL; - int iPending; - - while((pMsg = curl_multi_info_read(g_pCurl, &iPending))) - { - switch(pMsg->msg) - { - case CURLMSG_DONE: - curl_easy_getinfo(pMsg->easy_handle, CURLINFO_PRIVATE, (void*)&pReq); - - curl_multi_remove_handle(g_pCurl, pMsg->easy_handle); - LOG_EX(LOG_Debug, "Cleanup CURL: %p\n", pMsg->easy_handle); - curl_easy_cleanup(pMsg->easy_handle); - - if(pReq) - { - if(pReq->type == INET_HTTP_DOWNLOAD_FILE) - { - if(pMsg->data.result != CURLE_OK) - { - pReq->errCode = pMsg->data.result; - } - else - { - pReq->errCode = 0; - } - - uv_fs_fdatasync(g_pMainLoop, &pReq->uvFsDataSync, pReq->uvFsOpen.result, __uvFsDataSyncCb); - } - else if(pReq->type == INET_HTTP_WEBSERVICE_POST) - { - if(pMsg->data.result != CURLE_OK) - { - if(pReq->onRspCb && pReq->isCancel == FALSE) - { - pReq->onRspCb(pReq->uvFsBuf.base, pReq->dlSize, pReq->pReqUrl, pReq->sPath, - pReq->pTaskUuid, -pMsg->data.result, pReq->pData); - } - } - else - { - if(pReq->onRspCb && pReq->isCancel == FALSE) - { - pReq->onRspCb(pReq->uvFsBuf.base, pReq->dlSize, pReq->pReqUrl, pReq->sPath, - pReq->pTaskUuid, 0, pReq->pData); - } - } - - if(pReq->uvFsBuf.base) - { - free(pReq->uvFsBuf.base); - } - - if(pReq->pReqUrl) - { - free(pReq->pReqUrl); - pReq->pReqUrl = NULL; - } - - __removeReqIdFromTable(pReq->pTaskUuid); - - free(pReq); - pReq = NULL; - } - else - { - if(pMsg->data.result != CURLE_OK) - { - if(pReq->onRspCb && pReq->isCancel == FALSE){ - pReq->onRspCb(NULL, 0, pReq->pReqUrl, pReq->sPath, pReq->pTaskUuid, -pMsg->data.result, pReq->pData); - } - } - else - { - if(pReq->onRspCb && pReq->isCancel == FALSE) - { - pReq->onRspCb(NULL, 0, pReq->pReqUrl, pReq->sPath, pReq->pTaskUuid, 0, pReq->pData); - } - } - - if(pReq->pReqUrl) - { - free(pReq->pReqUrl); - pReq->pReqUrl = NULL; - } - - __removeReqIdFromTable(pReq->pTaskUuid); - - free(pReq); - pReq = NULL; - } - } - - break; - - default: - LOG_EX(LOG_Error, "pMsg->msg(%d) != CURLMSG_DONE\n", pMsg->msg); - return; - } - } -} - -static void __onDlTmoutCb(uv_timer_t *pufTimer) -{ - PCURL_HANDLE_TBL pItem = NULL, pTemp = NULL; - unsigned int curTm = (unsigned int)LIBUV_CURRENT_TIME_S(); - - HASH_ITER(hh, g_ReqHandleTbl, pItem, pTemp) - { - int dlTime; - - if(pItem->pCurlItem->isCancel) - { - continue; - } - - dlTime = curTm - pItem->pCurlItem->createTm; - - // 下载时间大于10s且平均下载速度小于10K/s超时 - if((dlTime * 10000 > pItem->pCurlItem->dlSize) && dlTime > 10) - { - LOG_EX(LOG_Error, "Download Speed less than 10k/s: %s (%uK/%ds)\n", - pItem->pTaskUuid, pItem->pCurlItem->dlSize / 1000, dlTime); - - __cancelDownloadTask(pItem->pCurlItem); - if(pItem->pCurlItem->onRspCb) - { - pItem->pCurlItem->onRspCb(NULL, - pItem->pCurlItem->dlSize, - pItem->pCurlItem->pReqUrl, - pItem->pCurlItem->sPath, - pItem->pCurlItem->pTaskUuid, - -CURLE_OPERATION_TIMEDOUT, - pItem->pCurlItem->pData); - } - break; - } - - // 10秒内没有下载任何数据超时 - if(pItem->pCurlItem->lastTm > 0) - { - if(curTm > pItem->pCurlItem->lastTm + MAX_TIMEOUT_VALUE) - { - LOG_EX(LOG_Error, "Download Timeout: %s\n", pItem->pTaskUuid); - __cancelDownloadTask(pItem->pCurlItem); - if(pItem->pCurlItem->onRspCb) - { - pItem->pCurlItem->onRspCb(NULL, - pItem->pCurlItem->dlSize, - pItem->pCurlItem->pReqUrl, - pItem->pCurlItem->sPath, - pItem->pCurlItem->pTaskUuid, - -CURLE_OPERATION_TIMEDOUT, - pItem->pCurlItem->pData); - } - break; - } - } - - // 下载最长时间设置为1800秒(30分钟) - if(dlTime > 1800) - { - LOG_EX(LOG_Error, "Download More than 1800 seconds: %s (%uK/%ds)\n", - pItem->pTaskUuid, pItem->pCurlItem->dlSize/1000, dlTime); - __cancelDownloadTask(pItem->pCurlItem); - if(pItem->pCurlItem->onRspCb) - { - pItem->pCurlItem->onRspCb(NULL, - pItem->pCurlItem->dlSize, - pItem->pCurlItem->pReqUrl, - pItem->pCurlItem->sPath, - pItem->pCurlItem->pTaskUuid, - -CURLE_OPERATION_TIMEDOUT, - pItem->pCurlItem->pData); - } - break; - } - } -} - -static void __onTimeoutCb(uv_timer_t *pufTimer) -{ - int iRun; - - curl_multi_socket_action(g_pCurl, CURL_SOCKET_TIMEOUT, 0, &iRun); - - __checkMultiInfoTimeout(); -} - -static int __curlTimerCb(CURLM *multi, /* multi handle */ - long timeout_ms, /* see above */ - void *userp) /* private callback pointer */ -{ - if(timeout_ms <= 0) - { - timeout_ms = 1; - } - - uv_timer_start(&g_uvCurlTm, __onTimeoutCb, timeout_ms, 0); - - return 0; -} - -static void __curlPollCb(uv_poll_t *pPoll, int status, int events) -{ - int iRun; - int flags; - PCURL_CONTEXT_DATA pContext = NULL; - - uv_timer_stop(&g_uvCurlTm); - - if(events & UV_READABLE) - { - flags = CURL_CSELECT_IN; - } - else if(events & UV_WRITABLE) - { - flags = CURL_CSELECT_OUT; - } - - pContext = (PCURL_CONTEXT_DATA)pPoll; - curl_multi_socket_action(g_pCurl, pContext->sock, flags, &iRun); - __checkMultiInfo(); -} - -static int __curlSockCb(CURL *easy, /* easy handle */ - curl_socket_t s, /* socket */ - int what, /* describes the socket */ - void *userp, /* private callback pointer */ - void *socketp) /* private socket pointer */ -{ - PCURL_CONTEXT_DATA pContext = NULL; - - if(what == CURL_POLL_IN || what == CURL_POLL_OUT) - { - if(socketp) - { - pContext = (PCURL_CONTEXT_DATA)socketp; - } - else - { - pContext = __createCurlContext(s); - } - - curl_multi_assign(g_pCurl, s, (void *)pContext); - } - - switch(what) - { - case CURL_POLL_IN: - uv_poll_start(&pContext->uvPool, UV_READABLE, __curlPollCb); - break; - - case CURL_POLL_OUT: - uv_poll_start(&pContext->uvPool, UV_WRITABLE, __curlPollCb); - break; - - case CURL_POLL_REMOVE: - if(socketp) - { - uv_poll_stop(&((PCURL_CONTEXT_DATA)socketp)->uvPool); - __destoryCurlContext((PCURL_CONTEXT_DATA)socketp); - curl_multi_assign(g_pCurl, s, NULL); - } - break; - - default: - return (0); - } - - return (0); -} - -static size_t __writeDataCb(void *pData, size_t size, size_t nmemb, void *pParams) -{ - PHTTP_REQ_PARAMS pReq = (PHTTP_REQ_PARAMS)pParams; - int iMemSize = size * nmemb; - - //print_hex_dump_bytes("OTA", DUMP_PREFIX_ADDRESS, pData, size * nmemb); - - if(pReq->isCancel) - { - return 0; - } - - pReq->lastTm = LIBUV_CURRENT_TIME_S(); - - if(pReq->type == INET_HTTP_DOWNLOAD_FILE) - { - int wr = 0; - - pReq->uvFsBuf = uv_buf_init(pData, iMemSize); - - wr = uv_fs_write(g_pMainLoop, &pReq->uvFsWrite, pReq->uvFsOpen.result, &pReq->uvFsBuf, 1, -1, NULL); - - if(wr > 0) - { - pReq->dlSize += wr; - } - } - else if(pReq->type == INET_HTTP_WEBSERVICE_POST) - { - int newSize = 0; - - if(pReq->uvFsBuf.base == NULL && pReq->uvFsBuf.len == 0) - { - newSize = iMemSize + 1; - //fprintf(stdout, "size = %d, newsize = %d, dlsize = %d\n", iMemSize, newSize, pReq->dlSize); - pReq->uvFsBuf.base = malloc(newSize); - memcpy(pReq->uvFsBuf.base, pData, iMemSize); - } - else - { - newSize = pReq->dlSize + iMemSize + 1; - //fprintf(stdout, "::size = %d, newsize = %d, dlsize = %d\n", iMemSize, newSize, pReq->dlSize); - pReq->uvFsBuf.base = realloc(pReq->uvFsBuf.base, newSize); - memcpy(pReq->uvFsBuf.base + pReq->dlSize, pData, iMemSize); - } - - pReq->uvFsBuf.base[pReq->dlSize] = 0; - pReq->dlSize += iMemSize; - } - - return (size * nmemb); -} - -static int __progressCb(void* pData, - double total, - double now, - double ultotal, - double ulnow) -{ - PHTTP_REQ_PARAMS pParams = (PHTTP_REQ_PARAMS)pData; - - if(pParams->onPrgCb) - { - if(pParams->type == INET_HTTP_DOWNLOAD_FILE) - { - pParams->onPrgCb(pParams->pReqUrl, pParams->pTaskUuid, (unsigned char)(now * 100.0 / total), pParams->pData); - } - } - - if(pParams->isCancel) - { - LOG_EX(LOG_Debug, "Cancel Download: %s\n", pParams->pTaskUuid); - return (-CURLE_OPERATION_TIMEDOUT); - } - - return (0); -} - -static size_t __getRemoteSizeCb(void *pData, size_t size, size_t nmemb, void *pParams) -{ - return (size * nmemb); -} - -static int __iNetGetRemoteSize(const char* pURL, unsigned int reqId) -{ - double size = 0.0; - CURL *pCurl = curl_easy_init(); - CURLcode res; - - curl_easy_setopt(pCurl, CURLOPT_URL, pURL); - curl_easy_setopt(pCurl, CURLOPT_NOBODY, 1L); - curl_easy_setopt(pCurl, CURLOPT_HEADERFUNCTION, __getRemoteSizeCb); - curl_easy_setopt(pCurl, CURLOPT_FOLLOWLOCATION, 1L); - - curl_easy_perform(pCurl); - - res = curl_easy_getinfo(pCurl, CURLINFO_CONTENT_LENGTH_DOWNLOAD, &size); - - if(res != CURLE_OK) - { - return (-1); - } - - curl_easy_cleanup(pCurl); - - return (int)(size); -} - -#if 0 -static const char* __restartDlFileAsync(PHTTP_REQ_PARAMS pParams) -{ - CURL *pCurl = curl_easy_init(); - - pParams->type = INET_HTTP_DOWNLOAD_FILE; - pParams->dlSize = 0; - pParams->pCurl = pCurl; - pParams->lastTm = 0; - - uv_fs_open(g_pMainLoop, - &pParams->uvFsOpen, - pParams->sDlPath, - O_RDWR | O_CREAT | O_TRUNC, - S_IRUSR | S_IWUSR, - NULL); - - curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, __writeDataCb); - curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, pParams); - curl_easy_setopt(pCurl, CURLOPT_PRIVATE, pParams); - curl_easy_setopt(pCurl, CURLOPT_URL, pParams->pReqUrl); - - curl_easy_setopt(pCurl, CURLOPT_NOPROGRESS, 0L); - curl_easy_setopt(pCurl, CURLOPT_PROGRESSFUNCTION, __progressCb); - curl_easy_setopt(pCurl, CURLOPT_PROGRESSDATA, pParams); - - curl_easy_setopt(pCurl, CURLOPT_LOW_SPEED_LIMIT, 10000L); // 10K bytes - curl_easy_setopt(pCurl, CURLOPT_LOW_SPEED_TIME, 10L); // 30 seconds - - curl_easy_setopt(pCurl, CURLOPT_CONNECTTIMEOUT, 10L); - -#ifdef SKIP_PEER_VERIFICATION - /* - * If you want to connect to a site who isn't using a certificate that is - * signed by one of the certs in the CA bundle you have, you can skip the - * verification of the server's certificate. This makes the connection - * A LOT LESS SECURE. - * - * If you have a CA cert for the server stored someplace else than in the - * default bundle, then the CURLOPT_CAPATH option might come handy for - * you. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 0L); -#else - curl_easy_setopt(pCurl, CURLOPT_CAINFO, SSL_CA_FILE); - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 1L); -#endif - -#ifdef SKIP_HOSTNAME_VERIFICATION - /* - * If the site you're connecting to uses a different host name that what - * they have mentioned in their server certificate's commonName (or - * subjectAltName) fields, libcurl will refuse to connect. You can skip - * this check, but this will make the connection less secure. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYHOST, 0L); -#endif - - //LOG_EX(LOG_Debug, "Total Size = %d\n", __iNetGetRemoteSize(pURL, 0)); - - curl_multi_add_handle(g_pCurl, pCurl); - - __addReqIdToTable(pParams->pTaskUuid, pCurl); - - return (pParams->pTaskUuid); -} -#endif - -const char* InetHttpDlFileAsync(const char *pURL, - const char *pPath, - OnHttpResponse onRespCb, - OnProgressNotify onProgressCb, - void* pData) -{ - CURLMcode ret; - uuid_t msgId; - char strMsgId[64]; - PHTTP_REQ_PARAMS pParams = NULL; - CURL *pCurl = NULL; - unsigned long long uMemFreeSize = GetPartitionFreeSize("/tmp/"); - - if(pURL == NULL || strlen(pURL) == 0 || onRespCb == NULL) - { - free(pParams); - return (NULL); - } - - LOG_EX(LOG_Debug, "Begin Download: %s --> %s\n", pURL, pPath); - - pParams = (PHTTP_REQ_PARAMS)malloc(sizeof(HTTP_REQ_PARAMS)); - - memset(pParams, 0, sizeof(HTTP_REQ_PARAMS)); - - pCurl = curl_easy_init(); - - pParams->onRspCb = onRespCb; - pParams->pReqUrl = (char *)malloc(strlen(pURL) + 1); - pParams->type = INET_HTTP_DOWNLOAD_FILE; - pParams->dlSize = 0; - pParams->onPrgCb = onProgressCb; - pParams->pData = pData; - pParams->pCurl = pCurl; - pParams->lastTm = 0; - pParams->isCancel = FALSE; - pParams->createTm = (unsigned int)LIBUV_CURRENT_TIME_S(); - - memset(pParams->pReqUrl, 0, strlen(pURL) + 1); - strcpy(pParams->pReqUrl, pURL); - - uuid_generate_random(msgId); - memset(strMsgId, 0, 64); - uuid_unparse_lower(msgId, strMsgId); - pParams->pTaskUuid = strdup(strMsgId); - - if(pPath == NULL) - { - sprintf(pParams->sPath, "./%s", basename_v2(pURL)); - } - else - { - strcpy(pParams->sPath, pPath); - } - - // Memory Free More Than 100M, Download Temp File To Memory - if(uMemFreeSize >= 100 * 1024 * 1024 && - strncmp(pParams->sPath, "/tmp/", 5) != 0) - { - int ret = system("mkdir /tmp/dl -p"); - sprintf(pParams->sDlPath, "/tmp/dl/%s_%s.dl", basename_v2(pParams->sPath), pParams->pTaskUuid); - } - else - { - strcpy(pParams->sDlPath, pParams->sPath); - } - - pParams->uvFsDataSync.data = pParams; - pParams->uvFsClose.data = pParams; - - uv_fs_open(g_pMainLoop, - &pParams->uvFsOpen, - pParams->sDlPath, - O_RDWR | O_CREAT | O_TRUNC, - S_IRUSR | S_IWUSR, - NULL); - - curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, __writeDataCb); - curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, pParams); - curl_easy_setopt(pCurl, CURLOPT_PRIVATE, pParams); - curl_easy_setopt(pCurl, CURLOPT_URL, pURL); - - curl_easy_setopt(pCurl, CURLOPT_NOPROGRESS, 0L); - curl_easy_setopt(pCurl, CURLOPT_PROGRESSFUNCTION, __progressCb); - curl_easy_setopt(pCurl, CURLOPT_PROGRESSDATA, pParams); - - //curl_easy_setopt(pCurl, CURLOPT_TIMEOUT, 1800L); // Max download times (30 minutes)1800s - curl_easy_setopt(pCurl, CURLOPT_LOW_SPEED_LIMIT, 10000L); // 10K bytes - curl_easy_setopt(pCurl, CURLOPT_LOW_SPEED_TIME, 10L); // 30 seconds - - curl_easy_setopt(pCurl, CURLOPT_CONNECTTIMEOUT, 10L); - //curl_easy_setopt(pCurl, CURLOPT_CONNECTTIMEOUT_MS, 10L); - - - //curl_easy_setopt(pCurl, CURLOPT_VERBOSE, 1L); - -#ifdef SKIP_PEER_VERIFICATION - /* - * If you want to connect to a site who isn't using a certificate that is - * signed by one of the certs in the CA bundle you have, you can skip the - * verification of the server's certificate. This makes the connection - * A LOT LESS SECURE. - * - * If you have a CA cert for the server stored someplace else than in the - * default bundle, then the CURLOPT_CAPATH option might come handy for - * you. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 0L); -#else - curl_easy_setopt(pCurl, CURLOPT_CAINFO, SSL_CA_FILE); - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 1L); -#endif - -#ifdef SKIP_HOSTNAME_VERIFICATION - /* - * If the site you're connecting to uses a different host name that what - * they have mentioned in their server certificate's commonName (or - * subjectAltName) fields, libcurl will refuse to connect. You can skip - * this check, but this will make the connection less secure. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYHOST, 0L); -#endif - - LOG_EX(LOG_Debug, "Download(%u): %s --> %p\n", g_TotalDownloads++, pParams->pTaskUuid, pCurl); - ret = curl_multi_add_handle(g_pCurl, pCurl); - if(ret == CURLE_OK) - { - __addReqIdToTable(pParams->pTaskUuid, pParams); - return (pParams->pTaskUuid); - } - else - { - free(pParams->pTaskUuid); - LOG_EX(LOG_Error, "Add Handle Error: %d\n", ret); - return NULL; - } -} - -int InetCancelDownload(const char *pTaskUuid) -{ - if(pTaskUuid && strlen(pTaskUuid) > 0) - { - PCURL_HANDLE_TBL pItem = NULL; - - HASH_FIND_STR(g_ReqHandleTbl, pTaskUuid, pItem); - - if(pItem != NULL && pItem->pCurlItem->isCancel != TRUE) - { - __cancelDownloadTask(pItem->pCurlItem); - if(pItem->pCurlItem->onRspCb) - { - pItem->pCurlItem->onRspCb(NULL, - pItem->pCurlItem->dlSize, - pItem->pCurlItem->pReqUrl, - pItem->pCurlItem->sPath, - pItem->pCurlItem->pTaskUuid, - -CURLE_OPERATION_TIMEDOUT, - pItem->pCurlItem->pData); - } - } - } - - return (0); -} - -static size_t __uploadCb(char *d, size_t n, size_t l, void *p) -{ - return n*l; -} - -#ifdef LIBCURL_DEBUG -struct data { - char trace_ascii; /* 1 or 0 */ -}; - -static -void dump(const char *text, - FILE *stream, unsigned char *ptr, size_t size, - char nohex) -{ - size_t i; - size_t c; - - unsigned int width = 0x10; - - if(nohex) - /* without the hex output, we can fit more on screen */ - width = 0x40; - - fprintf(stream, "%s, %10.10ld bytes (0x%8.8lx)\n", - text, (long)size, (long)size); - - for(i = 0; i= 0x20) && (ptr[i + c]<0x80)?ptr[i + c]:'.'); - /* check again for 0D0A, to avoid an extra \n if it's at width */ - if(nohex && (i + c + 2 < size) && ptr[i + c + 1] == 0x0D && - ptr[i + c + 2] == 0x0A) { - i += (c + 3 - width); - break; - } - } - fputc('\n', stream); /* newline */ - } - fflush(stream); -} - -static -int my_trace(CURL *handle, curl_infotype type, - char *data, size_t size, - void *userp) -{ - struct data *config = (struct data *)userp; - const char *text; - (void)handle; /* prevent compiler warning */ - - switch(type) { - case CURLINFO_TEXT: - fprintf(stderr, "== Info: %s", data); - /* FALLTHROUGH */ - default: /* in case a new one is introduced to shock us */ - return 0; - - case CURLINFO_HEADER_OUT: - text = "=> Send header"; - break; - case CURLINFO_DATA_OUT: - text = "=> Send data"; - break; - case CURLINFO_SSL_DATA_OUT: - text = "=> Send SSL data"; - break; - case CURLINFO_HEADER_IN: - text = "<= Recv header"; - break; - case CURLINFO_DATA_IN: - text = "<= Recv data"; - break; - case CURLINFO_SSL_DATA_IN: - text = "<= Recv SSL data"; - break; - } - - dump(text, stderr, (unsigned char *)data, size, config->trace_ascii); - return 0; -} -#endif - -int InetHttpUploadFileSync(const char *pURL, const char* pPath, void* pAttachInfo) -{ - CURL *pCurl = NULL; - int rc = 0; - CURLcode ret; - struct curl_httppost *pPost = NULL, *pLastPtr = NULL; - -#ifdef LIBCURL_DEBUG - struct data config; - config.trace_ascii = 1; /* enable ascii tracing */ -#endif - - if(pURL == NULL || strlen(pURL) == 0) - { - LOG_EX(LOG_Error, "Url: %s(%p)\n", SAFE_STRING_VALUE(pURL), pURL); - return -ERR_INPUT_PARAMS; - } - - if(pPath == NULL || strlen(pPath) == 0) - { - LOG_EX(LOG_Error, "Url: %s(%p)\n", SAFE_STRING_VALUE(pPath), pPath); - return -ERR_INPUT_PARAMS; - } - - curl_formadd(&pPost, &pLastPtr, - CURLFORM_COPYNAME, "file", - CURLFORM_FILE, pPath, - CURLFORM_END); - - if(pAttachInfo) - { - PHTTP_POST_ATTACH pDevInfoArray = (PHTTP_POST_ATTACH)pAttachInfo; - PHTTP_POST_ATTACH pItem = NULL, pTmp = NULL; - - LL_FOREACH_SAFE(pDevInfoArray, pItem, pTmp) - { - curl_formadd(&pPost, &pLastPtr, - CURLFORM_COPYNAME, pItem->keyName, - CURLFORM_COPYCONTENTS, pItem->keyValue, - CURLFORM_END); - } - } - - pCurl = curl_easy_init(); - - if(pCurl == NULL) - { - LOG_EX(LOG_Error, "curl_easy_init() Error\n"); - return -ERR_MALLOC_MEMORY; - } - - curl_easy_setopt(pCurl, CURLOPT_ACCEPT_ENCODING, "gzip, deflate"); - curl_easy_setopt(pCurl, CURLOPT_POST, 1L); - curl_easy_setopt(pCurl, CURLOPT_URL, pURL); - curl_easy_setopt(pCurl, CURLOPT_HTTPPOST, pPost); - curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, __uploadCb); - curl_easy_setopt(pCurl, CURLOPT_CONNECTTIMEOUT, 10L); -#ifdef LIBCURL_DEBUG - curl_easy_setopt(pCurl, CURLOPT_DEBUGFUNCTION, my_trace); - curl_easy_setopt(pCurl, CURLOPT_DEBUGDATA, &config); -#endif - -#ifdef SKIP_PEER_VERIFICATION - /* - * If you want to connect to a site who isn't using a certificate that is - * signed by one of the certs in the CA bundle you have, you can skip the - * verification of the server's certificate. This makes the connection - * A LOT LESS SECURE. - * - * If you have a CA cert for the server stored someplace else than in the - * default bundle, then the CURLOPT_CAPATH option might come handy for - * you. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 0L); -#else - curl_easy_setopt(pCurl, CURLOPT_CAINFO, SSL_CA_FILE); - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 1L); -#endif - -#ifdef SKIP_HOSTNAME_VERIFICATION - /* - * If the site you're connecting to uses a different host name that what - * they have mentioned in their server certificate's commonName (or - * subjectAltName) fields, libcurl will refuse to connect. You can skip - * this check, but this will make the connection less secure. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYHOST, 0L); -#endif - - -#ifdef LIBCURL_DEBUG - curl_easy_setopt(pCurl, CURLOPT_VERBOSE, 1L); -#else - curl_easy_setopt(pCurl, CURLOPT_VERBOSE, 0L); -#endif - - ret = curl_easy_perform(pCurl); - - if(ret != CURLE_OK) - { - LOG_EX(LOG_Error, "Upload %s File %s Error %s(%d)\n", pURL, pPath, curl_easy_strerror(ret), ret); - rc = -ERR_NETWORK_SEND; - } - - curl_easy_cleanup(pCurl); - curl_formfree(pPost); - - return rc; -} - -const char* InetHttpWebServicePostAsync(const char *pURL, const char* pPost, OnHttpResponse onRespCb, void* pData) -{ - uuid_t msgId; - char strMsgId[64]; - PHTTP_REQ_PARAMS pParams = (PHTTP_REQ_PARAMS)malloc(sizeof(HTTP_REQ_PARAMS)); - CURL *pCurl = NULL; - - if(pURL == NULL || strlen(pURL) == 0 || onRespCb == NULL) - { - free(pParams); - return (NULL); - } - - memset(pParams, 0, sizeof(HTTP_REQ_PARAMS)); - - pCurl = curl_easy_init(); - - pParams->onRspCb = onRespCb; - pParams->pReqUrl = (char *)malloc(strlen(pURL) + 1); - pParams->type = INET_HTTP_WEBSERVICE_POST; - pParams->dlSize = 0; - pParams->pData = pData; - pParams->pCurl = pCurl; - pParams->lastTm = 0; - pParams->isCancel = FALSE; - - memset(pParams->pReqUrl, 0, strlen(pURL) + 1); - strcpy(pParams->pReqUrl, pURL); - - uuid_generate_random(msgId); - memset(strMsgId, 0, 64); - uuid_unparse_lower(msgId, strMsgId); - pParams->pTaskUuid = strdup(strMsgId); - - curl_easy_setopt(pCurl, CURLOPT_WRITEFUNCTION, __writeDataCb); - curl_easy_setopt(pCurl, CURLOPT_WRITEDATA, pParams); - curl_easy_setopt(pCurl, CURLOPT_PRIVATE, pParams); - curl_easy_setopt(pCurl, CURLOPT_URL, pURL); - curl_easy_setopt(pCurl, CURLOPT_NOPROGRESS, 1L); - curl_easy_setopt(pCurl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); - - if(pPost != NULL && strlen(pPost) > 0) - { - curl_easy_setopt(pCurl, CURLOPT_POSTFIELDS, pPost); - curl_easy_setopt(pCurl, CURLOPT_POSTFIELDSIZE, (long)strlen(pPost)); - } - -#ifdef SKIP_PEER_VERIFICATION - /* - * If you want to connect to a site who isn't using a certificate that is - * signed by one of the certs in the CA bundle you have, you can skip the - * verification of the server's certificate. This makes the connection - * A LOT LESS SECURE. - * - * If you have a CA cert for the server stored someplace else than in the - * default bundle, then the CURLOPT_CAPATH option might come handy for - * you. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 0L); -#else - curl_easy_setopt(pCurl, CURLOPT_CAINFO, SSL_CA_FILE); - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYPEER, 1L); -#endif - -#ifdef SKIP_HOSTNAME_VERIFICATION - /* - * If the site you're connecting to uses a different host name that what - * they have mentioned in their server certificate's commonName (or - * subjectAltName) fields, libcurl will refuse to connect. You can skip - * this check, but this will make the connection less secure. - */ - curl_easy_setopt(pCurl, CURLOPT_SSL_VERIFYHOST, 0L); -#endif - - curl_multi_add_handle(g_pCurl, pCurl); - - __addReqIdToTable(pParams->pTaskUuid, pParams); - - return (pParams->pTaskUuid); -} - -#if 0 -static void __curlTaskRuntimeCb(void *pParams) -{ - PCURL_HANDLE_TBL pItem = NULL, pTmpItem = NULL; - - while(TRUE) - { - uv_rwlock_rdlock(&g_uvHashRwLock); - - HASH_ITER(hh, g_ReqHandleTbl, pItem, pTmpItem) - { - if(pItem->pCurlItem->type == INET_HTTP_DOWNLOAD_FILE - && pItem->pCurlItem->lastTm > 0) - { - //unsigned int tmNow = LIBUV_CURRENT_TIME_S(); - - if(pItem->pCurlItem->lastTm > 0) - { - //curl_multi_cleanup(pItem->pCurlItem->pCurl); - curl_multi_remove_handle(g_pCurl, pItem->pCurlItem->pCurl); - - if(pItem->uRetryTimes >= 3) - { - if(pItem->pCurlItem->onRspCb) - { - if(strcmp(pItem->pCurlItem->sPath, pItem->pCurlItem->sDlPath) != 0) - { - unlink(pItem->pCurlItem->sDlPath); - } - - pItem->pCurlItem->onRspCb(NULL, - pItem->pCurlItem->dlSize, - pItem->pCurlItem->pReqUrl, - pItem->pCurlItem->sPath, - pItem->pCurlItem->pTaskUuid, - TRUE, - pItem->pCurlItem->pData); - } - - if(pItem->pCurlItem->pReqUrl) - { - free(pItem->pCurlItem->pReqUrl); - } - } - else - { - __restartDlFileAsync(pItem->pCurlItem); - } - } - } - } - uv_rwlock_rdunlock(&g_uvHashRwLock); - usleep(100000); - } - - pthread_detach(pthread_self()); -} -#endif - -static int __getUsernameFromMail(const char *pMailAddr, char **pUsername) -{ - char *pTail; - - if(pMailAddr == NULL || pUsername == NULL || strlen(pMailAddr) == 0) - { - LOG_EX(LOG_Error, "Input Params Error: pMailAddr = [%s], pUsername = %p\n", - pMailAddr ? pMailAddr : "NULL", pUsername); - return (-ERR_INPUT_PARAMS); - } - - *pUsername = (char *)malloc(strlen(pMailAddr) + 1); - - if(*pUsername == NULL) - { - LOG_EX(LOG_Error, "Error Malloc Memory\n"); - *pUsername = ""; - return (-ERR_MALLOC_MEMORY); - } - - memset(*pUsername, 0, strlen(pMailAddr) + 1); - - pTail = strchr(pMailAddr, '@'); - - if(pTail == NULL) - { - strcpy(*pUsername, pMailAddr); - } - else - { - memcpy(*pUsername, pMailAddr, pTail - pMailAddr); - } - - return (0); -} - -int InetSmtpSendEmail(const char* pFrom, - const char* pTo[], - const char* pCc[], - const char* pTitle, - const char* pMessage, - const char* pAttach[], - PSMTP_MAIL_CONFIG pConfig) -{ - const char *pErrMsg = NULL; - quickmail pMail; - - if(pConfig == NULL) - { - LOG_EX(LOG_Error, "Input Param pConfig = NULL\n"); - return (-ERR_INPUT_PARAMS); - } - - if(pConfig->pPassword == NULL || strlen(pConfig->pPassword) == 0) - { - LOG_EX(LOG_Error, "Input Param Error: pConfig->pPassword = [%s]\n", pConfig->pPassword ? pConfig->pPassword : "NULL"); - return (-ERR_INPUT_PARAMS); - } - - if(pConfig->pUserName == NULL || strlen(pConfig->pUserName) == 0) - { - LOG_EX(LOG_Error, "Input Param Error: pConfig->pUserName = [%s]\n", pConfig->pUserName ? pConfig->pUserName : "NULL"); - return (-ERR_INPUT_PARAMS); - } - - if(pConfig->pSmtpServer == NULL || strlen(pConfig->pSmtpServer) == 0) - { - LOG_EX(LOG_Error, "Input Param Error: pConfig->pUserName = [%s]\n", pConfig->pSmtpServer ? pConfig->pSmtpServer : "NULL"); - return (-ERR_INPUT_PARAMS); - } - - if(pFrom == NULL) - { - LOG_EX(LOG_Error, "Input Param pFrom = NULL\n"); - return (-ERR_INPUT_PARAMS); - } - - if(pTo == NULL && pCc == NULL) - { - LOG_EX(LOG_Error, "Input Param pTo = %p, pCc = %p\n", pTo, pCc); - return (-ERR_INPUT_PARAMS); - } - - if(pTitle == NULL) - { - pTitle = ""; - } - - if(pMessage == NULL) - { - pMessage = ""; - } - - quickmail_initialize(); - - pMail = quickmail_create(pFrom, pTitle); - - if(pMail == NULL) - { - LOG_EX(LOG_Error, "Create Quickmail Object Error\n"); - return (-ERR_MALLOC_MEMORY); - } - - for(const char **pValue = pTo; pTo && *pValue; pValue++) - { - quickmail_add_to(pMail, *pValue); - } - - for(const char **pValue = pCc; pCc && *pValue; pValue++) - { - quickmail_add_cc(pMail, *pValue); - } - - quickmail_add_header(pMail, "Importance: Low"); - quickmail_add_header(pMail, "X-Priority: 5"); - quickmail_add_header(pMail, "X-MSMail-Priority: Low"); - quickmail_add_body_memory(pMail, "text/html", (char*)pMessage, strlen(pMessage), 0); - - for(const char **pValue = pAttach; pAttach && *pValue; pValue++) - { - quickmail_add_attachment_file(pMail, *pValue, NULL); - } - - //quickmail_set_debug_log(pMail, stderr); - - pErrMsg = quickmail_send(pMail, pConfig->pSmtpServer, pConfig->smtpPort, pConfig->pUserName, pConfig->pPassword); - - if(pErrMsg != NULL) - { - LOG_EX(LOG_Error, "Send Mail Error: %s\n", pErrMsg); - return (-ERR_SEND_MAIL); - } - - return (0); -} - -int InetInit(void) -{ - int ret = 0; - - ret = curl_global_init(CURL_GLOBAL_ALL); - - if(ret != 0) - { - LOG_EX(LOG_Error, "curl init error: %d\n", ret); - return ret; - } - - g_pMainLoop = DBusLibuvGetRuntime()->pLoop; - - uv_timer_init(g_pMainLoop, &g_uvCurlTm); - uv_timer_init(g_pMainLoop, &g_uvDlTm); - - g_pCurl = curl_multi_init(); - - curl_multi_setopt(g_pCurl, CURLMOPT_SOCKETFUNCTION, __curlSockCb); - curl_multi_setopt(g_pCurl, CURLMOPT_TIMERFUNCTION, __curlTimerCb); - - uv_rwlock_init(&g_uvHashRwLock); - - uv_timer_start(&g_uvDlTm, __onDlTmoutCb, 1000, 1000); - - return (0); -} - -void InetUnInit(void) -{ - curl_multi_cleanup(g_pCurl); - curl_global_cleanup(); -} - diff --git a/Framework/Skins/skin_res_vtbl.c b/Framework/Skins/skin_res_vtbl.c deleted file mode 100644 index ae30711..0000000 --- a/Framework/Skins/skin_res_vtbl.c +++ /dev/null @@ -1,320 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "libuv_dbus.h" -#include "skins.h" -#include "log.h" - -typedef struct -{ - sqlite3_vtab vTable; - sqlite3 *pSqlDb; - char *pTblName; -} SKINRES_VTBL, *PSKINRES_VTBL; - -typedef struct -{ - sqlite3_vtab_cursor base; - int count; - int eof; -} SKINRES_CURSOR, *PSKINRES_CURSOR; - -static int __skin_res_destructor(sqlite3_vtab *pVtab) -{ - PSKINRES_VTBL p = (PSKINRES_VTBL)pVtab; - - if(p->pTblName != NULL) - { - free(p->pTblName); - p->pTblName = NULL; - } - sqlite3_free(p); - - return 0; -} - -static int __skin_res_create(sqlite3 *pDb, - void *pAux, - int argc, const char * const *argv, - sqlite3_vtab **pp_vt, - char **pzErr) -{ - UT_string *pSqlCmd; - int rc = SQLITE_OK; - PSKINRES_VTBL pVTbl; - - /* Allocate the sqlite3_vtab/example_vtab structure itself */ - pVTbl = (PSKINRES_VTBL)sqlite3_malloc(sizeof(SKINRES_VTBL)); - - if(pVTbl == NULL) - { - return SQLITE_NOMEM; - } - - pVTbl->pSqlDb = pDb; - pVTbl->pTblName = strdup(argv[2]); - - utstring_new(pSqlCmd); - if(strcmp(argv[0], RES_MODE_NAME) == 0) - { - utstring_printf(pSqlCmd, CREATE_RES_TBL_SQL, ""); - } - else - { - utstring_printf(pSqlCmd, CREATE_SKIN_TBL_SQL, ""); - } - - /* Declare the vtable's structure */ - rc = sqlite3_declare_vtab(pDb, utstring_body(pSqlCmd)); - utstring_free(pSqlCmd); - - if(rc != SQLITE_OK) - { - __skin_res_destructor((sqlite3_vtab*)pVTbl); - - return SQLITE_ERROR; - } - - /* Success. Set *pp_vt and return */ - *pp_vt = &pVTbl->vTable; - - return SQLITE_OK; -} - -static int __skin_res_connect( sqlite3 *db, void *p_aux, - int argc, const char * const *argv, - sqlite3_vtab **pp_vt, char **pzErr ) -{ - return __skin_res_create(db, p_aux, argc, argv, pp_vt, pzErr); -} - -static int __skin_res_disconnect(sqlite3_vtab *pVtab) -{ - return __skin_res_destructor(pVtab); -} - -static int __skin_res_destroy(sqlite3_vtab *pVtab) -{ - int rc = SQLITE_OK; - //PSKINRES_VTBL p = (PSKINRES_VTBL)pVtab; - - if(rc == SQLITE_OK) - { - rc = __skin_res_destructor(pVtab); - } - - return rc; -} - -static int __skin_res_open(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) -{ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)sqlite3_malloc(sizeof(SKINRES_CURSOR)); - *ppCursor = (sqlite3_vtab_cursor*)pCur; - - return (pCur ? SQLITE_OK : SQLITE_NOMEM); -} - -static int __skin_res_close(sqlite3_vtab_cursor *cur) -{ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)cur; - sqlite3_free(pCur); - - return SQLITE_OK; -} - -static int __skin_res_eof(sqlite3_vtab_cursor *cur) -{ - return ((PSKINRES_CURSOR)cur)->eof; -} - -static int __skin_res_next(sqlite3_vtab_cursor *pInCur) -{ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)pInCur; - //PSKINRES_VTBL pvTable = (PSKINRES_VTBL)pInCur->pVtab; - - /* Increment the current row count. */ - pCur->count += 1; - - /* Arbitrary contstraint: when we get to 10 rows, then stop. */ - if(pCur->count >= SkinsDefaultSize()) - { - pCur->eof = 1; - } - - return SQLITE_OK; -} - -static int __skin_res_column(sqlite3_vtab_cursor *pInCur, sqlite3_context *ctx, int iCol) -{ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)pInCur; - PSKIN_RES_INFO pItem = SkinsItemById(pCur->count); - //PSKINRES_VTBL pvTable = (PSKINRES_VTBL)pInCur->pVtab; - - /* Just return the ordinal of the column requested. */ - switch(iCol) - { - case 0: - sqlite3_result_int(ctx, pCur->count); - break; - - case 1: - sqlite3_result_text(ctx, pItem->pResVer, strlen(pItem->pResVer), SQLITE_STATIC); - break; - - case 2: - sqlite3_result_text(ctx, pItem->pLocalPath, strlen(pItem->pLocalPath), SQLITE_STATIC); - break; - - case 3: - sqlite3_result_text(ctx, pItem->pLocalPath, strlen(pItem->pLocalPath), SQLITE_STATIC); - break; - - case 4: - sqlite3_result_text(ctx, pItem->pMD5Chksum, strlen(pItem->pMD5Chksum), SQLITE_STATIC); - break; - } - - return SQLITE_OK; -} - -static int __skin_cfg_column(sqlite3_vtab_cursor *pInCur, sqlite3_context *ctx, int iCol) -{ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)pInCur; - PSKIN_RES_INFO pItem = SkinsItemById(pCur->count); - //PSKINRES_VTBL pvTable = (PSKINRES_VTBL)pInCur->pVtab; - - /* Just return the ordinal of the column requested. */ - switch(iCol) - { - case 0: - sqlite3_result_int(ctx, pCur->count); - break; - - case 1: - sqlite3_result_text(ctx, pItem->pKeyName, strlen(pItem->pKeyName), SQLITE_STATIC); - break; - - case 2: - sqlite3_result_int(ctx, pItem->resType); - break; - - case 3: - sqlite3_result_int(ctx, 0); - break; - - case 4: - sqlite3_result_int(ctx, pCur->count); - break; - - case 5: - sqlite3_result_text(ctx, "", 0, SQLITE_STATIC); - break; - } - - return SQLITE_OK; -} - -static int __skin_res_rowid(sqlite3_vtab_cursor *pInCur, sqlite_int64 *p_rowid) -{ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)pInCur; - - /* Just use the current row count as the rowid. */ - *p_rowid = pCur->count; - - return SQLITE_OK; -} - -static int __skin_res_filter( sqlite3_vtab_cursor *pVtc, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv ) -{ - //int rc; - //int i; - - /* Initialize the cursor structure. */ - PSKINRES_CURSOR pCur = (PSKINRES_CURSOR)pVtc; - - /* Zero rows returned thus far. */ - pCur->count = 0; - - /* Have not reached end of set. */ - pCur->eof = 0; - - /* Move cursor to first row. */ - return __skin_res_next(pVtc); -} - -/* Pretty involved. We don't implement in this example. */ -static int __skin_res_best_index(sqlite3_vtab *pVTbl, sqlite3_index_info *pIdxInfo) -{ - return SQLITE_OK; -} - -static sqlite3_module g_ResModule = -{ - 0, /* iVersion */ - __skin_res_create, /* xCreate - create a vtable */ - __skin_res_connect, /* xConnect - associate a vtable with a connection */ - __skin_res_best_index, /* xBestIndex - best index */ - __skin_res_disconnect, /* xDisconnect - disassociate a vtable with a connection */ - __skin_res_destroy, /* xDestroy - destroy a vtable */ - __skin_res_open, /* xOpen - open a cursor */ - __skin_res_close, /* xClose - close a cursor */ - __skin_res_filter, /* xFilter - configure scan constraints */ - __skin_res_next, /* xNext - advance a cursor */ - __skin_res_eof, /* xEof - inidicate end of result set*/ - __skin_res_column, /* xColumn - read data */ - __skin_res_rowid, /* xRowid - read data */ - NULL, /* xUpdate - write data */ - NULL, /* xBegin - begin transaction */ - NULL, /* xSync - sync transaction */ - NULL, /* xCommit - commit transaction */ - NULL, /* xRollback - rollback transaction */ - NULL, /* xFindFunction - function overloading */ -}; - -static sqlite3_module g_SkinModule = -{ - 0, /* iVersion */ - __skin_res_create, /* xCreate - create a vtable */ - __skin_res_connect, /* xConnect - associate a vtable with a connection */ - __skin_res_best_index, /* xBestIndex - best index */ - __skin_res_disconnect, /* xDisconnect - disassociate a vtable with a connection */ - __skin_res_destroy, /* xDestroy - destroy a vtable */ - __skin_res_open, /* xOpen - open a cursor */ - __skin_res_close, /* xClose - close a cursor */ - __skin_res_filter, /* xFilter - configure scan constraints */ - __skin_res_next, /* xNext - advance a cursor */ - __skin_res_eof, /* xEof - inidicate end of result set*/ - __skin_cfg_column, /* xColumn - read data */ - __skin_res_rowid, /* xRowid - read data */ - NULL, /* xUpdate - write data */ - NULL, /* xBegin - begin transaction */ - NULL, /* xSync - sync transaction */ - NULL, /* xCommit - commit transaction */ - NULL, /* xRollback - rollback transaction */ - NULL, /* xFindFunction - function overloading */ -}; - -int InitSkinRomDatabase(sqlite3 *pDataBase) -{ - if((sqlite3_create_module(pDataBase, SKIN_MODE_NAME, &g_SkinModule, NULL) == SQLITE_OK) - && (sqlite3_create_module(pDataBase, RES_MODE_NAME, &g_ResModule, NULL) == SQLITE_OK)) - { - return 0; - } - else - { - return -ERR_SQL_REG_MODULE; - } -} - - diff --git a/Framework/Skins/skins.c b/Framework/Skins/skins.c index 2fc624b..d44b51f 100644 --- a/Framework/Skins/skins.c +++ b/Framework/Skins/skins.c @@ -354,7 +354,7 @@ static int __skinCreateCfgFile(const char* pCfgFilePath) int rc = 0; static sqlite3* pSqlFileDB = NULL; UT_string *pSqlCmd = NULL; - +#if 0 rc = sqlite3_open(":memory:", &g_pMemDb); if(rc != SQLITE_OK) @@ -377,8 +377,8 @@ static int __skinCreateCfgFile(const char* pCfgFilePath) utstring_free(pSqlCmd); return -ERR_SQLITE3_CREATE_TABLE; } - - rc = sqlite3_open_v2(pCfgFilePath, &pSqlFileDB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); +#endif + rc = sqlite3_open_v2(pCfgFilePath, &pSqlFileDB, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE , NULL); if(rc != SQLITE_OK) { @@ -388,6 +388,8 @@ static int __skinCreateCfgFile(const char* pCfgFilePath) return -ERR_OPEN_SQLITE3_DB; } + LOG_EX(LOG_Debug, "Create Database: %s\n", pCfgFilePath); +#if 0 utstring_renew(pSqlCmd); utstring_printf(pSqlCmd, CREATE_SKIN_TBL_SQL""CREATE_RES_TBL_SQL, "", ""); @@ -395,7 +397,22 @@ static int __skinCreateCfgFile(const char* pCfgFilePath) if(rc != SQLITE_OK) { - LOG_EX(LOG_Error, "Create Tbl %s Error: %s\n", utstring_body(pSqlCmd), pErrMsg); + LOG_EX(LOG_Error, "Create Tbl \n[%s]\n Error: %s\n", utstring_body(pSqlCmd), pErrMsg); + sqlite3_free(pErrMsg); + unlink(pCfgFilePath); + sqlite3_close(g_pMemDb); + utstring_free(pSqlCmd); + return -ERR_SQLITE3_CREATE_TABLE; + } +#else + utstring_renew(pSqlCmd); + utstring_printf(pSqlCmd, CREATE_SKIN_TBL_SQL, ""); + + rc = sqlite3_exec(pSqlFileDB, utstring_body(pSqlCmd), NULL, 0, &pErrMsg); + + if(rc != SQLITE_OK) + { + LOG_EX(LOG_Error, "Create Tbl \n[%s]\n Error(%d): %s\n", utstring_body(pSqlCmd), rc, pErrMsg); sqlite3_free(pErrMsg); unlink(pCfgFilePath); sqlite3_close(g_pMemDb); @@ -403,6 +420,21 @@ static int __skinCreateCfgFile(const char* pCfgFilePath) return -ERR_SQLITE3_CREATE_TABLE; } + utstring_renew(pSqlCmd); + utstring_printf(pSqlCmd, CREATE_RES_TBL_SQL, ""); + + rc = sqlite3_exec(pSqlFileDB, utstring_body(pSqlCmd), NULL, 0, &pErrMsg); + + if(rc != SQLITE_OK) + { + LOG_EX(LOG_Error, "Create Tbl \n[%s]\n Error: %s\n", utstring_body(pSqlCmd), pErrMsg); + sqlite3_free(pErrMsg); + unlink(pCfgFilePath); + sqlite3_close(g_pMemDb); + utstring_free(pSqlCmd); + return -ERR_SQLITE3_CREATE_TABLE; + } +#endif utstring_renew(pSqlCmd); utstring_printf(pSqlCmd, UPGRADE_TBL_SQL_CMD, ""); rc = sqlite3_exec(pSqlFileDB, utstring_body(pSqlCmd), NULL, 0, &pErrMsg); diff --git a/Framework/Timer/timer.c b/Framework/Timer/timer.c deleted file mode 100644 index 3f91d7c..0000000 --- a/Framework/Timer/timer.c +++ /dev/null @@ -1,772 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "libuv_dbus.h" - -#define TIMER_TIMEOUT (200) - -#define IS_LEAP_YEAR(year) ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) - -static unsigned char g_DayOfMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; - -typedef struct -{ - void* pUserData; - OnAlarmTimer pOnAlarmCb; - unsigned int alarmId; - - struct tm setDateTime; - int setWeekDay; - unsigned int repeatMode; - - struct tm onDateTime; - time_t onTimestamp; - unsigned int timerPriority; - - UT_hash_handle hh; ///< UT Hash handle -} ALARM_ITEM_DATA, *PALARM_ITEM_DATA; - -static uv_timer_t g_uvTimer; -static unsigned int g_iAlarmId = 1; -static struct tm g_LocalTime; -static time_t g_TimeStamp; -static uv_loop_t* g_pMainLoop = NULL; -static uv_rwlock_t g_uvHashRwLock; -static PALARM_ITEM_DATA g_TimerTbl = NULL; - -const char* DumpTimerRepeatModeString(int mode) -{ - switch(mode & 0xFF) - { - case REPEAT_MODE_NONE: return "NONE"; - case REPEAT_MODE_EVERY_DAY: return "EVERY_DAY"; - case REPEAT_MODE_WORKDAY: return "WORKDAY"; - case REPEAT_MODE_HOLIDAY: return ("REPEAT_MODE_HOLIDAY"); - case REPEAT_MODE_WEEKEND: return "WEEKEND"; - case REPEAT_MODE_WEEKDAY: return "WEEKDAY"; - case REPEAT_MODE_EVERY_MONTH_DAY: return "EVERY_MONTH_DAY"; - case REPEAT_MODE_EVERY_YEAR_DAY: return "EVERY_YEAR_DAY"; - case REPEAT_MODE_EVERY_TIME: return ("EVERY_TIME"); - case REPEAT_MODE_MONTH_LAST_DAY: return "REPEAT_MODE_MONTH_LAST_DAY"; - default: return ("Unknown Mode"); - } -} - -static int __timestampSort(PALARM_ITEM_DATA p1, PALARM_ITEM_DATA p2) -{ - if(p1->onTimestamp == p2->onTimestamp) - { - return (p2->timerPriority - p1->timerPriority); - } - else - { - return (p1->onTimestamp - p2->onTimestamp); - } -} - -static int __getNextOnTimestamp(PALARM_ITEM_DATA pInfo) -{ - int ret; - struct tm setTime; - time_t timestamp; - - if(pInfo == NULL) - { - return (-ERR_INPUT_PARAMS); - } - - if(pInfo->repeatMode == REPEAT_MODE_NONE) - { - pInfo->onTimestamp = 0; - return (-ERR_INPUT_PARAMS); - } - - timestamp = pInfo->onTimestamp + 24 * 3600; - pInfo->onTimestamp = timestamp; - localtime_r(×tamp, &setTime); - - switch(pInfo->repeatMode) - { - case REPEAT_MODE_EVERY_DAY: - localtime_r(×tamp, &pInfo->onDateTime); - break; - - case REPEAT_MODE_WORKDAY: - do - { - ret = CurrentIsWorkDay(setTime.tm_year, setTime.tm_yday); - - if(ret == 0) - { - timestamp = mktime(&setTime) + 24 * 3600; - - localtime_r(×tamp, &setTime); - } - } while(ret == 0); - - if(ret < 0) - { - pInfo->onTimestamp = 0; - pInfo->onDateTime.tm_year = -1; - pInfo->onDateTime.tm_mon = -1; - pInfo->onDateTime.tm_mday = -1; - } - else - { - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - } - break; - - case REPEAT_MODE_HOLIDAY: - do - { - ret = CurrentIsWorkDay(setTime.tm_year, setTime.tm_yday); - - if(ret == 0) - { - timestamp = mktime(&setTime) + 24 * 3600; - - localtime_r(×tamp, &setTime); - } - } while(ret == 1); - - if(ret < 0) - { - pInfo->onTimestamp = 0; - pInfo->onDateTime.tm_year = -1; - pInfo->onDateTime.tm_mon = -1; - pInfo->onDateTime.tm_mday = -1; - } - else - { - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - } - break; - - case REPEAT_MODE_WEEKEND: - while(setTime.tm_wday != 0 && setTime.tm_wday != 6) - { - timestamp = mktime(&setTime) + 24 * 3600; - localtime_r(×tamp, &setTime); - } - - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - break; - - case REPEAT_MODE_WEEKDAY: - if(pInfo->setDateTime.tm_wday == 0) - { - pInfo->setDateTime.tm_wday = 1 << 0; - } - else if(pInfo->setDateTime.tm_wday & (1 << 7)) - { - pInfo->setDateTime.tm_wday = 1 << 0; - } - - while(((1 << setTime.tm_wday) & pInfo->setDateTime.tm_wday) == 0) - { - timestamp = mktime(&setTime) + 24 * 3600; - localtime_r(×tamp, &setTime); - } - - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - - break; - - case REPEAT_MODE_EVERY_TIME: - timestamp = mktime(&g_LocalTime); - - if(pInfo->setDateTime.tm_hour > 0) - { - timestamp += pInfo->setDateTime.tm_hour * 3600; - } - - if(pInfo->setDateTime.tm_min > 0) - { - timestamp += pInfo->setDateTime.tm_min * 60; - } - - if(pInfo->setDateTime.tm_sec > 0) - { - timestamp += pInfo->setDateTime.tm_sec; - } - - localtime_r(×tamp, &pInfo->onDateTime); - pInfo->onTimestamp = timestamp; - break; - - case REPEAT_MODE_MONTH_LAST_DAY: - if(pInfo->onDateTime.tm_mon < 11) - { - pInfo->onDateTime.tm_mon++; - } - else - { - pInfo->onDateTime.tm_mon = 0; - pInfo->onDateTime.tm_year++; - } - - pInfo->onDateTime.tm_mday = g_DayOfMonth[pInfo->onDateTime.tm_mon]; - if(IS_LEAP_YEAR(pInfo->onDateTime.tm_year) && (pInfo->onDateTime.tm_mon == 1)) - { - pInfo->onDateTime.tm_mday += 1; - } - - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - break; - } - - return (0); -} - -static int __getOnTimestamp(PALARM_ITEM_DATA pInfo) -{ - int ret = 0; - struct tm setTime; - time_t timestamp; - - if(pInfo == NULL) - { - return (-ERR_INPUT_PARAMS); - } - - if(pInfo->setDateTime.tm_hour == -1) - { - pInfo->onDateTime.tm_hour = g_LocalTime.tm_hour; - } - else - { - pInfo->onDateTime.tm_hour = pInfo->setDateTime.tm_hour; - } - - if(pInfo->setDateTime.tm_min == -1) - { - pInfo->onDateTime.tm_min = g_LocalTime.tm_min; - } - else - { - pInfo->onDateTime.tm_min = pInfo->setDateTime.tm_min; - } - - if(pInfo->setDateTime.tm_sec == -1) - { - pInfo->onDateTime.tm_sec = g_LocalTime.tm_sec; - } - else - { - pInfo->onDateTime.tm_sec = pInfo->setDateTime.tm_sec; - } - - switch(pInfo->repeatMode) - { - case REPEAT_MODE_EVERY_MONTH_DAY: - pInfo->setDateTime.tm_mon = -1; - pInfo->setDateTime.tm_year = -1; - case REPEAT_MODE_EVERY_YEAR_DAY: - pInfo->setDateTime.tm_year = -1; - case REPEAT_MODE_NONE: - if(pInfo->setDateTime.tm_year == -1) - { - pInfo->onDateTime.tm_year = g_LocalTime.tm_year; - } - else - { - pInfo->onDateTime.tm_year = pInfo->setDateTime.tm_year; - } - - if(pInfo->setDateTime.tm_mon == -1) - { - pInfo->onDateTime.tm_mon = g_LocalTime.tm_mon; - } - else - { - pInfo->onDateTime.tm_mon = pInfo->setDateTime.tm_mon; - } - - if(pInfo->setDateTime.tm_mday == -1) - { - pInfo->onDateTime.tm_mday = g_LocalTime.tm_mday; - } - else - { - pInfo->onDateTime.tm_mday = pInfo->setDateTime.tm_mday; - } - break; - - case REPEAT_MODE_EVERY_DAY: - case REPEAT_MODE_WORKDAY: - case REPEAT_MODE_WEEKEND: - case REPEAT_MODE_WEEKDAY: - case REPEAT_MODE_EVERY_TIME: - case REPEAT_MODE_HOLIDAY: - pInfo->onDateTime.tm_year = g_LocalTime.tm_year; - pInfo->onDateTime.tm_mon = g_LocalTime.tm_mon; - pInfo->onDateTime.tm_mday = g_LocalTime.tm_mday; - break; - case REPEAT_MODE_MONTH_LAST_DAY: - pInfo->onDateTime.tm_year = g_LocalTime.tm_year; - pInfo->onDateTime.tm_mon = g_LocalTime.tm_mon; - pInfo->onDateTime.tm_mday = g_DayOfMonth[g_LocalTime.tm_mon]; - if(IS_LEAP_YEAR(g_LocalTime.tm_year) && (g_LocalTime.tm_mon == 1)) - { - pInfo->onDateTime.tm_mday += 1; - } - break; - } - - pInfo->onDateTime.tm_wday = g_LocalTime.tm_wday; - pInfo->onDateTime.tm_yday = g_LocalTime.tm_yday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - - if(pInfo->repeatMode == REPEAT_MODE_NONE) - { - return (0); - } - - memcpy(&setTime, &g_LocalTime, sizeof(struct tm)); - - if(mktime(&setTime) > (pInfo->onTimestamp + 1)) - { - if(pInfo->repeatMode == REPEAT_MODE_EVERY_MONTH_DAY) - { - if(pInfo->onDateTime.tm_mon < 11) - { - pInfo->onDateTime.tm_mon++; - } - else - { - pInfo->onDateTime.tm_mon = 0; - pInfo->onDateTime.tm_year++; - } - - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - return (0); - } - else if(pInfo->repeatMode == REPEAT_MODE_EVERY_YEAR_DAY) - { - pInfo->onDateTime.tm_year++; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - return (0); - } - else if(pInfo->repeatMode == REPEAT_MODE_MONTH_LAST_DAY) - { - if(pInfo->onDateTime.tm_mon < 11) - { - pInfo->onDateTime.tm_mon++; - } - else - { - pInfo->onDateTime.tm_mon = 0; - pInfo->onDateTime.tm_year++; - } - - pInfo->onDateTime.tm_mday = g_DayOfMonth[pInfo->onDateTime.tm_mon]; - if(IS_LEAP_YEAR(pInfo->onDateTime.tm_year) && (pInfo->onDateTime.tm_mon == 1)) - { - pInfo->onDateTime.tm_mday += 1; - } - - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - return (0); - } - else - { - timestamp = mktime(&setTime) + 24 * 3600; - localtime_r(×tamp, &setTime); - } - } - - switch(pInfo->repeatMode) - { - case REPEAT_MODE_EVERY_DAY: - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - break; - - case REPEAT_MODE_WORKDAY: - do - { - ret = CurrentIsWorkDay(setTime.tm_year, setTime.tm_yday); - - if(ret == 0) - { - timestamp = mktime(&setTime) + 24 * 3600; - - localtime_r(×tamp, &setTime); - } - } while(ret == 0); - - if(ret < 0) - { - pInfo->onTimestamp = 0; - pInfo->onDateTime.tm_year = -1; - pInfo->onDateTime.tm_mon = -1; - pInfo->onDateTime.tm_mday = -1; - } - else - { - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - } - break; - - case REPEAT_MODE_HOLIDAY: - do - { - ret = CurrentIsWorkDay(setTime.tm_year, setTime.tm_yday); - - if(ret == 0) - { - timestamp = mktime(&setTime) + 24 * 3600; - - localtime_r(×tamp, &setTime); - } - } while(ret == 1); - - if(ret < 0) - { - pInfo->onTimestamp = 0; - pInfo->onDateTime.tm_year = -1; - pInfo->onDateTime.tm_mon = -1; - pInfo->onDateTime.tm_mday = -1; - } - else - { - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - } - break; - - case REPEAT_MODE_WEEKEND: - while(setTime.tm_wday != 0 && setTime.tm_wday != 6) - { - timestamp = mktime(&setTime) + 24 * 3600; - localtime_r(×tamp, &setTime); - } - - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - break; - - case REPEAT_MODE_WEEKDAY: - if(pInfo->setDateTime.tm_wday == 0) - { - pInfo->setDateTime.tm_wday = 1 << 0; - } - else if(pInfo->setDateTime.tm_wday & (1 << 7)) - { - pInfo->setDateTime.tm_wday = 1 << 0; - } - - while(((1 << setTime.tm_wday) & pInfo->setDateTime.tm_wday) == 0) - { - timestamp = mktime(&setTime) + 24 * 3600; - localtime_r(×tamp, &setTime); - } - - pInfo->onDateTime.tm_year = setTime.tm_year; - pInfo->onDateTime.tm_mon = setTime.tm_mon; - pInfo->onDateTime.tm_mday = setTime.tm_mday; - pInfo->onTimestamp = mktime(&pInfo->onDateTime); - - break; - - case REPEAT_MODE_EVERY_TIME: - timestamp = mktime(&g_LocalTime); - - if(pInfo->setDateTime.tm_hour > 0) - { - timestamp += pInfo->setDateTime.tm_hour * 3600; - } - - if(pInfo->setDateTime.tm_min > 0) - { - timestamp += pInfo->setDateTime.tm_min * 60; - } - - if(pInfo->setDateTime.tm_sec > 0) - { - timestamp += pInfo->setDateTime.tm_sec; - } - - localtime_r(×tamp, &pInfo->onDateTime); - pInfo->onTimestamp = timestamp; - break; - } - - return (0); -} - -static void __timerout200msCb(uv_timer_t *pTimer) -{ - PALARM_ITEM_DATA pItem = NULL, pTemp = NULL; - - // upgrade current time and timestamp - g_TimeStamp = time((time_t*)NULL); - localtime_r(&g_TimeStamp, &g_LocalTime); - - uv_rwlock_wrlock(&g_uvHashRwLock); - HASH_ITER(hh, g_TimerTbl, pItem, pTemp) - { - // cleanup out of time more than 10s timer - if(g_TimeStamp - pItem->onTimestamp > 10) - { - LOG_EX(LOG_Warn, "Remove out of time timer: %u, %ld, %ld\n", pItem->alarmId, g_TimeStamp, pItem->onTimestamp); - HASH_DEL(g_TimerTbl, pItem); - free(pItem); - - continue; - } - - // timer not on time - if(pItem->onTimestamp != g_TimeStamp) - { - break; - } - - // timer on time, call callback - if(pItem->pOnAlarmCb) - { - pItem->pOnAlarmCb(pItem->alarmId, g_TimeStamp, pItem->pUserData); - } - - //LOG_EX(LOG_Debug, "Timer %d Alarming..................\n", pItem->alarmId); - - // cleanup not repeat timer - if(pItem->repeatMode == REPEAT_MODE_NONE) - { - HASH_DEL(g_TimerTbl, pItem); - free(pItem); - } - else - { - // calc next on time - int ret = __getNextOnTimestamp(pItem); - - if(ret != 0 || pItem->onTimestamp == 0) - { - // some error, remove it - LOG_EX(LOG_Error, "Timer %d repeat error: ret = %d, timestamp = %u\n", pItem->alarmId, ret, pItem->onTimestamp); - HASH_DEL(g_TimerTbl, pItem); - free(pItem); - } - else - { - // resort table by upgrade timestamp - HASH_SORT(g_TimerTbl, __timestampSort); - - // show log - LOG_EX(LOG_Debug, "Readd Timer: %u at [%04u-%02u-%02u %02u:%02u:%02u], repMode = %s, Timestamp = %u\n", - pItem->alarmId, - pItem->onDateTime.tm_year + 1900, - pItem->onDateTime.tm_mon + 1, - pItem->onDateTime.tm_mday, - pItem->onDateTime.tm_hour, - pItem->onDateTime.tm_min, - pItem->onDateTime.tm_sec, - DumpTimerRepeatModeString(pItem->repeatMode), - pItem->onTimestamp); - } - } - } - uv_rwlock_wrunlock(&g_uvHashRwLock); -} - -int AlarmTimerInit(uv_loop_t* pLoop) -{ - g_pMainLoop = pLoop; - uv_rwlock_init(&g_uvHashRwLock); - uv_timer_init(g_pMainLoop, &g_uvTimer); - - g_TimeStamp = time((time_t*)NULL); - localtime_r(&g_TimeStamp, &g_LocalTime); - - g_iAlarmId = 1; - - uv_timer_start(&g_uvTimer, __timerout200msCb, 0, TIMER_TIMEOUT); -} - -int AlarmTimerCleanup(void) -{ - uv_timer_stop(&g_uvTimer); - uv_rwlock_destroy(&g_uvHashRwLock); - - if(g_pMainLoop != NULL) - { - AlarmTimerInit(g_pMainLoop); - } -} - -int AlarmTimerRemove(unsigned int tmId) -{ - PALARM_ITEM_DATA pItem = NULL; - - uv_rwlock_rdlock(&g_uvHashRwLock); - HASH_FIND_INT(g_TimerTbl, &tmId, pItem); - uv_rwlock_rdunlock(&g_uvHashRwLock); - - if(pItem == NULL) - { - LOG_EX(LOG_Error, "Can't find item: %u\n", tmId); - return (-ERR_NO_ITEMS); - } - - uv_rwlock_wrlock(&g_uvHashRwLock); - HASH_DEL(g_TimerTbl, pItem); - uv_rwlock_wrunlock(&g_uvHashRwLock); - free(pItem); - - return (tmId); -} - -unsigned int AlarmTimerAdd(int year, - int month, - int day, - int hour, - int minute, - int second, - int weekDay, - int repMode, - OnAlarmTimer pOnTimerCb, - int priority, - void *pUserData, - int *pError) -{ - int et; - PALARM_ITEM_DATA pAlarmData = NULL; - - if(pOnTimerCb == NULL) - { - LOG_EX(LOG_Error, "Input Params Error: pOnTimerCb = %p\n", pOnTimerCb); - if(pError) - { - *pError = -ERR_INPUT_PARAMS; - } - - return (0xFFFFFFFF); - } - - g_TimeStamp = time((time_t*)NULL); - localtime_r(&g_TimeStamp, &g_LocalTime); - - pAlarmData = (PALARM_ITEM_DATA)malloc(sizeof(ALARM_ITEM_DATA)); - - if(pAlarmData == NULL) - { - LOG_EX(LOG_Error, "Malloc Memory Error\n"); - - if(pError) - { - *pError = -ERR_MALLOC_MEMORY; - } - - return (0xFFFFFFFF); - } - - memset(pAlarmData, 0, sizeof(ALARM_ITEM_DATA)); - - // save input params - pAlarmData->setDateTime.tm_year = year; - pAlarmData->setDateTime.tm_mon = month; - pAlarmData->setDateTime.tm_mday = day; - pAlarmData->setDateTime.tm_hour = hour; - pAlarmData->setDateTime.tm_min = minute; - pAlarmData->setDateTime.tm_sec = second; - pAlarmData->setDateTime.tm_wday = weekDay; - - pAlarmData->repeatMode = repMode; - pAlarmData->pOnAlarmCb = pOnTimerCb; - pAlarmData->pUserData = pUserData; - pAlarmData->timerPriority = priority; - - // get timer on time - __getOnTimestamp(pAlarmData); - - // check on time - et = pAlarmData->onTimestamp - mktime(&g_LocalTime); - - if(et < -1 || pAlarmData->onTimestamp == 0) - { - LOG_EX(LOG_Debug, "Add Timer Error: [%04u-%02u-%02u %02u:%02u:%02u], repMode = %s(%u), %d, %u/%u\n", - pAlarmData->setDateTime.tm_year + 1900, - pAlarmData->setDateTime.tm_mon + 1, - pAlarmData->setDateTime.tm_mday, - pAlarmData->setDateTime.tm_hour, - pAlarmData->setDateTime.tm_min, - pAlarmData->setDateTime.tm_sec, - DumpTimerRepeatModeString(repMode), repMode, - et, pAlarmData->onTimestamp, mktime(&g_LocalTime)); - - if(pError) - { - *pError = -ERR_INPUT_PARAMS; - } - - return (0xFFFFFFFF); - } - - if(pError) - { - *pError = 0; - } - - // upgrade time global id - pAlarmData->alarmId = __sync_fetch_and_add(&g_iAlarmId, 1); - - // save new timer to hash table, and sort it by timestamp - uv_rwlock_wrlock(&g_uvHashRwLock); - HASH_ADD_INT(g_TimerTbl, alarmId, pAlarmData); - HASH_SORT(g_TimerTbl, __timestampSort); - uv_rwlock_wrunlock(&g_uvHashRwLock); - - LOG_EX(LOG_Debug, "Add: %u [%04u-%02u-%02u %02u:%02u:%02u] at [%04u-%02u-%02u %02u:%02u:%02u], repMode = %s, priority = %d, Timestamp = %u\n", - pAlarmData->alarmId, - (pAlarmData->setDateTime.tm_year == -1) ? 1900 : pAlarmData->setDateTime.tm_year + 1900, - (pAlarmData->setDateTime.tm_mon == -1) ? 0 : pAlarmData->setDateTime.tm_mon + 1, - (pAlarmData->setDateTime.tm_mday == -1) ? 0 : pAlarmData->setDateTime.tm_mday, - (pAlarmData->setDateTime.tm_hour == -1) ? 0 : pAlarmData->setDateTime.tm_hour, - (pAlarmData->setDateTime.tm_min == -1) ? 0 : pAlarmData->setDateTime.tm_min, - (pAlarmData->setDateTime.tm_sec == -1) ? 0 : pAlarmData->setDateTime.tm_sec, - pAlarmData->onDateTime.tm_year + 1900, - pAlarmData->onDateTime.tm_mon + 1, - pAlarmData->onDateTime.tm_mday, - pAlarmData->onDateTime.tm_hour, - pAlarmData->onDateTime.tm_min, - pAlarmData->onDateTime.tm_sec, - DumpTimerRepeatModeString(repMode), - pAlarmData->timerPriority, - pAlarmData->onTimestamp); - - return (pAlarmData->alarmId); -} - - diff --git a/Framework/libuvEngine/libcomm.c b/Framework/libuvEngine/libcomm.c new file mode 100644 index 0000000..141e7fb --- /dev/null +++ b/Framework/libuvEngine/libcomm.c @@ -0,0 +1,505 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "libuv_dbus.h" + +int CopyFile(const char *pSrc, const char *pDest) +{ + int fdSrc, fdDest; + struct stat st; + ssize_t sz; + + if(stat(pSrc, &st) != 0) + { + LOG_EX(LOG_Error, "Get File %s Size Error\n", pSrc); + return (-ERR_GET_FILE_SIZE); + } + + fdSrc = open(pSrc, O_RDONLY); + + if(fdSrc < 0) + { + LOG_EX(LOG_Error, "Open File %s Error\n", pSrc); + return (-ERR_OPEN_FILE); + } + + fdDest = open(pDest, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); + + if(fdDest < 0) + { + close(fdSrc); + LOG_EX(LOG_Error, "Open File %s Error\n", pDest); + return (-ERR_OPEN_FILE); + } + + sz = sendfile(fdDest, fdSrc, NULL, st.st_size); + + if(sz != st.st_size) + { + LOG_EX(LOG_Error, "Copy File Size Error: %d, %d\n", sz, st.st_size); + close(fdSrc); + close(fdDest); + return (-ERR_COPY_FILE); + } + + fsync(fdDest); + + close(fdSrc); + close(fdDest); + + return (0); +} + +int CopyFileWithSize(const char *pSrc, const char *pDest, int iSize) +{ + int fdSrc, fdDest; + struct stat st; + ssize_t sz; + size_t cpSize = iSize; + + if(iSize <= 0) + { + if(stat(pSrc, &st) != 0) + { + LOG_EX(LOG_Error, "Get File %s Size Error\n", pSrc); + return (-ERR_GET_FILE_SIZE); + } + + cpSize = st.st_size; + } + + fdSrc = open(pSrc, O_RDONLY); + + if(fdSrc < 0) + { + LOG_EX(LOG_Error, "Open File %s Error\n", pSrc); + return (-ERR_OPEN_FILE); + } + + fdDest = open(pDest, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |S_IWOTH); + + if(fdDest < 0) + { + close(fdSrc); + LOG_EX(LOG_Error, "Open File %s Error\n", pDest); + return (-ERR_OPEN_FILE); + } + + sz = sendfile(fdDest, fdSrc, NULL, cpSize); + + if(sz != cpSize) + { + LOG_EX(LOG_Error, "Copy File Size Error: %d, %d\n", sz, cpSize); + close(fdSrc); + close(fdDest); + return (-ERR_COPY_FILE); + } + + close(fdSrc); + close(fdDest); + + return (0); +} + +int ReadFileToBuf(const char *pSrc, unsigned char *pBuf, int iSize) +{ + int fdSrc; + struct stat st; + ssize_t sz; + size_t cpSize = iSize; + + if(iSize < 0) + { + if(stat(pSrc, &st) != 0) + { + LOG_EX(LOG_Error, "Get File %s Size Error\n", pSrc); + return (-ERR_GET_FILE_SIZE); + } + + cpSize = st.st_size; + } + + fdSrc = open(pSrc, O_RDONLY); + + if(fdSrc < 0) + { + LOG_EX(LOG_Error, "Open File %s Error\n", pSrc); + return (-ERR_OPEN_FILE); + } + + sz = read(fdSrc, pBuf, cpSize); + + if(sz != cpSize) + { + LOG_EX(LOG_Error, "Copy File Size Error: %d, %d\n", sz, cpSize); + close(fdSrc); + return (-ERR_COPY_FILE); + } + + close(fdSrc); + + return (sz); +} + +int GetShellExecResult(const char *pCmd, char **pResult) +{ + FILE *pFile = NULL; + unsigned int uRdSize = 0; + char *pCmdOut; + + *pResult = NULL; + + if(pCmd == NULL || strlen(pCmd) == 0) + { + return (-ERR_INPUT_PARAMS); + } + + pFile = popen(pCmd, "r"); + + if(pFile == NULL) + { + return (-ERR_OPEN_FILE); + } + + *pResult = (char *)malloc(4096); + pCmdOut = *pResult; + + uRdSize = fread(pCmdOut, sizeof(char), 4096, pFile); + + pCmdOut[uRdSize] = 0; + + if(pCmdOut[strlen(pCmdOut) - 1] == '\n') + { + pCmdOut[strlen(pCmdOut) - 1] = 0; + } + + pclose(pFile); + //fprintf(stdout, "%s --> [%s](%u)\n", pCmd, pCmdOut, uRdSize); + return (0); +} + +void SystemSafeReboot(void) +{ + int ret, reTry = 0; +#if 0 + ret = system("sync"); + + ret = system("ubus call system watchdog \'{\"stop\" : true}\'"); + + reTry = 3; + do + { + sleep(1); + } while(reTry--); + + reTry = 0; + + LOG_EX(LOG_Debug, "Reboot System By Power Control Chips\n"); + sleep(1); + + ret = system("echo 3140 > /sys/bus/platform/devices/axp22_board/axp22_reg"); + + sleep(10); +#endif + while(TRUE) + { + LOG_EX(LOG_Debug, "Reboot System: %d times\n", reTry++); + sleep(1); + ret = system("reboot -f"); + sleep(3); + } +} + +char* GetCpuChipId(void) +{ + char* pRet = NULL; +#ifdef PLATFORM_R16 + char* pChipId = NULL; + + GetShellExecResult("cat /proc/cpuinfo | grep Chipid | awk '{print $3}'", &pChipId); + + if(pChipId == NULL) + { + return strdup(""); + } + + pRet = strdup(pChipId); + free(pChipId); + return pRet; +#else + return strdup("Unknown CPU Chip ID"); +#endif +} + +char* GetCpuSerial(void) +{ + char* pRet = NULL; +#ifdef PLATFORM_R16 + char* pSerial = NULL; + + GetShellExecResult("cat /proc/cpuinfo | grep Serial | awk '{print $3}'", &pSerial); + + if(pSerial == NULL) + { + return strdup(""); + } + + pRet = strdup(pSerial); + free(pSerial); + return pRet; +#else + return strdup("Unknown CPU Serial"); +#endif +} + +unsigned long long GetPartitionFreeSize(const char *pPartPath) +{ + struct statfs myStatfs; + unsigned long long freeSize; + + if(statfs(pPartPath, &myStatfs) == -1) + { + return 0; + } + + freeSize = myStatfs.f_bsize * myStatfs.f_bfree; + + //fprintf(stdout, "%s free = %llu bytes\n", pPartPath, freeSize); + + return freeSize; +} + +#ifdef CURRENT_VERSION +char* GetCurrentVersion(void) +{ + return CURRENT_VERSION; +} +#else +char* GetCurrentVersion(void) +{ + return "0.0.1"; +} +#endif + +const char* ErrcodeToString(int errCode) +{ + switch(errCode) + { + case ERR_INPUT_PARAMS: return "ERR_INPUT_PARAMS"; + case ERR_NO_ITEMS: return "ERR_NO_ITEMS"; + case ERR_GET_BUS: return "ERR_GET_BUS"; + case ERR_DBUS_CONNECTION: return "ERR_DBUS_CONNECTION"; + case ERR_REQUEST_BUS_NAME: return "ERR_REQUEST_BUS_NAME"; + case ERR_SET_WATCH_FUNCTION: return "ERR_SET_WATCH_FUNCTION"; + case ERR_SET_TIMEOUT_FUNCTION: return "ERR_SET_TIMEOUT_FUNCTION"; + case ERR_BUS_MATCH: return "ERR_BUS_MATCH"; + case ERR_BUS_SET_MSG_CB: return "ERR_BUS_SET_MSG_CB"; + case ERR_DBUS_CREATE_MSG: return "ERR_DBUS_CREATE_MSG"; + case ERR_BUS_SEND_MSG: return "ERR_BUS_SEND_MSG"; + case ERR_DBUS_MSG_TO_LARGE: return "ERR_DBUS_MSG_TO_LARGE"; + case ERR_BUS_RCV_MSG: return "ERR_BUS_RCV_MSG"; + case ERR_ADD_TASK: return "ERR_ADD_TASK"; + case ERR_UNSUP_EVP_TYPE: return "ERR_UNSUP_EVP_TYPE"; + case ERR_CREATE_MQ: return "ERR_CREATE_MQ"; + case ERR_MQ_SENDMSG: return "ERR_MQ_SENDMSG"; + case ERR_CREATE_SHM: return "ERR_CREATE_SHM"; + case ERR_MAP_SHM: return "ERR_MAP_SHM"; + case ERR_MALLOC_MEMORY: return "ERR_MALLOC_MEMORY"; + case ERR_EVP_INIT_KEY: return "ERR_EVP_INIT_KEY"; + case ERR_EVP_UPDATE: return "ERR_EVP_UPDATE"; + case ERR_EVP_FINALE: return "ERR_EVP_FINALE"; + case ERR_EVP_KEY_SIZE: return "ERR_EVP_KEY_SIZE"; + case ERR_OPEN_FILE: return "ERR_OPEN_FILE"; + case ERR_READ_FILE: return "ERR_READ_FILE"; + case ERR_WRITE_FILE: return "ERR_WRITE_FILE"; + case ERR_COPY_FILE: return "ERR_COPY_FILE"; + case ERR_FILE_NOT_EXISTS: return "ERR_FILE_NOT_EXISTS"; + case ERR_GET_FILE_SIZE: return "ERR_GET_FILE_SIZE"; + case ERR_UNINIT_ITEM: return "ERR_UNINIT_ITEM"; + case ERR_FILE_EMPTY: return "ERR_FILE_EMPTY"; + case ERR_SEND_MAIL: return "ERR_SEND_MAIL"; + case ERR_NETWORK_SEND: return "ERR_NETWORK_SEND"; + case ERR_NETWORK_NOT_CONNECTED: return "ERR_NETWORK_NOT_CONNECTED"; + case ERR_UNSUPPORT: return "ERR_UNSUPPORT"; + case ERR_NO_INIT_IPL3: return "ERR_NO_INIT_IPL3"; + case ERR_BAD_IPL3: return "ERR_BAD_IPL3"; + case ERR_BAD_FILE_SIZE: return "ERR_BAD_FILE_SIZE"; + case ERR_MD5_FILE: return "ERR_MD5_FILE"; + case ERR_MD5_CHECK_SUM: return "ERR_MD5_CHECK_SUM"; + case ERR_OTA_WRITE_BOOT: return "ERR_OTA_WRITE_BOOT"; + case ERR_OTA_WRITE_ROOTFS: return "ERR_OTA_WRITE_ROOTFS"; + case ERR_OTA_WRITE_IPL3: return "ERR_OTA_WRITE_IPL3"; + case ERR_OTA_WRITE_PARAMS: return "ERR_OTA_WRITE_PARAMS"; + case ERR_OTA_DOWNLOAD_FILE: return "ERR_OTA_DOWNLOAD_FILE"; + case ERR_VERIFY_PARTITION_MD5: return "ERR_VERIFY_PARTITION_MD5"; + case ERR_OTA_PRE_STATR: return "ERR_OTA_PRE_STATR"; + case ERR_OTA_YET_CUR_VER: return "ERR_OTA_YET_CUR_VER"; + case ERR_OTA_NOT_READY: return "ERR_OTA_NOT_READY"; + case ERR_CREATE_CFG_FILE: return "ERR_CREATE_CFG_FILE"; + case ERR_CREATE_SQLITE3_DB: return "ERR_CREATE_SQLITE3_DB"; + case ERR_OPEN_SQLITE3_DB: return "ERR_OPEN_SQLITE3_DB"; + case ERR_SQLITE3_CREATE_TABLE: return "ERR_SQLITE3_CREATE_TABLE"; + case ERR_SYNC_DATABASE: return "ERR_SYNC_DATABASE"; + case ERR_SQL_QUERY: return "ERR_SQL_QUERY"; + case ERR_SQL_DELETE: return "ERR_SQL_DELETE"; + case ERR_UNKNOWN_TYPE: return "ERR_UNKNOWN_TYPE"; + case ERR_PERMISSION_DENIED: return "ERR_PERMISSION_DENIED"; + case ERR_CFG_NOITEM: return "ERR_CFG_NOITEM"; + case ERR_CFG_ITEM_EXIST: return "ERR_CFG_ITEM_EXIST"; + case ERR_CFG_WAIT_RSP: return "ERR_CFG_WAIT_RSP"; + case ERR_CFG_BUSY: return "ERR_CFG_BUSY"; + case ERR_STR_CONVERT: return "ERR_STR_CONVERT"; + case ERR_SQL_REG_MODULE: return "ERR_SQL_REG_MODULE"; + default: return "Unknown Error"; + } +} + +const char* DBusCmdToString(DBUS_CMD cmd) +{ + switch(cmd) + { + case CMD_MISC_PING: return "CMD_MISC_PING"; + case CMD_MISC_OTA: return "CMD_MISC_OTA"; + case CMD_MISC_WEATHER: return "CMD_MISC_WEATHER"; + case CMD_MISC_NOWTIME: return "CMD_MISC_NOWTIME"; + case CMD_MISC_UPGRADE: return "CMD_MISC_UPGRADE"; + case CMD_SYSTEM_STANDBY: return "CMD_SYSTEM_STANDBY"; + case CMD_MISC_QUERY_OTA_STATUS: return "CMD_MISC_QUERY_OTA_STATUS"; + case CMD_MISC_QUERY_DL_STATUS: return "CMD_MISC_QUERY_DL_STATUS"; + case CMD_CALL_DIAL: return "CMD_CALL_DIAL"; + case CMD_CALL_ACCEPI: return "CMD_CALL_ACCEPI"; + case CMD_CALL_HANGUP: return "CMD_CALL_HANGUP"; + case CMD_CALL_MESSAGE: return "CMD_CALL_MESSAGE"; + case CMD_PLAY_MODECHANGE: return "CMD_PLAY_MODECHANGE"; + case CMD_PLAY_PLAY: return "CMD_PLAY_PLAY"; + case CMD_PLAY_PAUSE: return "CMD_PLAY_PAUSE"; + case CMD_PLAY_STOP: return "CMD_PLAY_STOP"; + case CMD_PLAY_SEEKTO: return "CMD_PLAY_SEEKTO"; + case CMD_PLAY_SHOWMODE: return "CMD_PLAY_SHOWMODE"; + case CMD_PLAY_NEXT: return "CMD_PLAY_NEXT"; + case CMD_PLAY_PRE: return "CMD_PLAY_PRE"; + case CMD_PLAY_SHOWLIST: return "CMD_PLAY_SHOWLIST"; + case CMD_PLAY_UPDATELIST: return "CMD_PLAY_UPDATELIST"; + case CMD_PLAY_PREPARE_NEXT: return "CMD_PLAY_PREPARE_NEXT"; + case CMD_PLAY_ADDTOLIST: return "CMD_PLAY_ADDTOLIST"; + case CMD_PLAY_DELETEFROMLIST: return "CMD_PLAY_DELETEFROMLIST"; + case CMD_PLAY_RESETLIST: return "CMD_PLAY_RESETLIST"; + case CMD_PLAY_AUDIO_STOP: return "CMD_PLAY_AUDIO_STOP"; + case CMD_PLAY_AUDIO_PLAY: return "CMD_PLAY_AUDIO_PLAY"; + case CMD_SE_PLAY: return "CMD_SE_PLAY"; + case CMD_PLAY_RET_STATUS: return "CMD_PLAY_RET_STATUS"; + case CMD_CFG_ADD_REQ: return "CMD_CFG_ADD_REQ"; + case CMD_CFG_ADD_RSP: return "CMD_CFG_ADD_RSP"; + case CMD_CFG_CHANGE_REQ: return "CMD_CFG_CHANGE_REQ"; + case CMD_CFG_CHANGE_RSP: return "CMD_CFG_CHANGE_RSP"; + case CMD_CFG_GET_REQ: return "CMD_CFG_GET_REQ"; + case CMD_CFG_GET_RSP: return "CMD_CFG_GET_RSP"; + case CMD_CFG_UPG_NOTIFY: return "CMD_CFG_UPG_NOTIFY"; + case CMD_MSC_MSG_CONTROLLER_RECOG_SUCCESS: return "CMD_MSC_MSG_CONTROLLER_RECOG_SUCCESS"; + case CMD_MSC_MSG_CONTROLLER_RECOG_ERROR: return "CMD_MSC_MSG_CONTROLLER_RECOG_ERROR"; + case CMD_MSC_MSG_CONTROLLER_WAKEUP: return "CMD_MSC_MSG_CONTROLLER_WAKEUP"; + case CMD_MSC_MSG_CONTROLLER_RECOGING: return "CMD_MSC_MSG_CONTROLLER_RECOGING"; + case CMD_CONTROLLER_REQMSG_INITARGS: return "CMD_CONTROLLER_REQMSG_INITARGS"; + case CMD_CONTROLLER_RSPMSG_INITARGS: return "CMD_CONTROLLER_RSPMSG_INITARGS"; + case CMD_CONTROLLER_REQMSG_PLAYERSTATUS: return "CMD_CONTROLLER_REQMSG_PLAYERSTATUS"; + case CMD_CONTROLLER_RSPMSG_PLAYERSTATUS: return "CMD_CONTROLLER_RSPMSG_PLAYERSTATUS"; + case CMD_MSC_REQMSG_MIC_CONTROL: return "CMD_MSC_REQMSG_MIC_CONTROL"; + case CMD_MSC_RSPMSG_MIC_CONTROL: return "CMD_MSC_RSPMSG_MIC_CONTROL"; + case CMD_YUNXIN_RECVMSG: return "CMD_YUNXIN_RECVMSG"; + case CMD_YUNXIN_SENDMSG: return "CMD_YUNXIN_SENDMSG"; + case CMD_YUNXIN_SENDMSG_BYPASS: return "CMD_YUNXIN_SENDMSG_BYPASS"; + case CMD_YUNXIN_SENDMSGCB: return "CMD_YUNXIN_SENDMSGCB"; + case CMD_CONTROLLER_MSG_YUNXIN: return "CMD_CONTROLLER_MSG_YUNXIN"; + case CMD_YUNXIN_STATUS: return "CMD_YUNXIN_STATUS"; + case CMD_YUNXIN_SYSMSG: return "CMD_YUNXIN_SYSMSG"; + case CMD_WIFI_CONF: return "CMD_WIFI_CONF"; + case CMD_WIFI_CONF_RESP: return "CMD_WIFI_CONF_RESP"; + case CMD_WIFI_AUTO_CONN: return "CMD_WIFI_AUTO_CONN"; + case CMD_WIFI_AUTO_CONN_RESP: return "CMD_WIFI_AUTO_CONN_RESP"; + case CMD_WIFI_STATE_REQ: return "CMD_WIFI_STATE_REQ"; + case CMD_WIFI_STATE_RESP: return "CMD_WIFI_STATE_RESP"; + case CMD_WIFI_STATE_NTF: return "CMD_WIFI_STATE_NTF"; + case CMD_BT_NAME_GET_REQ: return "CMD_BT_NAME_GET_REQ"; + case CMD_BT_NAME_GET_RESP: return "CMD_BT_NAME_GET_RESP"; + case CMD_BT_EVT_NTF: return "CMD_BT_EVT_NTF"; + case CMD_KPLAYER_START: return "CMD_KPLAYER_START"; + case CMD_KPLAYER_STOP: return "CMD_KPLAYER_STOP"; + case CMD_KPLAYER_NOTIF_DUR: return "CMD_KPLAYER_NOTIF_DUR"; + case CMD_KPLAYER_HOST_ACTION: return "CMD_KPLAYER_HOST_ACTION"; + case CMD_KPLAYER_CTR_NTF_BASE: return "CMD_KPLAYER_CTR_NTF_BASE"; + case CMD_KPLAYER_CTR_CREATED: return "CMD_KPLAYER_CTR_CREATED"; + case CMD_KPLAYER_CTR_DELED: return "CMD_KPLAYER_CTR_DELED"; + case CMD_KPLAYER_CTR_PLAY: return "CMD_KPLAYER_CTR_PLAY"; + case CMD_KPLAYER_CTR_STOP: return "CMD_KPLAYER_CTR_STOP"; + case CMD_KPLAYER_CTR_PAUSE: return "CMD_KPLAYER_CTR_PAUSE"; + case CMD_KPLAYER_CTR_SEEK: return "CMD_KPLAYER_CTR_SEEK"; + case CMD_KPLAYER_CTR_SET_URL: return "CMD_KPLAYER_CTR_SET_URL"; + case CMD_KPLAYER_CTR_SET_VOLUME: return "CMD_KPLAYER_CTR_SET_VOLUME"; + case CMD_KPLAYER_CTR_SET_MUTE: return "CMD_KPLAYER_CTR_SET_MUTE"; + case CMD_KPLAYER_CTR_SET_NXT_URL: return "CMD_KPLAYER_CTR_SET_NXT_URL"; + case CMD_KPLAYER_CTR_SET_NEXT: return "CMD_KPLAYER_CTR_SET_NEXT"; + case CMD_KPLAYER_CTR_SET_PREV: return "CMD_KPLAYER_CTR_SET_PREV"; + case CMD_ALARM_SYNC_REQ: return "CMD_ALARM_SYNC_REQ"; + case CMD_ALARM_SYNC_RSP: return "CMD_ALARM_SYNC_RSP"; + case CMD_ALARM_ADD: return "CMD_ALARM_ADD"; + case CMD_ALARM_REMOVE: return "CMD_ALARM_REMOVE"; + case CMD_ALARM_REMOVEALL: return "CMD_ALARM_REMOVEALL"; + case CMD_REMAIND_SYNC_REQ: return "CMD_REMAIND_SYNC_REQ"; + case CMD_REMAIND_SYNC_RSP: return "CMD_REMAIND_SYNC_RSP"; + case CMD_REMAIND_ADD: return "CMD_REMAIND_ADD"; + case CMD_REMAIND_REMOVE: return "CMD_REMAIND_REMOVE"; + case CMD_REMAIND_REMOVEALL: return "CMD_REMAIND_REMOVEALL"; + case CMD_ASSISTANT_STATUS: return "CMD_ASSISTANT_STATUS"; + case CMD_ASSISTANT_RUNNING: return "CMD_ASSISTANT_RUNNING"; + case CMD_ASSISTANT_NOTIFY: return "CMD_ASSISTANT_NOTIFY"; + case CMD_SESSION_ALARM_SYNC: return "CMD_SESSION_ALARM_SYNC"; + case CMD_WORKDAY_DB_REQ: return "CMD_WORKDAY_DB_REQ"; + case CMD_WORKDAY_DB_RSP: return "CMD_WORKDAY_DB_RSP"; + case CMD_OTA_NOTIFY: return "CMD_OTA_NOTIFY"; + case CMD_OTA_STATUS: return "CMD_OTA_STATUS"; + case CMD_OTA_RUNNOW: return "CMD_OTA_RUNNOW"; + case CMD_LOG_CONFIG: return "CMD_LOG_CONFIG"; + default: return "Unknown CMD"; + } +} + +const char* ModuleNameToString(MODULE_NAME modName) +{ + switch(modName) + { + case MODULE_CONTROLLER: return "MODULE_CONTROLLER"; + case MODULE_ALARM: return "MODULE_ALARM"; + case MODULE_CALL: return "MODULE_CALL"; + case MODULE_VOICEENGINE: return "MODULE_VOICEENGINE"; + case MODULE_PLAYER: return "MODULE_PLAYER"; + case MODULE_CONFIGURE: return "MODULE_CONFIGURE"; + case MODULE_OTA: return "MODULE_OTA"; + case MODULE_WIFI: return "MODULE_WIFI"; + case MODULE_BT: return "MODULE_BT"; + case MODULE_KPLAYER: return "MODULE_KPLAYER"; + case MODULE_KPLAYER_TEST: return "MODULE_KPLAYER_TEST"; + case MODULE_SPLAYER: return "MODULE_SPLAYER"; + case MODULE_SPLAYER_TEST: return "MODULE_SPLAYER_TEST"; + case MODULE_LIGHT_MCU: return "MODULE_LIGHT_MCU"; + case MODULE_BLUEKC: return "MODULE_BLUEKC"; + case MODULE_BLUEKC_TEST: return "MODULE_BLUEKC_TEST"; + case MODULE_MANUFACTURE: return "MODULE_MANUFACTURE"; + case MODULE_BT_DEMO: return "MODULE_BT_DEMO"; + case MODULE_LOG_CTRL: return "MODULE_LOG_CTRL"; + } + + return "Unknown Module Name"; +} + diff --git a/Framework/libuvEngine/libuv_dbus.c b/Framework/libuvEngine/libuv_dbus.c deleted file mode 100644 index e73264b..0000000 --- a/Framework/libuvEngine/libuv_dbus.c +++ /dev/null @@ -1,2405 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "log.h" -#include "libuv_dbus.h" -#include "json_struct.h" -#include "inet_api.h" -#include "crypto.h" -#include "server_addr.h" -#ifdef ENABLE_COUNT_DEBUG -#include "monitor.h" -#endif - -#ifdef ENABLE_COUNT_DEBUG -#define MON_MSG_PROC_STAT ("Message Process") -#define MON_MSG_BST_PROC_STAT ("Boardcast Message Process") -#define MON_USER_MSG_PROC_STAT ("User Message Process") -#define MON_USER_MSG_BST_PROC_STAT ("User Boardcast Message Process") -#endif - -typedef void (*OnDBusSendError)(int, void*); -static void uvOpenKeyEventCb(uv_fs_t* puvFs); - -typedef struct LOOP_TASK_ARRAY -{ - uv_loop_t* pLoop; - int isRunning; - - struct LOOP_TASK_ARRAY *next, *prev; -} *PLOOP_TASK_ARRAY; - -typedef struct -{ - key_t shmKey; -// uint32_t tarMask; -// uint32_t tmSend; - uint32_t msgSize; - - UT_hash_handle hh; ///< UT Hash handle -} UV_SHM_ITEM, *PUV_SHM_ITEM; - -typedef struct -{ - long int msgMask; - unsigned char pMsgContext[0]; -} DBUS_MSG_DATA, *PDBUS_MSG_DATA; - -typedef struct -{ - DBusConnection* pBus; - const char* pBusName; - uint32_t busCmd; - JSON_ENGINE_TYPE type; - void* pStruct; - int iSize; - OnDBusAsyncSendTo cbSendTo; - int enBase64; -} DBUS_ASYNC_PARAMS, *PDBUS_ASYNC_PARAMS; - -static LIBUV_DBUS_PARAMS g_LibuvDBusParam; - -static uv_idle_t g_uvIdleHandle; -static uv_timer_t g_uvTimerPing; -static uv_fs_t g_uvKeyEvent; -static WORKDAY_INFO g_workDayArray; -static WIFI_STATUS g_WifiConnStatus = WIFI_CONNECTED; -static PDBUS_MSG_PROC g_pMsgProcList = NULL; -static uv_rwlock_t g_uvLoopRwLock; -static PLOOP_TASK_ARRAY g_LoopArray = NULL; -static unsigned int g_EnHBLExit = TRUE; -static uv_rwlock_t g_uvMsgProcRwLock; - -#if USED_SHM_TO_DBUS -static uv_rwlock_t g_uvShmHashRwLock; -static PUV_SHM_ITEM g_pShmTbl = NULL; - -static void __addShmIdToTable(key_t shmKey, uint32_t tmSend, uint32_t tarMask, uint32_t msgSize) -{ - PUV_SHM_ITEM pItem = NULL; - - uv_rwlock_rdlock(&g_uvShmHashRwLock); - HASH_FIND_INT(g_pShmTbl, &shmKey, pItem); - uv_rwlock_rdunlock(&g_uvShmHashRwLock); - - if(pItem == NULL) - { - pItem = (PUV_SHM_ITEM)malloc(sizeof(UV_SHM_ITEM)); - - memset(pItem, 0, sizeof(UV_SHM_ITEM)); - pItem->shmKey = shmKey; - - uv_rwlock_wrlock(&g_uvShmHashRwLock); - HASH_ADD_INT(g_pShmTbl, shmKey, pItem); - uv_rwlock_wrunlock(&g_uvShmHashRwLock); - } - - pItem->tmSend = tmSend; - pItem->tarMask = tarMask; - pItem->msgSize = msgSize; -} - -static void __removeReqIdFromTable(key_t shmKey) -{ - PUV_SHM_ITEM pItem = NULL; - - uv_rwlock_rdlock(&g_uvShmHashRwLock); - HASH_FIND_INT(g_pShmTbl, &shmKey, pItem); - uv_rwlock_rdunlock(&g_uvShmHashRwLock); - - if(pItem != NULL) - { - uv_rwlock_wrlock(&g_uvShmHashRwLock); - HASH_DEL(g_pShmTbl, pItem); - uv_rwlock_wrunlock(&g_uvShmHashRwLock); - free(pItem); - } -} - -static void __uvShmTblTaskThreadCb(void *pParam) -{ - struct timeval tv; - PUV_SHM_ITEM pItem = NULL, pTmpItem = NULL; - - while(TRUE) - { - gettimeofday(&tv, NULL); - - HASH_ITER(hh, g_pShmTbl, pItem, pTmpItem) - { - int msgId; - - if(tv.tv_sec - pItem->tmSend <= 60) - { - continue; - } - - msgId = shmget((key_t)pItem->shmKey, pItem->msgSize, 0666 | IPC_CREAT); - - if(msgId == -1) - { - continue; - } - - // Not Boardcast Message - if((pItem->tarMask & 0xFFFF0000) != 0xFFFF0000) - { - PDBUS_MSG_DATA pData = (PDBUS_MSG_DATA)shmat(msgId, NULL, 0); - - if(pData == (void*)-1) - { - continue; - } - - // Nevery Recevied By Anyone - if(pData->msgMask == pItem->tarMask) - { - continue; - } - - shmdt(pData); - shmctl(msgId, IPC_RMID, 0); - __removeReqIdFromTable((key_t)pItem->shmKey); - } - } - - sleep(1); - } - - pthread_detach(pthread_self()); -} -#endif - -PLIBUV_DBUS_PARAMS DBusLibuvGetRuntime(void) -{ - if(g_LibuvDBusParam.pBus == NULL || g_LibuvDBusParam.pLoop == NULL) - { - return NULL; - } - - return &g_LibuvDBusParam; -} - -MODULE_NAME DBusLibGetModName(void) -{ - return g_LibuvDBusParam.modName; -} - -uv_loop_t* GetDBusDefaultLoop(void) -{ - if(g_LibuvDBusParam.pBus == NULL || g_LibuvDBusParam.pLoop == NULL) - { - return uv_default_loop(); - } - - return g_LibuvDBusParam.pLoop; -} - -static void uvAsyncCb(uv_async_t* pAsync) -{ - DBusConnection* pConn = (DBusConnection*)pAsync->data; - dbus_connection_read_write(pConn, 0); - - while(dbus_connection_dispatch(pConn) == DBUS_DISPATCH_DATA_REMAINS); -} - -static void uvTimeoutCb(uv_timer_t* pTimer) -{ - DBusTimeout* timeout = (DBusTimeout*)pTimer->data; - dbus_timeout_handle(timeout); -} - -static void uvPollCb(uv_poll_t* pPoll, int status, int events) -{ - DBusWatch* watch = (DBusWatch*)pPoll->data; - unsigned int uvFlags = 0; - - if(events & UV_READABLE) - { - uvFlags |= DBUS_WATCH_READABLE; - } - - if(events & UV_WRITABLE) - { - uvFlags |= DBUS_WATCH_WRITABLE; - } - - dbus_watch_handle(watch, uvFlags); -} - -static void uvIdleCb(uv_idle_t* phuvIdle) -{ - usleep(1000); -} - -static void uvFsAccessCb(uv_fs_t* puvFs) -{ - if(puvFs->result != 0) - { - IHW_EnableLogLevel((LOG_LEVEL)(LOG_Fatal | LOG_Error | LOG_Warn | LOG_Debug | LOG_Info), 1); - } - - uv_fs_req_cleanup(puvFs); - free(puvFs); -} - -static void uvReadKeyEventCb(uv_fs_t* puvFs) -{ - if(puvFs->result < 0) - { - uv_fs_req_cleanup(puvFs); - return; - } - else if(puvFs->result == 0) - { - uv_fs_t uvClose; - uv_fs_close(g_LibuvDBusParam.pLoop, &uvClose, g_uvKeyEvent.result, NULL); - } - else - { - uv_buf_t* puvIov = (uv_buf_t*)puvFs->data; - - if(puvIov->len == sizeof(struct input_event)) - { - struct input_event* pKeyEvt = (struct input_event*)puvIov->base; - - if(g_LibuvDBusParam.onKeyCb) - { -// LOG_EX(LOG_Info, "type = %u, code = %u, value = %u\n", pKeyEvt->type, pKeyEvt->code, pKeyEvt->value); - g_LibuvDBusParam.onKeyCb(pKeyEvt->type, pKeyEvt->code, pKeyEvt->value); - } - } - } - - uv_fs_req_cleanup(puvFs); - - usleep(1000); - uv_fs_open(g_LibuvDBusParam.pLoop, &g_uvKeyEvent, R16_TINA_KEY_EVENT_PATH, O_RDONLY, 0, uvOpenKeyEventCb); -} - -static void uvOpenKeyEventCb(uv_fs_t* puvFs) -{ - static uv_buf_t uvIoV; - static struct input_event keyEvent; - - if(puvFs->result < 0) - { - LOG_EX(LOG_Error, "Open Key Event File[%s] Error: %d\n", R16_TINA_KEY_EVENT_PATH, puvFs->result); - uv_fs_req_cleanup(puvFs); - return; - } - - uvIoV = uv_buf_init((void*)&keyEvent, sizeof(struct input_event)); - puvFs->data = (void*)&uvIoV; - - uv_fs_read(g_LibuvDBusParam.pLoop, &g_uvKeyEvent, puvFs->result, &uvIoV, 1, -1, uvReadKeyEventCb); - uv_fs_req_cleanup(puvFs); - - return; -} - -static void DBusAsyncFreeCb(void* pData) -{ - uv_async_t* pAsync = (uv_async_t*)pData; - - if(pAsync) - { - pAsync->data = NULL; - uv_close((uv_handle_t*)pAsync, (uv_close_cb)free); - } -} - -static void DBusPollFreeCb(void* pData) -{ - uv_poll_t* pPoll = (uv_poll_t*)pData; - - if(pPoll) - { - pPoll->data = NULL; - - uv_ref((uv_handle_t*)pPoll); - uv_poll_stop(pPoll); - uv_close((uv_handle_t*)pPoll, (uv_close_cb)free); - } -} - -static dbus_bool_t DBusAddWatchCb(DBusWatch* pWatch, void* pData) -{ - static int isCreate = 0; - int fdDBus, uvPollFlags = 0; - unsigned int dBusWatchFlags; - uv_poll_t* pPoll = NULL; - uv_loop_t* pLoop = (uv_loop_t*)pData; - - if(!dbus_watch_get_enabled(pWatch) - || dbus_watch_get_data(pWatch) != NULL - || isCreate != 0) - { - return TRUE; - } - - fdDBus = dbus_watch_get_unix_fd(pWatch); - dBusWatchFlags = dbus_watch_get_flags(pWatch); - - if(dBusWatchFlags & DBUS_WATCH_READABLE) - { - uvPollFlags |= UV_READABLE; - } - - if(dBusWatchFlags & DBUS_WATCH_WRITABLE) - { - uvPollFlags |= UV_WRITABLE; - } - - pPoll = (uv_poll_t*)malloc(sizeof(uv_poll_t)); - pPoll->data = (void*)pWatch; - - uv_poll_init(pLoop, pPoll, fdDBus); - uv_poll_start(pPoll, uvPollFlags, uvPollCb); - LOG_EX(LOG_Debug, "Create POOL by FD: %d\n", fdDBus); - - uv_unref((uv_handle_t*)pPoll); - - dbus_watch_set_data(pWatch, (void*)pPoll, DBusPollFreeCb); - - isCreate = 1; - return TRUE; -} - -static void DBusRemoveWatchCb(DBusWatch* pWatch, void* pData) -{ - uv_poll_t* pPoll = (uv_poll_t*)dbus_watch_get_data(pWatch); - - if(pPoll) - { - dbus_watch_set_data(pWatch, NULL, NULL); - } -} - -static void DBusNotifyWatchCb(DBusWatch* pWatch, void* pData) -{ - if(dbus_watch_get_enabled(pWatch)) - { - DBusAddWatchCb(pWatch, pData); - } - else - { - DBusRemoveWatchCb(pWatch, pData); - } -} - -static void DBusTimeoutFreeCb(void* pData) -{ - uv_timer_t* pTimer = (uv_timer_t*)pData; - - if(pTimer == NULL) - { - return; - } - - pTimer->data = NULL; - uv_timer_stop(pTimer); - uv_unref((uv_handle_t*)pTimer); - uv_close((uv_handle_t*)pTimer, (uv_close_cb)free); -} - -static dbus_bool_t DBusAddTimeoutCb(DBusTimeout* pTimeout, void* pData) -{ - uv_timer_t* pTimer = NULL; - uv_loop_t* pLoop = (uv_loop_t*)pData; - - if(!dbus_timeout_get_enabled(pTimeout) - || dbus_timeout_get_data(pTimeout) != NULL) - { - return TRUE; - } - - pTimer = (uv_timer_t*)malloc(sizeof(uv_timer_t)); - pTimer->data = pTimeout; - - uv_timer_init(pLoop, pTimer); - uv_timer_start(pTimer, uvTimeoutCb, dbus_timeout_get_interval(pTimeout), 0); - - dbus_timeout_set_data(pTimeout, (void*)pTimer, DBusTimeoutFreeCb); - return TRUE; -} - -static void DBusRemoveTimeoutCb(DBusTimeout* pTimeout, void* pData) -{ - uv_timer_t* pTimer = (uv_timer_t*)dbus_timeout_get_data(pTimeout); - - if(pTimer) - { - dbus_timeout_set_data(pTimeout, NULL, NULL); - } -} - -static void DBusNotifyTimeoutCb(DBusTimeout* pTimeout, void* pData) -{ - if(dbus_timeout_get_enabled(pTimeout)) - { - DBusAddTimeoutCb(pTimeout, pData); - } - else - { - DBusRemoveTimeoutCb(pTimeout, pData); - } -} - -static void DBusWakeupMainLoopCb(void* pData) -{ - uv_async_t* pAsync = (uv_async_t*)pData; - uv_async_send(pAsync); -} - -static void FreeDBusOnMsgCb(uv_work_t* pWork, int status) -{ - PDBUS_MSG_PACK pMsg = (PDBUS_MSG_PACK)pWork->data; - - if(pMsg) - { - free(pMsg); - } - free(pWork); -} - -#if 0 -static void DBusOnBoardcastMsgWorkCb(uv_work_t* pWork) -#else -static int DBusOnBoardcastMsgWorkCb(PDBUS_MSG_PACK pMsg) -#endif -{ - - pMsg->isBstMsg = TRUE; - // Message context on dbus message pad - if(pMsg->msgSize < DBUS_MSG_MAX_PAD_SIZE) - { - if(pMsg->busCmd == CMD_WIFI_STATE_NTF) - { - int err = 0; - PWIFI_STATUS_PRO pWifiInfo = (PWIFI_STATUS_PRO)Json2Struct((const char *)pMsg->pMsg, - JSON_WIFI_STATUS_NOTIFY, FALSE, &err); - - //LOG_EX(LOG_Debug, "pWifiInfo: %s\n", pMsg->pMsg); - if(pWifiInfo && err == 0) - { - if(pWifiInfo->wifi_evt == 0) - { - g_WifiConnStatus = WIFI_CONNECTED; - } - else - { - g_WifiConnStatus = WIFI_DISCONNECTED; - } - } - - if(pWifiInfo) - { - free(pWifiInfo); - } - } - else if(pMsg->busCmd == CMD_CFG_UPG_NOTIFY) - { - } - else if(pMsg->busCmd == CMD_LOG_CONFIG) - { - int err = 0; - PLOG_CFG_PROTOCOL pCfgInfo = (PLOG_CFG_PROTOCOL)Json2Struct((const char *)pMsg->pMsg, - JSON_ENGINE_LOG_CFG_CMD, FALSE, &err); - - //LOG_EX(LOG_Debug, "pCfgInfo: %s\n", pMsg->pMsg); - if(pCfgInfo && err == 0) - { - UpgradLogConfigure(pCfgInfo); - } - - if(pCfgInfo) - { - free(pCfgInfo); - } - } - else if(pMsg->busCmd != CMD_MISC_PING) - { - pMsg->msgDests = 0xFFFFFFFF; - if(g_LibuvDBusParam.onMsgCb) - { - g_LibuvDBusParam.onMsgCb(g_LibuvDBusParam.pLoop, g_LibuvDBusParam.pBus, pMsg); - } - - return 1; - } - } - - return 0; -} - -#if 0 -static void DBusOnMsgWorkAPICb(uv_work_t* pWork) -#else -static int DBusOnMsgWorkAPICb(PDBUS_MSG_PACK pMsg) -#endif -{ - int err = 0; - - pMsg->isBstMsg = FALSE; - - // Message context on dbus message pad - if(pMsg->msgSize < DBUS_MSG_MAX_PAD_SIZE) - { - if(pMsg->busCmd >= CMD_CFG_ADD_REQ && pMsg->busCmd < CMD_CFG_UPG_NOTIFY) - { - OnCfgMsgProcess(pMsg->msgSrc, pMsg->busCmd, pMsg->pMsg); - } - else if(pMsg->busCmd == CMD_LOG_CONFIG) - { - PLOG_CFG_PROTOCOL pCfgInfo = (PLOG_CFG_PROTOCOL)Json2Struct((const char *)pMsg->pMsg, - JSON_ENGINE_LOG_CFG_CMD, FALSE, &err); - - //LOG_EX(LOG_Debug, "pCfgInfo: %s\n", pMsg->pMsg); - if(pCfgInfo && err == 0) - { - UpgradLogConfigure(pCfgInfo); - } - - if(pCfgInfo) - { - free(pCfgInfo); - } - } - else if(pMsg->busCmd == CMD_WORKDAY_DB_RSP) - { - PWORKDAY_INFO pWorkDayInfo = (PWORKDAY_INFO)Json2Struct((const char *)pMsg->pMsg, - JSON_ENGINE_WORKDAY_REQ, FALSE, &err); - - //LOG_EX(LOG_Debug, "WorkDay: %s\n", pMsg->pMsg); - if(pWorkDayInfo && err == 0) - { - memcpy(&g_workDayArray, pWorkDayInfo, sizeof(WORKDAY_INFO)); - g_workDayArray.isReady = TRUE; - LOG_EX(LOG_Debug, "Sync Alarm Database: %s\n", pMsg->pMsg); - } - - //LOG_EX2(LOG_Debug, "Database: %s\n", pMsg->pMsg); - - if(pWorkDayInfo) - { - free(pWorkDayInfo); - } - } - else if(pMsg->busCmd != CMD_MISC_PING) - { - if(g_LibuvDBusParam.onMsgCb) - { - g_LibuvDBusParam.onMsgCb(g_LibuvDBusParam.pLoop, g_LibuvDBusParam.pBus, pMsg); - } - - return 1; - } - } - else // More than 4K size used Share Memory - { - LOG_EX(LOG_Error, "Receive Message Error Size: %d\n", pMsg->msgSize); -#if 0 - PDBUS_MSG_DATA pData = NULL; - int key = strtol(pMsg->pMsg, NULL, 10); - - int msgId = shmget((key_t)key, pMsg->msgSize, 0666 | IPC_CREAT); - - if(msgId == -1) - { - return; - } - - pData = (PDBUS_MSG_DATA)shmat(msgId, NULL, 0); - - if(pData == (void*)-1) - { - return; - } - - //print_hex_dump_bytes("send_", 2, pData, pMsg->msgSize); - - pMsg->pMsg = pData->pMsgContext; - pMsg->msgSize -= sizeof(long int); - - if(pMsg->busCmd != CMD_MISC_PING) - { - g_LibuvDBusParam.onMsgCb(g_LibuvDBusParam.pLoop, g_LibuvDBusParam.pBus, pMsg); - } - - pData->msgMask &= ~(1 << g_LibuvDBusParam.modName); - - // Cleanup Share Memory - if(pData->msgMask == 0) - { - shmctl(msgId, IPC_RMID, 0); -#if USED_SHM_TO_DBUS - __removeReqIdFromTable((key_t)key); -#endif - } - - shmdt(pData); -#endif - } - - return 0; -} - -static DBusHandlerResult DBusOnMsgCb(DBusConnection* pConn, DBusMessage* pMsg, void* user_data) -{ -#if 0 - struct timeval tmBegin, tmEnd; - long long diffTm; -#endif - DBusError error; - PDBUS_MSG_PROC pMsgProc = NULL; - - PDBUS_MSG_PACK pMsgPack = (PDBUS_MSG_PACK)malloc(sizeof(DBUS_MSG_PACK)); - - if(pMsgPack == NULL) - { - LOG_EX(LOG_Error, "Receive Message: No Memory\n"); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - memset(pMsgPack, 0, sizeof(DBUS_MSG_PACK)); - - dbus_error_init(&error); - - if(dbus_message_is_signal(pMsg, DBUS_MESSAGE_INTERFACE_NAME, "Notify")) - { - if(dbus_message_get_args(pMsg, &error, - DBUS_TYPE_UINT32, &pMsgPack->msgSrc, // from - DBUS_TYPE_UINT32, &pMsgPack->msgDests, // to -1 means all except it's self -#if USED_SHM_TO_DBUS - DBUS_TYPE_UINT32, &pMsgPack->tmTickMSec, // timestamp for msecond -#endif - DBUS_TYPE_UINT32, &pMsgPack->busCmd, // command type - DBUS_TYPE_STRING, &pMsgPack->pMsg, // message context if had - DBUS_TYPE_INVALID)) - { - pMsgPack->msgSize = strlen((char*)pMsgPack->pMsg); - // reset timeout timer - if(g_LibuvDBusParam.onHblCb && pMsgPack->msgSrc != g_LibuvDBusParam.modName) - { - HeartDaemonUpgrade(pMsgPack->msgSrc); - } - - // Dispatch message except from it's self - if(pMsgPack->msgSrc != g_LibuvDBusParam.modName - && pMsgPack->msgDests & (1 << g_LibuvDBusParam.modName)) - { - if(g_LibuvDBusParam.onMsgCb == NULL) - { - pMsgProc = (PDBUS_MSG_PROC)malloc(sizeof(struct DBUS_MSG_PROC)); - - if(pMsgProc == NULL) - { - LOG_EX(LOG_Error, "Receive Message: No Memory\n"); - free(pMsgPack); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - memset(pMsgProc, 0, sizeof(struct DBUS_MSG_PROC)); - memcpy(&pMsgProc->msgContent, pMsgPack, sizeof(DBUS_MSG_PACK)); - pMsgProc->msgContent.pMsg = strdup(pMsgPack->pMsg); - pMsgProc->msgFrom = 0; - - uv_rwlock_wrlock(&g_uvMsgProcRwLock); - DL_APPEND(g_pMsgProcList, pMsgProc); - uv_rwlock_wrunlock(&g_uvMsgProcRwLock); - } - else - { - DBusOnBoardcastMsgWorkCb(pMsgPack); - } - } - } - else - { - LOG_EX(LOG_Error, "Receive Notify Message Error: %s\n", error.message); - dbus_error_free(&error); - } - - free(pMsgPack); - return DBUS_HANDLER_RESULT_HANDLED; - } - else if(dbus_message_is_method_call(pMsg, DBUS_MESSAGE_INTERFACE_NAME, "API")) - { - if(dbus_message_get_args(pMsg, &error, - DBUS_TYPE_UINT32, &pMsgPack->msgSrc, // from - DBUS_TYPE_UINT32, &pMsgPack->msgDests, // to -1 means all except it's self -#if USED_SHM_TO_DBUS - DBUS_TYPE_UINT32, &pMsgPack->tmTickMSec, // timestamp for msecond -#endif - DBUS_TYPE_UINT32, &pMsgPack->busCmd, // command type - DBUS_TYPE_UINT32, &pMsgPack->msgSize, // message size(in bytes) - DBUS_TYPE_STRING, &pMsgPack->pMsg, // message context if had - DBUS_TYPE_INVALID)) - { - // reset timeout timer - if(g_LibuvDBusParam.onHblCb && pMsgPack->msgSrc != g_LibuvDBusParam.modName) - { - HeartDaemonUpgrade(pMsgPack->msgSrc); - } - - // Dispatch message except from it's self - if(pMsgPack->msgSrc != g_LibuvDBusParam.modName - && pMsgPack->msgDests == (1 << g_LibuvDBusParam.modName)) - { - if(g_LibuvDBusParam.onMsgCb == NULL) - { - pMsgProc = (PDBUS_MSG_PROC)malloc(sizeof(struct DBUS_MSG_PROC)); - - if(pMsgProc == NULL) - { - LOG_EX(LOG_Error, "Receive Message: No Memory\n"); - free(pMsgPack); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; - } - - memset(pMsgProc, 0, sizeof(struct DBUS_MSG_PROC)); - memcpy(&pMsgProc->msgContent, pMsgPack, sizeof(DBUS_MSG_PACK)); - pMsgProc->msgContent.pMsg = strdup(pMsgPack->pMsg); - pMsgProc->msgFrom = 1; - - uv_rwlock_wrlock(&g_uvMsgProcRwLock); - DL_APPEND(g_pMsgProcList, pMsgProc); - uv_rwlock_wrunlock(&g_uvMsgProcRwLock); - } - else - { - DBusOnMsgWorkAPICb(pMsgPack); - } - } - } - else - { - LOG_EX(LOG_Error, "Receive API Message Error: %s\n", error.message); - dbus_error_free(&error); - } - - free(pMsgPack); - return DBUS_HANDLER_RESULT_HANDLED; - } - - free(pMsgPack); - return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; -} - -static void freeSHMResource(int shmId, void* pData) -{ - // Cleanup Share Memory - if(pData) - { - shmdt(pData); - } - - shmctl(shmId, IPC_RMID, 0); -} - -static void FreeDBusSendToAsyncCb(uv_work_t* pWork, int status) -{ - PDBUS_ASYNC_PARAMS pParam = (PDBUS_ASYNC_PARAMS)pWork->data; - free(pParam->pStruct); - free(pParam); - free(pWork); -} - -static void DBusSendToAsyncCb(uv_work_t* pWork) -{ - int err = 0; - PDBUS_ASYNC_PARAMS pParam = (PDBUS_ASYNC_PARAMS)pWork->data; - const char *pJsonStr = Struct2Json(pParam->pStruct, pParam->type, pParam->enBase64, &err); - - if(pJsonStr == NULL || err != 0) - { - pParam->cbSendTo(err); - return; - } - - err = DBusSendToCommand(pParam->pBus, pParam->pBusName, pParam->busCmd, pJsonStr); - - free((void*)pJsonStr); - - pParam->cbSendTo(err); -} - -int DBusJsonSendToCommandAsync(DBusConnection* pBus, - const char* pBusName, - uint32_t busCmd, - JSON_ENGINE_TYPE type, - void* pStruct, - int iSize, - OnDBusAsyncSendTo cbSendTo, - int enBase64) -{ - PDBUS_ASYNC_PARAMS pParam = NULL; - uv_work_t* puvWork = NULL; - - if(cbSendTo == NULL) - { - return 0; - } - - pParam = (PDBUS_ASYNC_PARAMS)malloc(sizeof(DBUS_ASYNC_PARAMS)); - puvWork = (uv_work_t*)malloc(sizeof(uv_work_t)); - - pParam->pBus = pBus; - pParam->pBusName = pBusName; - pParam->busCmd = busCmd; - pParam->type = type; - pParam->iSize = iSize; - pParam->pStruct = malloc(iSize); - pParam->cbSendTo = cbSendTo; - pParam->enBase64 = enBase64; - memcpy(pParam->pStruct, pStruct, iSize); - - puvWork->data = (void*)pParam; - uv_queue_work(g_LibuvDBusParam.pLoop, puvWork, DBusSendToAsyncCb, FreeDBusSendToAsyncCb); - - return 0; -} - -int DBusJsonSendToCommand(DBusConnection* pBus, - const char* pBusName, - uint32_t busCmd, - JSON_ENGINE_TYPE type, - void* pStruct, - int enBase64) -{ - int ret, err = 0; - const char* pJsonStr = Struct2Json(pStruct, type, enBase64, &err); - - if(pJsonStr == NULL || err != 0) - { - return err; - } - - ret = DBusSendToCommand(pBus, pBusName, busCmd, pJsonStr); - - free((void*)pJsonStr); - - return ret; -} - -int DBusJsonBoardcastCommand(DBusConnection* pBus, - uint32_t msgToMask, - uint32_t busCmd, - JSON_ENGINE_TYPE type, - void* pStruct, - int enBase64) -{ - int ret, err = 0; - const char* pJsonStr = Struct2Json(pStruct, type, enBase64, &err); - - if(pJsonStr == NULL || err != 0) - { - return err; - } - - ret = DBusBoardcastCommand(pBus, msgToMask, busCmd, pJsonStr); - - free((void*)pJsonStr); - return ret; -} - -static unsigned int __getShmReqId(void) -{ - static unsigned int g_shmReqId = 1; - unsigned int iReqId; - - if(g_shmReqId >= 0xFFFF - 1) - { - g_shmReqId = 1; - } - - iReqId = __sync_fetch_and_add(&g_shmReqId, 1); - - return (iReqId & 0xFFFF) | (g_LibuvDBusParam.modName << 16); -} - -int DBusSendToCommand(DBusConnection* pBus, - const char* pBusName, - uint32_t busCmd, - const char* pContext) -{ -#if USED_SHM_TO_DBUS - struct timeval tv; -#endif - int i; - int msgId; - //char msgContext[DBUS_MSG_MAX_PAD_SIZE]; - DBusMessage* pMsg = NULL; - uint32_t msgLen = 0; - uint32_t msgToMask = 0; - OnDBusSendError pErrorCb = NULL; - uint8_t* pMsgInfo = NULL; - PDBUS_MSG_DATA pShmData = NULL; - const char* pPath = NULL; - char* pMsgContent = NULL; - -#if 0 - if(pContext == NULL || (msgLen = strlen(pContext)) <= 0) - { - return (-ERR_INPUT_PARAMS); - } -#else - if(pContext == NULL) - { - pContext = ""; - msgLen = 0; - } - else - { - msgLen = strlen(pContext); - } -#endif - - pMsgContent = (char*)malloc(msgLen + 1); - - if(pMsgContent == NULL) - { - LOG_EX(LOG_Error, "Malloc memory %d error\n", msgLen + 1); - return -ERR_MALLOC_MEMORY; - } - - pMsgInfo = (uint8_t*)pMsgContent; - - memset(pMsgContent, 0, msgLen + 1); - - if(pBus == NULL) - { - pBus = g_LibuvDBusParam.pBus; - } - - for(i = 0; (i < sizeof(g_pModInfoTable) / sizeof(g_pModInfoTable[0])); i++) - { - // Skip match it'self - if(strcmp(g_pModInfoTable[i].modAliase, pBusName) == 0) - { - msgToMask = 1 << i; - pPath = g_pModInfoTable[i].modPath; - break; - } - } - - pMsg = dbus_message_new_method_call(pBusName, - pPath, - DBUS_MESSAGE_INTERFACE_NAME, - "API"); - - if(pMsg == NULL) - { - free(pMsgContent); - LOG_EX(LOG_Error, "DBus Create Message Error\n"); - return -ERR_DBUS_CREATE_MSG; - } - - dbus_message_set_no_reply(pMsg, TRUE); - -#if USED_SHM_TO_DBUS - gettimeofday(&tv, NULL); -#endif - - if(msgLen < DBUS_MSG_MAX_PAD_SIZE) - { - strcpy(pMsgContent, pContext); - } - else - { -#if 0 - int msgKey = __getShmReqId(); - msgLen += sizeof(long int); - - // Make message with Memory Share - msgId = shmget((key_t)msgKey, msgLen, 0666 | IPC_CREAT); - - if(msgId == -1) - { - perror("shmget_"); - return (-ERR_CREATE_SHM); - } - else - { - pShmData = (PDBUS_MSG_DATA)shmat(msgId, NULL, 0); - - if(pShmData == (void*)-1) - { - return -ERR_MAP_SHM; - } - - pShmData->msgMask = msgToMask; - - memcpy(pShmData->pMsgContext, pContext, msgLen); - sprintf(pMsgInfo, "%d", msgKey); - - shmdt(pShmData); - //print_hex_dump_bytes("send_", 2, pShmData, msgLen); - //strcpy(pMsgInfo, (void*)&msgKey, sizeof(key_t)); - -#if USED_SHM_TO_DBUS - __addShmIdToTable((key_t)msgKey, tv.tv_sec, msgToMask, msgLen); -#endif - pErrorCb = freeSHMResource; - } -//#else -#endif - free(pMsgContent); - LOG_EX(LOG_Error, "Send Message size %d more than DBUS_MSG_MAX_PAD_SIZE, busCmd = %u, pBusName = %s\n", - msgLen, busCmd, pBusName); - return -ERR_INPUT_PARAMS; - } - - dbus_message_append_args(pMsg, - DBUS_TYPE_UINT32, &g_LibuvDBusParam.modName, // from - DBUS_TYPE_UINT32, &msgToMask, // to -1 means all except it's self -#if USED_SHM_TO_DBUS - DBUS_TYPE_UINT32, &tv.tv_sec, // timestamp for msecond -#endif - DBUS_TYPE_UINT32, &busCmd, // command type - DBUS_TYPE_UINT32, &msgLen, // message size(in bytes) - DBUS_TYPE_STRING, &pMsgInfo, - // msgLen[0, 512): pad to message; msgLen[512, ~): memory map key, - //DBUS_TYPE_ARRAY, DBUS_TYPE_BYTE, &pMsgInfo, (msgLen < DBUS_MSG_MAX_PAD_SIZE) ? msgLen : sizeof(key_t), - DBUS_TYPE_INVALID); - - free(pMsgContent); - - if(!dbus_connection_send(pBus, pMsg, NULL)) - { - LOG_EX(LOG_Error, "Send Message Error\n"); - if(pErrorCb) - { - pErrorCb(msgId, pShmData); - } - - return -ERR_BUS_SEND_MSG; - } - - //dbus_connection_flush(pBus); - dbus_message_unref(pMsg); - - usleep(100); - - return 0; -} - -int DBusBoardcastCommand(DBusConnection* pBus, - uint32_t msgToMask, - uint32_t busCmd, - const char* pContext) -{ -#if USED_SHM_TO_DBUS - struct timeval tv; -#endif - DBusMessage* pMsg = NULL; - - if(pContext == NULL) - { - pContext = ""; - } - - if(strlen(pContext) >= DBUS_MSG_MAX_PAD_SIZE) - { - LOG_EX(LOG_Error, "Msg size = %u more than DBUS_MSG_MAX_PAD_SIZE\n", strlen(pContext)); - return -ERR_DBUS_MSG_TO_LARGE; - } - - if(pBus == NULL) - { - pBus = g_LibuvDBusParam.pBus; - } - - pMsg = dbus_message_new_signal(g_LibuvDBusParam.pBusPath, DBUS_MESSAGE_INTERFACE_NAME, "Notify"); - - if(pMsg == NULL) - { - return -ERR_DBUS_CREATE_MSG; - } - - dbus_message_set_no_reply(pMsg, TRUE); - -#if USED_SHM_TO_DBUS - gettimeofday(&tv, NULL); -#endif - - dbus_message_append_args(pMsg, - DBUS_TYPE_UINT32, &g_LibuvDBusParam.modName, // from - DBUS_TYPE_UINT32, &msgToMask, // to -1 means all except it's self -#if USED_SHM_TO_DBUS - DBUS_TYPE_UINT32, &tv.tv_sec, // timestamp for msecond -#endif - DBUS_TYPE_UINT32, &busCmd, // command type - DBUS_TYPE_STRING, &pContext, - DBUS_TYPE_INVALID); - - if(!dbus_connection_send(pBus, pMsg, NULL)) - { - return -ERR_BUS_SEND_MSG; - } - - //dbus_connection_flush(pBus); - dbus_message_unref(pMsg); - - usleep(100); - return 0; -} - -static void __addNewLoopTask(uv_loop_t* pLoop) -{ - PLOOP_TASK_ARRAY pItem = NULL; - PLOOP_TASK_ARRAY pTask = NULL; - if(pLoop == NULL) - { - return; - } - - uv_rwlock_wrlock(&g_uvLoopRwLock); - LL_FOREACH(g_LoopArray, pItem) - { - if(pItem->pLoop == pLoop) - { - LOG_EX(LOG_Warn, "Loop %p is added\n", pLoop); - uv_rwlock_wrunlock(&g_uvLoopRwLock); - return; - } - } - - pTask = (PLOOP_TASK_ARRAY)malloc(sizeof(struct LOOP_TASK_ARRAY)); - if(pTask == NULL) - { - LOG_EX(LOG_Error, "Malloc Memory Error\n"); - return; - } - memset(pTask, 0, sizeof(struct LOOP_TASK_ARRAY)); - pTask->pLoop = pLoop; - pTask->isRunning = FALSE; - LL_APPEND(g_LoopArray, pTask); - uv_rwlock_wrunlock(&g_uvLoopRwLock); -} - -static void __uvLoopRuntime(void *pParam) -{ - uv_loop_t* pLoop = (uv_loop_t*)pParam; - - if(pLoop) - { - while(TRUE) - { - uv_run(pLoop, UV_RUN_DEFAULT); - usleep(1000); - } - } - - pthread_detach(pthread_self()); -} - -static void __runUVLoopTask(uv_loop_t* pLoop, void* pCallback) -{ - uv_thread_t uvThread; - if(pLoop == NULL) - { - return; - } - - uv_thread_create(&uvThread, __uvLoopRuntime, pLoop); -} - -void RunUVLoop(uv_loop_t *pLoop) -{ -#if 1 - int more; - - while(TRUE) - { - more = uv_run(g_LibuvDBusParam.pLoop, UV_RUN_ONCE); - - if(more == FALSE) - { - more = uv_loop_alive(g_LibuvDBusParam.pLoop); - - if(uv_run(g_LibuvDBusParam.pLoop, UV_RUN_NOWAIT) != 0) - { - more = TRUE; - } - } - } -#else - int more; - - do - { - if(pLoop && pLoop != g_LibuvDBusParam.pUserLoop) - { - more = uv_run(pLoop, UV_RUN_ONCE); - - if(more == FALSE) - { - more = uv_loop_alive(pLoop); - - if(uv_run(pLoop, UV_RUN_NOWAIT) != 0) - { - more = TRUE; - } - } - } - - if(g_LibuvDBusParam.pUserLoop) - { - more = uv_run(g_LibuvDBusParam.pUserLoop, UV_RUN_ONCE); - - if(more == FALSE) - { - more = uv_loop_alive(g_LibuvDBusParam.pUserLoop); - - if(uv_run(g_LibuvDBusParam.pUserLoop, UV_RUN_NOWAIT) != 0) - { - more = TRUE; - } - } - } - - if(g_LibuvDBusParam.pLoop) - { - more = uv_run(g_LibuvDBusParam.pLoop, UV_RUN_ONCE); - - if(more == FALSE) - { - more = uv_loop_alive(g_LibuvDBusParam.pLoop); - - if(uv_run(g_LibuvDBusParam.pLoop, UV_RUN_NOWAIT) != 0) - { - more = TRUE; - } - } - } - } - while(TRUE); -//#else - //__runUVLoopTask(pLoop, NULL); - //__addNewLoopTask(pLoop); -#endif -} - -static void __uvDBusRecvProc(void *pParams) -{ - while(TRUE) - { - DBusMessage* pMsg = NULL; - dbus_connection_read_write(g_LibuvDBusParam.pBus, 0); - - pMsg = dbus_connection_pop_message(g_LibuvDBusParam.pBus); - - if(pMsg != NULL) - { - DBusOnMsgCb(g_LibuvDBusParam.pBus, pMsg, NULL); - } - - usleep(100); - } -} - -void DBusMsgCleanup(PDBUS_MSG_PACK pMsg) -{ - if(pMsg) - { - if(pMsg->pMsg) - { - free(pMsg->pMsg); - } - - free(pMsg); - } -} - -PDBUS_MSG_PACK DBusGetMessage(void) -{ - int iCount, ret = 0; - PDBUS_MSG_PACK pMsg = NULL; - PDBUS_MSG_PROC pItem = NULL, pTmp = NULL; - - if(g_LibuvDBusParam.onMsgCb) - { - return NULL; - } - - DL_COUNT(g_pMsgProcList, pItem, iCount); - - if(iCount == 0) - { - return pMsg; - } - - pItem = NULL; - uv_rwlock_wrlock(&g_uvMsgProcRwLock); - DL_FOREACH_SAFE(g_pMsgProcList, pItem, pTmp) - { - if(pItem->msgFrom == 0) - { - ret = DBusOnBoardcastMsgWorkCb(&pItem->msgContent); - } - else - { - ret = DBusOnMsgWorkAPICb(&pItem->msgContent); - } - - if(ret != 0) - { - pMsg = (PDBUS_MSG_PACK)malloc(sizeof(DBUS_MSG_PACK)); - - if(pMsg) - { - memset(pMsg, 0, sizeof(DBUS_MSG_PACK)); - memcpy(pMsg, &pItem->msgContent, sizeof(DBUS_MSG_PACK)); - pMsg->pMsg = strdup(pItem->msgContent.pMsg); - } - } - - DL_DELETE(g_pMsgProcList, pItem); - free(pItem->msgContent.pMsg); - free(pItem); - - break; - } - uv_rwlock_wrunlock(&g_uvMsgProcRwLock); - - return pMsg; -} - -#if 0 -static void __uvMsgProc(void *pParams) -{ -#ifdef ENABLE_COUNT_DEBUG - struct timeval tmBegin, tmEnd; - long long diffTm; -#endif - - while(TRUE) - { - int iMaxProcMsg = 100; - PDBUS_MSG_PROC pItem = NULL, pTmp = NULL; - - uv_rwlock_wrlock(&g_uvMsgProcRwLock); - DL_FOREACH_SAFE(g_pMsgProcList, pItem, pTmp) - { - if(--iMaxProcMsg == 0) - { - break; - } - -#ifdef ENABLE_COUNT_DEBUG - gettimeofday(&tmBegin, NULL); -#endif - if(pItem->msgFrom == 0) - { - DBusOnBoardcastMsgWorkCb(&pItem->msgContent); -#ifdef ENABLE_COUNT_DEBUG - gettimeofday(&tmEnd, NULL); - diffTm = (tmEnd.tv_sec * 1000000 + tmEnd.tv_usec) - (tmBegin.tv_sec * 1000000 + tmBegin.tv_usec); - MonUpgradeStatistical(MON_MSG_BST_PROC_STAT, diffTm); -#endif - } - else - { - DBusOnMsgWorkAPICb(&pItem->msgContent); -#ifdef ENABLE_COUNT_DEBUG - gettimeofday(&tmEnd, NULL); - diffTm = (tmEnd.tv_sec * 1000000 + tmEnd.tv_usec) - (tmBegin.tv_sec * 1000000 + tmBegin.tv_usec); - MonUpgradeStatistical(MON_MSG_PROC_STAT, diffTm); -#endif - } - - if(pItem->msgContent.pMsg) - { - free(pItem->msgContent.pMsg); - } - - DL_DELETE(g_pMsgProcList, pItem); - free(pItem); - } - uv_rwlock_wrunlock(&g_uvMsgProcRwLock); - usleep(1000); - } - - pthread_detach(pthread_self()); -} -#endif - -void SetHBLAutoExit(int flag) -{ - g_EnHBLExit = flag ? TRUE : FALSE; -} - -static void __dBusDeameonCb(MODULE_NAME modName, int status) -{ - LOG_EX(status == 0 ? LOG_Info : LOG_Error, - "Daemon %s(%d) Msg: [%s]\n", ModuleNameToString(modName), modName, - status == 0 ? "Connect" : "Disconnect"); - - if(status != 0 && modName == MODULE_CONTROLLER && g_EnHBLExit) - { - sleep(1); - //exit(0); - } -} - -static void __waitUDISKMount(void) -{ -#ifdef PLATFORM_R16 - const char* pDoneStat = "done"; - const char* pBootStatFile = "/tmp/booting_state"; - char buf[5]; - FILE* pFile; - - // wait system create setup status file - fprintf(stdout, "Wait boot status file create ......\n"); - while(access(pBootStatFile, F_OK) != 0) - { - usleep(10000); - } - - pFile = fopen(pBootStatFile, "rb"); - - if(pFile == NULL) - { - fprintf(stdout, "Open boot status file error\n"); - return; - } - - fprintf(stdout, "Wait boot status done ......\n"); - - // when UDISK mount, file /tmp/booting_state content is "done" - do - { - fseek(pFile, 0, SEEK_SET); - memset(buf, 0, 5); - fread(buf, 1, 4, pFile); // read 4 bytes status tags - - usleep(10000); - } - while(strncmp(buf, pDoneStat, strlen(pDoneStat)) != 0); - - fclose(pFile); - - fprintf(stdout, "Boot status done ......\n"); -#endif -} - -int GetServerModeFromCC(int defValue, int* pErr) -{ - char* pSvrMode = NULL; - int iValue = defValue; - - GetShellExecResult("curl --silent http://localhost:1705/httpenv/999 | grep 'env:' | awk '{print $3}'", &pSvrMode); - - if(pSvrMode == NULL) - { - if(pErr) - { - *pErr = -ERR_NO_ITEMS; - } - return defValue; - } - - iValue = strtol(pSvrMode, NULL, 10); - free(pSvrMode); - - if(errno == EINVAL || errno == ERANGE) - { - if(pErr) - { - *pErr = -ERR_STR_CONVERT; - } - - return defValue; - } - - if(pErr) - { - *pErr = 0; - } - - return iValue; -} - -DBusConnection* DBusWithLibuvInit(uv_loop_t* pUserLoop, - const char* pBusName, - OnDBusMessage cbOnMsg, - OnDaemonMsg cbOnHbl, - OnKeyEvent cbOnKey, - int* pErrno) -{ - int i, ret = 0; - DBusError error; - SERVER_MODULE_TYPE svrMode; - uv_async_t* pAsync = NULL; - DBusConnection* pBus = NULL; - uv_fs_t* puvFsReq; - //uv_thread_t uvMsgProcThread; - //uv_thread_t uvMsgRecvThread; - - //uv_thread_t uvLoopThread; - char rule[DBUS_MAXIMUM_MATCH_RULE_LENGTH - 1]; -#if USED_SHM_TO_DBUS - uv_thread_t uvSyncThread; -#endif - //uv_loop_t *pLoop = uv_loop_new(); - uv_loop_t *pLoop = pUserLoop; - - memset(&g_LibuvDBusParam, 0, sizeof(LIBUV_DBUS_PARAMS)); - - for(i = 0; (i < sizeof(g_pModInfoTable) / sizeof(g_pModInfoTable[0])); i++) - { - // Skip match it'self - if(strcmp(g_pModInfoTable[i].modAliase, pBusName) == 0) - { - g_LibuvDBusParam.modName = g_pModInfoTable[i].modName; - g_LibuvDBusParam.pBusName = g_pModInfoTable[i].modAliase; - g_LibuvDBusParam.pBusPath = g_pModInfoTable[i].modPath; - break; - } - } - - memset(&g_workDayArray, 0, sizeof(WORKDAY_INFO)); - srand(time(NULL)); - - if(pLoop == NULL || pBusName == NULL || pErrno == NULL) - { - if(pErrno) - { - *pErrno = -ERR_INPUT_PARAMS; - } - - LOG_EX(LOG_Error, "Input params error: pLoop = %p, pBusName = %p, pErrno = %p\n", - pLoop, pBusName, pErrno); - return NULL; - } - - puvFsReq = (uv_fs_t*)malloc(sizeof(uv_fs_t)); - - // wait UDISK mount, configure file save in UDISK partition - __waitUDISKMount(); - - CfgFileInit(); - - IHW_InitLOG(strrchr(pBusName, '.') + 1, NULL, TRUE); - IHW_EnableLogLevel(LOG_Fatal | LOG_Error | LOG_Warn | LOG_Debug | LOG_Info, 1); - IHW_RunLogService(); - - APP_BUILD_INFO(strrchr(pBusName, '.') + 1, GetCurrentVersion()); - - i = 0; - do - { - svrMode = CfgGetIntValueV1("Global.ServerMode", PUBLISH_MODE, &ret); - - if(ret != 0) - { - sleep(1); - } - else - { - usleep(1000); - } - - LOG_EX(LOG_Debug, "ServerMode = %d, Error = %d\n", svrMode, ret); - } while (ret != 0 && i++ <= 3); - - if(ret != 0) - { - LOG_EX(LOG_Error, "Read Server Mode Error: ret = %d\n", ret); - svrMode = CfgGetIntValueV2("ServerMode", PUBLISH_MODE, &ret); - - if(ret == 0) - { - LOG_EX(LOG_Warn, "Recovery Server Mode OK: ServerMode = %d\n", svrMode); - } - else - { - LOG_EX(LOG_Error, "CfgGetInvValueV2 Read Server Mode Error: ret = %d\n", ret); - svrMode = GetServerModeFromCC(PUBLISH_MODE, &ret); - - if(ret == 0) - { - LOG_EX(LOG_Warn, "Netease Controller Server Mode OK: ServerMode = %d\n", svrMode); - } - else - { - svrMode = PUBLISH_MODE; - LOG_EX(LOG_Error, "GetServerModeFromCC Read Server Mode Error: " - "ret = %d, Set to default: PUBLISH_MODE\n", ret); - } - } - } - - SetCurrentServerMode(svrMode); - DumpCurServerAddr("Default"); - -#if USED_SHM_TO_DBUS - uv_rwlock_init(&g_uvShmHashRwLock); -#endif - - uv_rwlock_init(&g_uvMsgProcRwLock); - uv_rwlock_init(&g_uvLoopRwLock); - - uv_fs_access(pLoop, puvFsReq, "/mnt/UDISK/debug.dbg", F_OK, uvFsAccessCb); - - memset(rule, 0, DBUS_MAXIMUM_MATCH_RULE_LENGTH - 1); - srand(time(NULL)); - - //setenv("UV_THREADPOOL_SIZE", "128", 1); - - dbus_error_init(&error); - - pBus = dbus_bus_get(DBUS_BUS_SESSION, &error); - - if (dbus_error_is_set(&error)) - { - LOG_EX(LOG_Error, "dbus: Could not acquire the session bus\n"); - - dbus_error_free(&error); - *pErrno = -ERR_GET_BUS; - return NULL; - } - - ret = dbus_bus_request_name(pBus, pBusName, DBUS_NAME_FLAG_REPLACE_EXISTING, &error); - - if(dbus_error_is_set(&error)) - { - LOG_EX(LOG_Error, "dbus: Could not request dbus name\n"); - - dbus_error_free(&error); - *pErrno = -ERR_REQUEST_BUS_NAME; - return NULL; - } - - if(ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) - { - LOG_EX(LOG_Error, "dbus: Could not request dbus name\n"); - - dbus_error_free(&error); - *pErrno = -ERR_REQUEST_BUS_NAME; - return NULL; - } -#if 1 - if(!dbus_connection_set_watch_functions(pBus, - DBusAddWatchCb, - DBusRemoveWatchCb, - DBusNotifyWatchCb, - (void*)pLoop, NULL)) - { - LOG_EX(LOG_Error, "dbus: Could not set watch function\n"); - - *pErrno = -ERR_SET_WATCH_FUNCTION; - return NULL; - } - - if(!dbus_connection_set_timeout_functions(pBus, - DBusAddTimeoutCb, - DBusRemoveTimeoutCb, - DBusNotifyTimeoutCb, - (void*)pLoop, NULL)) - { - LOG_EX(LOG_Error, "dbus: Could not set watch function\n"); - - *pErrno = -ERR_SET_TIMEOUT_FUNCTION; - return NULL; - } -#endif - - pAsync = malloc(sizeof(uv_async_t)); - pAsync->data = (void*)pBus; - - uv_async_init(pLoop, pAsync, uvAsyncCb); - uv_unref((uv_handle_t*)pAsync); - -#if 1 - dbus_connection_set_wakeup_main_function(pBus, - DBusWakeupMainLoopCb, - (void*)pAsync, DBusAsyncFreeCb); -#endif - - sprintf(rule, "type='signal', interface='%s'", DBUS_MESSAGE_INTERFACE_NAME); - dbus_bus_add_match(pBus, rule, &error); - - if(dbus_error_is_set(&error)) - { - LOG_EX(LOG_Error, "dbus_bus_add_match [%s] error: %s\n", DBUS_MESSAGE_INTERFACE_NAME, error.message); - dbus_error_free(&error); - *pErrno = -ERR_BUS_MATCH; - return NULL; - } -#if 1 - if(!dbus_connection_add_filter(pBus, DBusOnMsgCb, pLoop, NULL)) - { - LOG_EX(LOG_Error, "dbus_connection_add_filter error\n"); - *pErrno = -ERR_BUS_SET_MSG_CB; - return NULL; - } -#endif - - uv_idle_init(pLoop, &g_uvIdleHandle); - g_uvIdleHandle.data = pBus; - uv_idle_start(&g_uvIdleHandle, uvIdleCb); - - if(cbOnKey) - { - uv_fs_open(pLoop, &g_uvKeyEvent, R16_TINA_KEY_EVENT_PATH, O_RDONLY, 0, uvOpenKeyEventCb); - g_LibuvDBusParam.onKeyCb = cbOnKey; - } - - g_LibuvDBusParam.pLoop = pLoop; - g_LibuvDBusParam.pUserLoop = pUserLoop; - g_LibuvDBusParam.pBus = pBus; - g_LibuvDBusParam.onMsgCb = cbOnMsg; - -#if 0 - if(cbOnHbl) - { - g_LibuvDBusParam.onHblCb = cbOnHbl; - HeartDaemonInit(g_LibuvDBusParam.modName, HEART_LOST_DELAY, cbOnHbl); - } -#else - g_LibuvDBusParam.onHblCb = __dBusDeameonCb; - HeartDaemonInit(g_LibuvDBusParam.modName, HEART_LOST_DELAY, __dBusDeameonCb); -#endif - -#if USED_SHM_TO_DBUS - uv_thread_create(&uvSyncThread, __uvShmTblTaskThreadCb, NULL); -#endif - -#ifdef ENABLE_COUNT_DEBUG - MonitorInit(); - MonAddNewItem(MON_MSG_PROC_STAT, 100000); - MonAddNewItem(MON_MSG_BST_PROC_STAT, 100000); - MonAddNewItem(MON_USER_MSG_PROC_STAT, 100000); - MonAddNewItem(MON_USER_MSG_BST_PROC_STAT, 100000); -#endif - - InetInit(); - EvpSystemInit(); - -#if 0 - if(g_LibuvDBusParam.onMsgCb) - { - uv_thread_create(&uvMsgProcThread, __uvMsgProc, NULL); - } -#endif - - return pBus; -} - -int DBusWithLibuvCfgInit(OnCfgMsg cbOnCfgMsg) -{ - CfgGlobalEnvInit(); - - if(cbOnCfgMsg == NULL) - { - return (-ERR_INPUT_PARAMS); - } - - g_LibuvDBusParam.onCfgCb = cbOnCfgMsg; - - return (0); -} - -int GetShellExecResult(const char *pCmd, char **pResult) -{ - FILE *pFile = NULL; - unsigned int uRdSize = 0; - char *pCmdOut; - - *pResult = NULL; - - if(pCmd == NULL || strlen(pCmd) == 0) - { - return (-ERR_INPUT_PARAMS); - } - - pFile = popen(pCmd, "r"); - - if(pFile == NULL) - { - return (-ERR_OPEN_FILE); - } - - *pResult = (char *)malloc(4096); - pCmdOut = *pResult; - - uRdSize = fread(pCmdOut, sizeof(char), 4096, pFile); - - pCmdOut[uRdSize] = 0; - - if(pCmdOut[strlen(pCmdOut) - 1] == '\n') - { - pCmdOut[strlen(pCmdOut) - 1] = 0; - } - - pclose(pFile); - //fprintf(stdout, "%s --> [%s](%u)\n", pCmd, pCmdOut, uRdSize); - return (0); -} - -void SystemSafeReboot(void) -{ - int ret, reTry = 0; -#if 0 - ret = system("sync"); - - ret = system("ubus call system watchdog \'{\"stop\" : true}\'"); - - reTry = 3; - do - { - sleep(1); - } while(reTry--); - - reTry = 0; - - LOG_EX(LOG_Debug, "Reboot System By Power Control Chips\n"); - sleep(1); - - ret = system("echo 3140 > /sys/bus/platform/devices/axp22_board/axp22_reg"); - - sleep(10); -#endif - while(TRUE) - { - LOG_EX(LOG_Debug, "Reboot System: %d times\n", reTry++); - sleep(1); - ret = system("reboot -f"); - sleep(3); - } -} - -char* GetCpuChipId(void) -{ - char* pRet = NULL; -#ifdef PLATFORM_R16 - char* pChipId = NULL; - - GetShellExecResult("cat /proc/cpuinfo | grep Chipid | awk '{print $3}'", &pChipId); - - if(pChipId == NULL) - { - return strdup(""); - } - - pRet = strdup(pChipId); - free(pChipId); - return pRet; -#else - return strdup("Unknown CPU Chip ID"); -#endif -} - -char* GetCpuSerial(void) -{ - char* pRet = NULL; -#ifdef PLATFORM_R16 - char* pSerial = NULL; - - GetShellExecResult("cat /proc/cpuinfo | grep Serial | awk '{print $3}'", &pSerial); - - if(pSerial == NULL) - { - return strdup(""); - } - - pRet = strdup(pSerial); - free(pSerial); - return pRet; -#else - return strdup("Unknown CPU Serial"); -#endif -} - -int CopyFile(const char *pSrc, const char *pDest) -{ - int fdSrc, fdDest; - struct stat st; - ssize_t sz; - - if(stat(pSrc, &st) != 0) - { - LOG_EX(LOG_Error, "Get File %s Size Error\n", pSrc); - return (-ERR_GET_FILE_SIZE); - } - - fdSrc = open(pSrc, O_RDONLY); - - if(fdSrc < 0) - { - LOG_EX(LOG_Error, "Open File %s Error\n", pSrc); - return (-ERR_OPEN_FILE); - } - - fdDest = open(pDest, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); - - if(fdDest < 0) - { - close(fdSrc); - LOG_EX(LOG_Error, "Open File %s Error\n", pDest); - return (-ERR_OPEN_FILE); - } - - sz = sendfile(fdDest, fdSrc, NULL, st.st_size); - - if(sz != st.st_size) - { - LOG_EX(LOG_Error, "Copy File Size Error: %d, %d\n", sz, st.st_size); - close(fdSrc); - close(fdDest); - return (-ERR_COPY_FILE); - } - - fsync(fdDest); - - close(fdSrc); - close(fdDest); - - return (0); -} - -int CopyFileWithSize(const char *pSrc, const char *pDest, int iSize) -{ - int fdSrc, fdDest; - struct stat st; - ssize_t sz; - size_t cpSize = iSize; - - if(iSize <= 0) - { - if(stat(pSrc, &st) != 0) - { - LOG_EX(LOG_Error, "Get File %s Size Error\n", pSrc); - return (-ERR_GET_FILE_SIZE); - } - - cpSize = st.st_size; - } - - fdSrc = open(pSrc, O_RDONLY); - - if(fdSrc < 0) - { - LOG_EX(LOG_Error, "Open File %s Error\n", pSrc); - return (-ERR_OPEN_FILE); - } - - fdDest = open(pDest, O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |S_IWOTH); - - if(fdDest < 0) - { - close(fdSrc); - LOG_EX(LOG_Error, "Open File %s Error\n", pDest); - return (-ERR_OPEN_FILE); - } - - sz = sendfile(fdDest, fdSrc, NULL, cpSize); - - if(sz != cpSize) - { - LOG_EX(LOG_Error, "Copy File Size Error: %d, %d\n", sz, cpSize); - close(fdSrc); - close(fdDest); - return (-ERR_COPY_FILE); - } - - close(fdSrc); - close(fdDest); - - return (0); -} - -int ReadFileToBuf(const char *pSrc, unsigned char *pBuf, int iSize) -{ - int fdSrc; - struct stat st; - ssize_t sz; - size_t cpSize = iSize; - - if(iSize < 0) - { - if(stat(pSrc, &st) != 0) - { - LOG_EX(LOG_Error, "Get File %s Size Error\n", pSrc); - return (-ERR_GET_FILE_SIZE); - } - - cpSize = st.st_size; - } - - fdSrc = open(pSrc, O_RDONLY); - - if(fdSrc < 0) - { - LOG_EX(LOG_Error, "Open File %s Error\n", pSrc); - return (-ERR_OPEN_FILE); - } - - sz = read(fdSrc, pBuf, cpSize); - - if(sz != cpSize) - { - LOG_EX(LOG_Error, "Copy File Size Error: %d, %d\n", sz, cpSize); - close(fdSrc); - return (-ERR_COPY_FILE); - } - - close(fdSrc); - - return (sz); -} - -static int __reqWorkDayInfo(int year) -{ - int ret = 0; - WORKDAY_INFO reqInfo; - - memset(&reqInfo, 0, sizeof(WORKDAY_INFO)); - - if(year <= 0) - { - struct tm localTime; - time_t tmStamp = time((time_t*)NULL); - - localtime_r(&tmStamp, &localTime); - - reqInfo.year = localTime.tm_year; - } - else - { - reqInfo.year = year; - } - - if(reqInfo.year < (2018 - 1900)) - { - return 0; - } - - ret = DBusJsonSendToCommand(NULL, - g_pModInfoTable[MODULE_CONTROLLER].modAliase, - CMD_WORKDAY_DB_REQ, - JSON_ENGINE_WORKDAY_REQ, - &reqInfo, FALSE); - - return (ret); -} - -int IsHolidayDBSynced(void) -{ - return g_workDayArray.isReady; -} - -int CurrentIsWorkDay(int year, int day) -{ - static unsigned int i = 0; - - if(year != 0) - { - LOG_EX(LOG_Debug, "CurrentIsWorkDay: year = %d, day = %d\n", year, day); - } - - if(day > 365) - { - LOG_EX(LOG_Error, "Error Input Params: day = %d\n", day); - return (-ERR_INPUT_PARAMS); - } - - if(g_workDayArray.year <= 0) - { - __reqWorkDayInfo(year); - if(i++ % 10 == 0) - { - LOG_EX(LOG_Error, "Unsync Database: year = %d\n", year); - } - return (-ERR_UNINIT_ITEM); - } - - if(day < 0 || year <= 0) - { - struct tm localTime; - time_t tmStamp = time((time_t*)NULL); - localtime_r(&tmStamp, &localTime); - - if(day < 0) - { - day = localTime.tm_yday; - } - - if(year <= 0) - { - year = localTime.tm_year; - } - } - - if(year != g_workDayArray.year - 1900) - { - __reqWorkDayInfo(year); - LOG_EX(LOG_Error, "Have No Current Year Database: year = %d, g_workDayArray.year = %d\n", - year, g_workDayArray.year); - - return (-ERR_NO_ITEMS); - } - - // 0 work day, 1 holiday - return (g_workDayArray.days[day] == 0); -} - -unsigned long long GetPartitionFreeSize(const char *pPartPath) -{ - struct statfs myStatfs; - unsigned long long freeSize; - - if(statfs(pPartPath, &myStatfs) == -1) - { - return 0; - } - - freeSize = myStatfs.f_bsize * myStatfs.f_bfree; - - //fprintf(stdout, "%s free = %llu bytes\n", pPartPath, freeSize); - - return freeSize; -} - -#ifdef CURRENT_VERSION -char* GetCurrentVersion(void) -{ - return CURRENT_VERSION; -} -#else -char* GetCurrentVersion(void) -{ - return "0.0.1"; -} -#endif - -WIFI_STATUS GetCurrWIFIConnStatus(void) -{ - return g_WifiConnStatus; -} - -const char* ErrcodeToString(int errCode) -{ - switch(errCode) - { - case ERR_INPUT_PARAMS: return "ERR_INPUT_PARAMS"; - case ERR_NO_ITEMS: return "ERR_NO_ITEMS"; - case ERR_GET_BUS: return "ERR_GET_BUS"; - case ERR_DBUS_CONNECTION: return "ERR_DBUS_CONNECTION"; - case ERR_REQUEST_BUS_NAME: return "ERR_REQUEST_BUS_NAME"; - case ERR_SET_WATCH_FUNCTION: return "ERR_SET_WATCH_FUNCTION"; - case ERR_SET_TIMEOUT_FUNCTION: return "ERR_SET_TIMEOUT_FUNCTION"; - case ERR_BUS_MATCH: return "ERR_BUS_MATCH"; - case ERR_BUS_SET_MSG_CB: return "ERR_BUS_SET_MSG_CB"; - case ERR_DBUS_CREATE_MSG: return "ERR_DBUS_CREATE_MSG"; - case ERR_BUS_SEND_MSG: return "ERR_BUS_SEND_MSG"; - case ERR_DBUS_MSG_TO_LARGE: return "ERR_DBUS_MSG_TO_LARGE"; - case ERR_BUS_RCV_MSG: return "ERR_BUS_RCV_MSG"; - case ERR_ADD_TASK: return "ERR_ADD_TASK"; - case ERR_UNSUP_EVP_TYPE: return "ERR_UNSUP_EVP_TYPE"; - case ERR_CREATE_MQ: return "ERR_CREATE_MQ"; - case ERR_MQ_SENDMSG: return "ERR_MQ_SENDMSG"; - case ERR_CREATE_SHM: return "ERR_CREATE_SHM"; - case ERR_MAP_SHM: return "ERR_MAP_SHM"; - case ERR_MALLOC_MEMORY: return "ERR_MALLOC_MEMORY"; - case ERR_EVP_INIT_KEY: return "ERR_EVP_INIT_KEY"; - case ERR_EVP_UPDATE: return "ERR_EVP_UPDATE"; - case ERR_EVP_FINALE: return "ERR_EVP_FINALE"; - case ERR_EVP_KEY_SIZE: return "ERR_EVP_KEY_SIZE"; - case ERR_OPEN_FILE: return "ERR_OPEN_FILE"; - case ERR_READ_FILE: return "ERR_READ_FILE"; - case ERR_WRITE_FILE: return "ERR_WRITE_FILE"; - case ERR_COPY_FILE: return "ERR_COPY_FILE"; - case ERR_FILE_NOT_EXISTS: return "ERR_FILE_NOT_EXISTS"; - case ERR_GET_FILE_SIZE: return "ERR_GET_FILE_SIZE"; - case ERR_UNINIT_ITEM: return "ERR_UNINIT_ITEM"; - case ERR_FILE_EMPTY: return "ERR_FILE_EMPTY"; - case ERR_SEND_MAIL: return "ERR_SEND_MAIL"; - case ERR_NETWORK_SEND: return "ERR_NETWORK_SEND"; - case ERR_NETWORK_NOT_CONNECTED: return "ERR_NETWORK_NOT_CONNECTED"; - case ERR_UNSUPPORT: return "ERR_UNSUPPORT"; - case ERR_NO_INIT_IPL3: return "ERR_NO_INIT_IPL3"; - case ERR_BAD_IPL3: return "ERR_BAD_IPL3"; - case ERR_BAD_FILE_SIZE: return "ERR_BAD_FILE_SIZE"; - case ERR_MD5_FILE: return "ERR_MD5_FILE"; - case ERR_MD5_CHECK_SUM: return "ERR_MD5_CHECK_SUM"; - case ERR_OTA_WRITE_BOOT: return "ERR_OTA_WRITE_BOOT"; - case ERR_OTA_WRITE_ROOTFS: return "ERR_OTA_WRITE_ROOTFS"; - case ERR_OTA_WRITE_IPL3: return "ERR_OTA_WRITE_IPL3"; - case ERR_OTA_WRITE_PARAMS: return "ERR_OTA_WRITE_PARAMS"; - case ERR_OTA_DOWNLOAD_FILE: return "ERR_OTA_DOWNLOAD_FILE"; - case ERR_VERIFY_PARTITION_MD5: return "ERR_VERIFY_PARTITION_MD5"; - case ERR_OTA_PRE_STATR: return "ERR_OTA_PRE_STATR"; - case ERR_OTA_YET_CUR_VER: return "ERR_OTA_YET_CUR_VER"; - case ERR_OTA_NOT_READY: return "ERR_OTA_NOT_READY"; - case ERR_CREATE_CFG_FILE: return "ERR_CREATE_CFG_FILE"; - case ERR_CREATE_SQLITE3_DB: return "ERR_CREATE_SQLITE3_DB"; - case ERR_OPEN_SQLITE3_DB: return "ERR_OPEN_SQLITE3_DB"; - case ERR_SQLITE3_CREATE_TABLE: return "ERR_SQLITE3_CREATE_TABLE"; - case ERR_SYNC_DATABASE: return "ERR_SYNC_DATABASE"; - case ERR_SQL_QUERY: return "ERR_SQL_QUERY"; - case ERR_SQL_DELETE: return "ERR_SQL_DELETE"; - case ERR_UNKNOWN_TYPE: return "ERR_UNKNOWN_TYPE"; - case ERR_PERMISSION_DENIED: return "ERR_PERMISSION_DENIED"; - case ERR_CFG_NOITEM: return "ERR_CFG_NOITEM"; - case ERR_CFG_ITEM_EXIST: return "ERR_CFG_ITEM_EXIST"; - case ERR_CFG_WAIT_RSP: return "ERR_CFG_WAIT_RSP"; - case ERR_CFG_BUSY: return "ERR_CFG_BUSY"; - case ERR_STR_CONVERT: return "ERR_STR_CONVERT"; - case ERR_SQL_REG_MODULE: return "ERR_SQL_REG_MODULE"; - default: return "Unknown Error"; - } -} - -const char* DBusCmdToString(DBUS_CMD cmd) -{ - switch(cmd) - { - case CMD_MISC_PING: return "CMD_MISC_PING"; - case CMD_MISC_OTA: return "CMD_MISC_OTA"; - case CMD_MISC_WEATHER: return "CMD_MISC_WEATHER"; - case CMD_MISC_NOWTIME: return "CMD_MISC_NOWTIME"; - case CMD_MISC_UPGRADE: return "CMD_MISC_UPGRADE"; - case CMD_SYSTEM_STANDBY: return "CMD_SYSTEM_STANDBY"; - case CMD_MISC_QUERY_OTA_STATUS: return "CMD_MISC_QUERY_OTA_STATUS"; - case CMD_MISC_QUERY_DL_STATUS: return "CMD_MISC_QUERY_DL_STATUS"; - case CMD_CALL_DIAL: return "CMD_CALL_DIAL"; - case CMD_CALL_ACCEPI: return "CMD_CALL_ACCEPI"; - case CMD_CALL_HANGUP: return "CMD_CALL_HANGUP"; - case CMD_CALL_MESSAGE: return "CMD_CALL_MESSAGE"; - case CMD_PLAY_MODECHANGE: return "CMD_PLAY_MODECHANGE"; - case CMD_PLAY_PLAY: return "CMD_PLAY_PLAY"; - case CMD_PLAY_PAUSE: return "CMD_PLAY_PAUSE"; - case CMD_PLAY_STOP: return "CMD_PLAY_STOP"; - case CMD_PLAY_SEEKTO: return "CMD_PLAY_SEEKTO"; - case CMD_PLAY_SHOWMODE: return "CMD_PLAY_SHOWMODE"; - case CMD_PLAY_NEXT: return "CMD_PLAY_NEXT"; - case CMD_PLAY_PRE: return "CMD_PLAY_PRE"; - case CMD_PLAY_SHOWLIST: return "CMD_PLAY_SHOWLIST"; - case CMD_PLAY_UPDATELIST: return "CMD_PLAY_UPDATELIST"; - case CMD_PLAY_PREPARE_NEXT: return "CMD_PLAY_PREPARE_NEXT"; - case CMD_PLAY_ADDTOLIST: return "CMD_PLAY_ADDTOLIST"; - case CMD_PLAY_DELETEFROMLIST: return "CMD_PLAY_DELETEFROMLIST"; - case CMD_PLAY_RESETLIST: return "CMD_PLAY_RESETLIST"; - case CMD_PLAY_AUDIO_STOP: return "CMD_PLAY_AUDIO_STOP"; - case CMD_PLAY_AUDIO_PLAY: return "CMD_PLAY_AUDIO_PLAY"; - case CMD_SE_PLAY: return "CMD_SE_PLAY"; - case CMD_PLAY_RET_STATUS: return "CMD_PLAY_RET_STATUS"; - case CMD_CFG_ADD_REQ: return "CMD_CFG_ADD_REQ"; - case CMD_CFG_ADD_RSP: return "CMD_CFG_ADD_RSP"; - case CMD_CFG_CHANGE_REQ: return "CMD_CFG_CHANGE_REQ"; - case CMD_CFG_CHANGE_RSP: return "CMD_CFG_CHANGE_RSP"; - case CMD_CFG_GET_REQ: return "CMD_CFG_GET_REQ"; - case CMD_CFG_GET_RSP: return "CMD_CFG_GET_RSP"; - case CMD_CFG_UPG_NOTIFY: return "CMD_CFG_UPG_NOTIFY"; - case CMD_MSC_MSG_CONTROLLER_RECOG_SUCCESS: return "CMD_MSC_MSG_CONTROLLER_RECOG_SUCCESS"; - case CMD_MSC_MSG_CONTROLLER_RECOG_ERROR: return "CMD_MSC_MSG_CONTROLLER_RECOG_ERROR"; - case CMD_MSC_MSG_CONTROLLER_WAKEUP: return "CMD_MSC_MSG_CONTROLLER_WAKEUP"; - case CMD_MSC_MSG_CONTROLLER_RECOGING: return "CMD_MSC_MSG_CONTROLLER_RECOGING"; - case CMD_CONTROLLER_REQMSG_INITARGS: return "CMD_CONTROLLER_REQMSG_INITARGS"; - case CMD_CONTROLLER_RSPMSG_INITARGS: return "CMD_CONTROLLER_RSPMSG_INITARGS"; - case CMD_CONTROLLER_REQMSG_PLAYERSTATUS: return "CMD_CONTROLLER_REQMSG_PLAYERSTATUS"; - case CMD_CONTROLLER_RSPMSG_PLAYERSTATUS: return "CMD_CONTROLLER_RSPMSG_PLAYERSTATUS"; - case CMD_MSC_REQMSG_MIC_CONTROL: return "CMD_MSC_REQMSG_MIC_CONTROL"; - case CMD_MSC_RSPMSG_MIC_CONTROL: return "CMD_MSC_RSPMSG_MIC_CONTROL"; - case CMD_YUNXIN_RECVMSG: return "CMD_YUNXIN_RECVMSG"; - case CMD_YUNXIN_SENDMSG: return "CMD_YUNXIN_SENDMSG"; - case CMD_YUNXIN_SENDMSG_BYPASS: return "CMD_YUNXIN_SENDMSG_BYPASS"; - case CMD_YUNXIN_SENDMSGCB: return "CMD_YUNXIN_SENDMSGCB"; - case CMD_CONTROLLER_MSG_YUNXIN: return "CMD_CONTROLLER_MSG_YUNXIN"; - case CMD_YUNXIN_STATUS: return "CMD_YUNXIN_STATUS"; - case CMD_YUNXIN_SYSMSG: return "CMD_YUNXIN_SYSMSG"; - case CMD_WIFI_CONF: return "CMD_WIFI_CONF"; - case CMD_WIFI_CONF_RESP: return "CMD_WIFI_CONF_RESP"; - case CMD_WIFI_AUTO_CONN: return "CMD_WIFI_AUTO_CONN"; - case CMD_WIFI_AUTO_CONN_RESP: return "CMD_WIFI_AUTO_CONN_RESP"; - case CMD_WIFI_STATE_REQ: return "CMD_WIFI_STATE_REQ"; - case CMD_WIFI_STATE_RESP: return "CMD_WIFI_STATE_RESP"; - case CMD_WIFI_STATE_NTF: return "CMD_WIFI_STATE_NTF"; - case CMD_BT_NAME_GET_REQ: return "CMD_BT_NAME_GET_REQ"; - case CMD_BT_NAME_GET_RESP: return "CMD_BT_NAME_GET_RESP"; - case CMD_BT_EVT_NTF: return "CMD_BT_EVT_NTF"; - case CMD_KPLAYER_START: return "CMD_KPLAYER_START"; - case CMD_KPLAYER_STOP: return "CMD_KPLAYER_STOP"; - case CMD_KPLAYER_NOTIF_DUR: return "CMD_KPLAYER_NOTIF_DUR"; - case CMD_KPLAYER_HOST_ACTION: return "CMD_KPLAYER_HOST_ACTION"; - case CMD_KPLAYER_CTR_NTF_BASE: return "CMD_KPLAYER_CTR_NTF_BASE"; - case CMD_KPLAYER_CTR_CREATED: return "CMD_KPLAYER_CTR_CREATED"; - case CMD_KPLAYER_CTR_DELED: return "CMD_KPLAYER_CTR_DELED"; - case CMD_KPLAYER_CTR_PLAY: return "CMD_KPLAYER_CTR_PLAY"; - case CMD_KPLAYER_CTR_STOP: return "CMD_KPLAYER_CTR_STOP"; - case CMD_KPLAYER_CTR_PAUSE: return "CMD_KPLAYER_CTR_PAUSE"; - case CMD_KPLAYER_CTR_SEEK: return "CMD_KPLAYER_CTR_SEEK"; - case CMD_KPLAYER_CTR_SET_URL: return "CMD_KPLAYER_CTR_SET_URL"; - case CMD_KPLAYER_CTR_SET_VOLUME: return "CMD_KPLAYER_CTR_SET_VOLUME"; - case CMD_KPLAYER_CTR_SET_MUTE: return "CMD_KPLAYER_CTR_SET_MUTE"; - case CMD_KPLAYER_CTR_SET_NXT_URL: return "CMD_KPLAYER_CTR_SET_NXT_URL"; - case CMD_KPLAYER_CTR_SET_NEXT: return "CMD_KPLAYER_CTR_SET_NEXT"; - case CMD_KPLAYER_CTR_SET_PREV: return "CMD_KPLAYER_CTR_SET_PREV"; - case CMD_ALARM_SYNC_REQ: return "CMD_ALARM_SYNC_REQ"; - case CMD_ALARM_SYNC_RSP: return "CMD_ALARM_SYNC_RSP"; - case CMD_ALARM_ADD: return "CMD_ALARM_ADD"; - case CMD_ALARM_REMOVE: return "CMD_ALARM_REMOVE"; - case CMD_ALARM_REMOVEALL: return "CMD_ALARM_REMOVEALL"; - case CMD_REMAIND_SYNC_REQ: return "CMD_REMAIND_SYNC_REQ"; - case CMD_REMAIND_SYNC_RSP: return "CMD_REMAIND_SYNC_RSP"; - case CMD_REMAIND_ADD: return "CMD_REMAIND_ADD"; - case CMD_REMAIND_REMOVE: return "CMD_REMAIND_REMOVE"; - case CMD_REMAIND_REMOVEALL: return "CMD_REMAIND_REMOVEALL"; - case CMD_ASSISTANT_STATUS: return "CMD_ASSISTANT_STATUS"; - case CMD_ASSISTANT_RUNNING: return "CMD_ASSISTANT_RUNNING"; - case CMD_ASSISTANT_NOTIFY: return "CMD_ASSISTANT_NOTIFY"; - case CMD_SESSION_ALARM_SYNC: return "CMD_SESSION_ALARM_SYNC"; - case CMD_WORKDAY_DB_REQ: return "CMD_WORKDAY_DB_REQ"; - case CMD_WORKDAY_DB_RSP: return "CMD_WORKDAY_DB_RSP"; - case CMD_OTA_NOTIFY: return "CMD_OTA_NOTIFY"; - case CMD_OTA_STATUS: return "CMD_OTA_STATUS"; - case CMD_OTA_RUNNOW: return "CMD_OTA_RUNNOW"; - case CMD_LOG_CONFIG: return "CMD_LOG_CONFIG"; - default: return "Unknown CMD"; - } -} - -const char* ModuleNameToString(MODULE_NAME modName) -{ - switch(modName) - { - case MODULE_CONTROLLER: return "MODULE_CONTROLLER"; - case MODULE_ALARM: return "MODULE_ALARM"; - case MODULE_CALL: return "MODULE_CALL"; - case MODULE_VOICEENGINE: return "MODULE_VOICEENGINE"; - case MODULE_PLAYER: return "MODULE_PLAYER"; - case MODULE_CONFIGURE: return "MODULE_CONFIGURE"; - case MODULE_OTA: return "MODULE_OTA"; - case MODULE_WIFI: return "MODULE_WIFI"; - case MODULE_BT: return "MODULE_BT"; - case MODULE_KPLAYER: return "MODULE_KPLAYER"; - case MODULE_KPLAYER_TEST: return "MODULE_KPLAYER_TEST"; - case MODULE_SPLAYER: return "MODULE_SPLAYER"; - case MODULE_SPLAYER_TEST: return "MODULE_SPLAYER_TEST"; - case MODULE_LIGHT_MCU: return "MODULE_LIGHT_MCU"; - case MODULE_BLUEKC: return "MODULE_BLUEKC"; - case MODULE_BLUEKC_TEST: return "MODULE_BLUEKC_TEST"; - case MODULE_MANUFACTURE: return "MODULE_MANUFACTURE"; - case MODULE_BT_DEMO: return "MODULE_BT_DEMO"; - case MODULE_LOG_CTRL: return "MODULE_LOG_CTRL"; - } - - return "Unknown Module Name"; -} diff --git a/build/Makefile.app.cross b/build/Makefile.app.cross index 72cad07..44ec0a1 100644 --- a/build/Makefile.app.cross +++ b/build/Makefile.app.cross @@ -43,7 +43,7 @@ PLAT_LINUX_CFLAGS += -I../linux32/inc/ -I../linux32/inc/cjson/ -I../linux32/inc R16_LIBS := $(COMMON_R16_LIBS) -lreadline -lcurses R16_LIBS += ./libuvdbus-r16.so -R311_LIBS := $(COMMON_R16_LIBS) -lreadline -lcurses +R311_LIBS := $(COMMON_R311_LIBS) -lreadline -lcurses R311_LIBS += ./libuvdbus-r311.so LINUX_LIBS := $(COMMON_LINUX_LIBS) -lreadline -lnghttp2 diff --git a/build/Makefile.def.cross b/build/Makefile.def.cross index e7a46f4..0f58a18 100644 --- a/build/Makefile.def.cross +++ b/build/Makefile.def.cross @@ -1,2 +1,6 @@ -COMMON_R16_LIBS := -ldbus-1 -luv -lcrypto -lcjson -ls2json -lsqlite3 -lnghttp2 -lquickmail -lz -luuid -lconfig -lcurl -lssl -lpthread ../3partys/boardlink/libfastcon.a +COMMON_R16_LIBS := -ldbus-1 -luv -lcrypto -lcjson -ls2json -lsqlite3 -lnghttp2 -lquickmail -lz -luuid -lconfig -lcurl -lssl -lpthread +COMMON_R16_LIBS += ../3partys/boardlink/libfastcon.a ./libpv1comm-r16.so +COMMON_R311_LIBS := -ldbus-1 -luv -lcrypto -lcjson -ls2json -lsqlite3 -lnghttp2 -lquickmail -lz -luuid -lconfig -lcurl -lssl -lpthread +COMMON_R311_LIBS += ../3partys/boardlink/libfastcon.a ./libpv1comm-r311.so COMMON_LINUX_LIBS := -ldbus-1 -luv -lcrypto -lcurl -lm -lnghttp2 -lsqlite3 -lquickmail -lz -luuid -lconfig -lssl -lpthread +COMMON_LINUX_LIBS += ./libpv1comm-linux.so diff --git a/build/Makefile.lib.cross b/build/Makefile.lib.cross index 4f15807..02060b6 100644 --- a/build/Makefile.lib.cross +++ b/build/Makefile.lib.cross @@ -32,7 +32,7 @@ VPATH = ../Framework ../log ../Modules ../linux32 # set the source file, don't used .o because of ... # MRS Board Source Files PLAT_R16_SRCS = \ - libuvEngine/libuv_dbus.c \ + libuvEngine/libcomm.c \ HeartDaemon/heart_daemon.c \ JsonUtils/json_struct.c \ Configure/config_engine.c \ @@ -42,20 +42,13 @@ PLAT_R16_SRCS = \ Crypto/md5.c \ Crypto/crypto.c \ Compress/zlib.c \ - Network/inet_api.c \ - Timer/timer.c \ - Fifo/fifo.c \ Skins/skins.c \ - Skins/skin_res_vtbl.c \ IoT/Boardlink/boardlink_iot.c \ Monitor/monitor.c \ - log.c \ - SvrManager/svr_manager.c \ - hexdump.c + SvrManager/svr_manager.c \ + mark_point.c -PLAT_LINUX_SRCS := $(PLAT_R16_SRCS) \ - src/cJSON.c \ - src/s2j.c +PLAT_LINUX_SRCS := $(PLAT_R16_SRCS) PLAT_R311_SRCS := $(PLAT_R16_SRCS) # gcc CFLAGS @@ -70,12 +63,35 @@ PLAT_R311_LDFLAGS := $(PLAT_R16_LDFLAGS) PLAT_LINUX_LDFLAGS := $(PLAT_R16_LDFLAGS) R16_LIBS := $(COMMON_R16_LIBS) -R311_LIBS := $(COMMON_R16_LIBS) +R311_LIBS := $(COMMON_R311_LIBS) LINUX_LIBS := $(COMMON_LINUX_LIBS) +ifeq ($(PLAT_R16), TRUE) +DEPEND_LIB := ../3partys/allwinner/libpv1comm-r16.so +USER_CLEAN_ITEMS += ./libpv1comm-r16.so +endif + +ifeq ($(PLAT_R311), TRUE) +DEPEND_LIB += ../3partys/allwinner/libpv1comm-r311.so +USER_CLEAN_ITEMS += ./libpv1comm-r311.so +endif + +ifeq ($(PLAT_LINUX), TRUE) +DEPEND_LIB += ../3partys/allwinner/libpv1comm-linux.so +USER_CLEAN_ITEMS += ./libpv1comm-linux.so +endif + # this line must be at below of thus, because of... include /opt/common/Makefile.cross +ifneq ($(MAKECMDGOALS), clean) +ifneq ($(MAKECMDGOALS), cleanall) +ifneq ($(notdir $(DEPEND_LIB)), $(wildcard $(DEPEND_LIB))) +$(shell $(CP) $(DEPEND_LIB) ./) +endif +endif +endif + ifeq ($(MAKECMDGOALS), ) $(shell find ./ -name $(TARGET)-*.exe -delete) else diff --git a/include/skins_res.h b/include/skins_res.h index 742ccda..af757d1 100644 --- a/include/skins_res.h +++ b/include/skins_res.h @@ -84,18 +84,18 @@ const SKIN_RES_INFO g_SkinDefaultResTable[] = { {VOICE_RES, "0", "v309", DEF_SKINS_ROOT_PATH"voice/S009.mp3", "f9039012752b3ed2a00f173aa305acf1"}, {VOICE_RES, "0", "v310", DEF_SKINS_ROOT_PATH"voice/S010.mp3", "446ec757495bdf7aee31a41a9efe8bab"}, {VOICE_RES, "0", "v311", DEF_SKINS_ROOT_PATH"voice/S011.mp3", "e9fa92d8929dcb2e134f42c1cedf4827"}, - {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-60.mp3", "61b24ec25307072464866da912d38287"}, - {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-61.mp3", "a231dc24277e25e6d762269efa9a1e07"}, - {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-62.mp3", "27402531c6aff9a9cfb5e418267fb41e"}, - {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-63.mp3", "f9487a6bf86f82961011920509ae0704"}, - {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-64.mp3", "1e67f62e7d8f38dbd8535355cb50fd81"}, - {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-65.mp3", "d2e6c99c68e981e6126306cfe8a8058e"}, - {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-66.mp3", "cb64153aef2ea8d5d9baeb0fc683fd54"}, - {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-67.mp3", "6661a903cd05fdab1ecd5193fb789e51"}, - {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-68.mp3", "db32f17dc439c25255d934bbeaec6275"}, - {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-69.mp3", "a93fea8d57e37a519f3ee0388cbd6e9a"}, - {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-70.mp3", "f91f277864c927fedfee53fb1e9d964a"}, - {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-71.mp3", "a4a4ff36d63fa47072c9eb181712e5cb"}, + {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-60.mp3", "9828d1ab422bc917bc6aeb1b3e87be78"}, + {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-61.mp3", "26afdbca771abb35ae30be251211245c"}, + {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-62.mp3", "56bda2a05dee06eb64271d69df16a5f7"}, + {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-63.mp3", "bfa246ebc08235208b01d251279c3c3a"}, + {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-64.mp3", "4a18af279fce82af357a4d8061f76608"}, + {VOICE_RES, "0", "v400", DEF_SKINS_ROOT_PATH"voice/B-h-65.mp3", "ec06ed18a96a28a5c2a8335f8c94af22"}, + {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-66.mp3", "014233835f5b9996adb572c7ba7b2cfa"}, + {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-67.mp3", "29a476772a85097a5fe31d2147234110"}, + {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-68.mp3", "5a746e5a466c2beee159174b08049221"}, + {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-69.mp3", "986d49e19cef9e19ed059112ed8ebbdf"}, + {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-70.mp3", "666c2d4f6de83dfaf7a8b0ead3db7231"}, + {VOICE_RES, "0", "v401", DEF_SKINS_ROOT_PATH"voice/B-h-71.mp3", "d39d5b43690f01bfb5746cadf1d98b17"}, {VOICE_RES, "0", "v402", DEF_SKINS_ROOT_PATH"voice/b-h-50.mp3", "017b53f7610f6dd99e21b546e6b35605"}, {VOICE_RES, "0", "v403", DEF_SKINS_ROOT_PATH"voice/b-h-51.mp3", "422b4550253780343b7a9805ca7b629a"}, {VOICE_RES, "0", "v5011", DEF_SKINS_ROOT_PATH"voice/a-a-01.mp3", "5d9d186ef50b603ab84a9abbfd348630"}, diff --git a/log/hexdump.c b/log/hexdump.c deleted file mode 100644 index 0217b34..0000000 --- a/log/hexdump.c +++ /dev/null @@ -1,326 +0,0 @@ -#ifndef __KERNEL__ -#include -#include -#include -#include -#include - -#include "log.h" - -static const char hex_asc[] = "0123456789abcdef"; - -#define hex_asc_lo(x) hex_asc[((x) & 0x0f)] -#define hex_asc_hi(x) hex_asc[((x) & 0xf0) >> 4] - -char* IHW_bin2hex(char *p, const unsigned char *cp, int count) -{ - while (count) { - unsigned char c = *cp++; - /* put lowercase hex digits */ - *p++ = 0x20 | hex_asc[c >> 4]; - *p++ = 0x20 | hex_asc[c & 0xf]; - count--; - } - - return p; -} - -/** - * hex_to_bin - convert a hex digit to its real value - * @ch: ascii character represents hex digit - * - * hex_to_bin() converts one hex digit to its actual value or -1 in case of bad - * input. - */ -int hex_to_bin(char ch) -{ - if((ch >= '0') && (ch <= '9')) - { - return ch - '0'; - } - - ch = tolower(ch); - - if((ch >= 'a') && (ch <= 'f')) - { - return ch - 'a' + 10; - } - - return -1; -} - -/** - * hex_dump_to_buffer - convert a blob of data to "hex ASCII" in memory - * @buf: data blob to dump - * @len: number of bytes in the @buf - * @rowsize: number of bytes to print per line; must be 16 or 32 - * @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1) - * @linebuf: where to put the converted data - * @linebuflen: total size of @linebuf, including space for terminating NUL - * @ascii: include ASCII after the hex output - * - * hex_dump_to_buffer() works on one "line" of output at a time, i.e., - * 16 or 32 bytes of input data converted to hex + ASCII output. - * - * Given a buffer of u8 data, hex_dump_to_buffer() converts the input data - * to a hex + ASCII dump at the supplied memory location. - * The converted output is always NUL-terminated. - * - * E.g.: - * hex_dump_to_buffer(frame->data, frame->len, 16, 1, - * linebuf, sizeof(linebuf), true); - * - * example output buffer: - * 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO - */ -void hex_dump_to_buffer(const void* buf, int len, int rowsize, - int groupsize, char* linebuf, size_t linebuflen, - int ascii) -{ - const unsigned char* ptr = (const unsigned char *)buf; - unsigned char ch; - int j, lx = 0; - int ascii_column; - - if(rowsize != 16 && rowsize != 32) - { - rowsize = 16; - } - - if(!len) - { - goto nil; - } - - if(len > rowsize) /* limit to one line at a time */ - { - len = rowsize; - } - - if((len % groupsize) != 0) /* no mixed size output */ - { - groupsize = 1; - } - - switch(groupsize) - { - case 8: - { - const unsigned long long* ptr8 = (const unsigned long long *)buf; - int ngroups = len / groupsize; - - for(j = 0; j < ngroups; j++) - lx += snprintf(linebuf + lx, linebuflen - lx, - "%s%16.16llx", j ? " " : "", - (unsigned long long) * (ptr8 + j)); - - ascii_column = 17 * ngroups + 2; - break; - } - - case 4: - { - const unsigned int* ptr4 = (const unsigned int *)buf; - int ngroups = len / groupsize; - - for(j = 0; j < ngroups; j++) - lx += snprintf(linebuf + lx, linebuflen - lx, - "%s%8.8x", j ? " " : "", *(ptr4 + j)); - - ascii_column = 9 * ngroups + 2; - break; - } - - case 2: - { - const unsigned short* ptr2 = (const unsigned short *)buf; - int ngroups = len / groupsize; - - for(j = 0; j < ngroups; j++) - lx += snprintf(linebuf + lx, linebuflen - lx, - "%s%4.4x", j ? " " : "", *(ptr2 + j)); - - ascii_column = 5 * ngroups + 2; - break; - } - - default: - for(j = 0; (j < len) && (lx + 3) <= linebuflen; j++) - { - ch = ptr[j]; - linebuf[lx++] = hex_asc_hi(ch); - linebuf[lx++] = hex_asc_lo(ch); - linebuf[lx++] = ' '; - } - - if(j) - { - lx--; - } - - ascii_column = 3 * rowsize + 2; - break; - } - - if(!ascii) - { - goto nil; - } - - while(lx < (linebuflen - 1) && lx < (ascii_column - 1)) - { - linebuf[lx++] = ' '; - } - - for(j = 0; (j < len) && (lx + 2) < linebuflen; j++) - { - ch = ptr[j]; - linebuf[lx++] = (isascii(ch) && isprint(ch)) ? ch : '.'; - } - -nil: - linebuf[lx++] = '\0'; -} - -/** - * print_hex_dump - print a text hex dump to syslog for a binary blob of data - * @level: kernel log level (e.g. KERN_DEBUG) - * @prefix_str: string to prefix each line with; - * caller supplies trailing spaces for alignment if desired - * @prefix_type: controls whether prefix of an offset, address, or none - * is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE) - * @rowsize: number of bytes to print per line; must be 16 or 32 - * @groupsize: number of bytes to print at a time (1, 2, 4, 8; default = 1) - * @buf: data blob to dump - * @len: number of bytes in the @buf - * @ascii: include ASCII after the hex output - * - * Given a buffer of u8 data, print_hex_dump() prints a hex + ASCII dump - * to the kernel log at the specified kernel log level, with an optional - * leading prefix. - * - * print_hex_dump() works on one "line" of output at a time, i.e., - * 16 or 32 bytes of input data converted to hex + ASCII output. - * print_hex_dump() iterates over the entire input @buf, breaking it into - * "line size" chunks to format and print. - * - * E.g.: - * print_hex_dump(KERN_DEBUG, "raw data: ", DUMP_PREFIX_ADDRESS, - * 16, 1, frame->data, frame->len, true); - * - * Example output using %DUMP_PREFIX_OFFSET and 1-byte mode: - * 0009ab42: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f @ABCDEFGHIJKLMNO - * Example output using %DUMP_PREFIX_ADDRESS and 4-byte mode: - * ffffffff88089af0: 73727170 77767574 7b7a7978 7f7e7d7c pqrstuvwxyz{|}~. - */ -void print_hex_dump(const char* prefix_str, int prefix_type, - int rowsize, int groupsize, - const void* buf, int len, int ascii) -{ - const unsigned char* ptr = (const unsigned char *)buf; - int i, remaining = len; - unsigned char linebuf[32 * 3 + 2 + 32 + 1]; - - if(rowsize != 16 && rowsize != 32) - { - rowsize = 16; - } - - for(i = 0; i < len; i += rowsize) - { - int linelen = MIN(remaining, rowsize); - remaining -= rowsize; - - hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize, - (char *)linebuf, sizeof(linebuf), ascii); - - switch(prefix_type) - { - case DUMP_PREFIX_ADDRESS: - print("%s%p: %s\n", - prefix_str, ptr + i, linebuf); - break; - - case DUMP_PREFIX_OFFSET: - print("%s%.8x: %s\n", prefix_str, i, linebuf); - break; - - default: - print("%s%.8x: %s\n", prefix_str, i, linebuf); - break; - } - } - - print("%s", "\n"); -} - -/** - * print_hex_dump_bytes - shorthand form of print_hex_dump() with default params - * @prefix_str: string to prefix each line with; - * caller supplies trailing spaces for alignment if desired - * @prefix_type: controls whether prefix of an offset, address, or none - * is printed (%DUMP_PREFIX_OFFSET, %DUMP_PREFIX_ADDRESS, %DUMP_PREFIX_NONE) - * @buf: data blob to dump - * @len: number of bytes in the @buf - * - * Calls print_hex_dump(), with log level of KERN_DEBUG, - * rowsize of 16, groupsize of 1, and ASCII output included. - */ -void print_hex_dump_bytes(const char* prefix_str, int prefix_type, - const void* buf, int len) -{ - print_hex_dump(prefix_str, prefix_type, 16, 1, - buf, len, 1); -} - -const char* format_hex_buf(const char* prefix_str, int prefix_type, - int rowsize, int groupsize, - const void* buf, int len, int ascii) -{ - UT_string* pLogStr = NULL; - const char* pFormatStr; - const unsigned char* ptr = (const unsigned char *)buf; - int i, remaining = len; - unsigned char linebuf[32 * 3 + 2 + 32 + 1]; - - if(rowsize != 16 && rowsize != 32) - { - rowsize = 16; - } - - utstring_new(pLogStr); - - for(i = 0; i < len; i += rowsize) - { - int linelen = MIN(remaining, rowsize); - remaining -= rowsize; - - hex_dump_to_buffer(ptr + i, linelen, rowsize, groupsize, - (char *)linebuf, sizeof(linebuf), ascii); - - switch(prefix_type) - { - case DUMP_PREFIX_ADDRESS: - utstring_printf(pLogStr, "%s%p: %s\n", - prefix_str, ptr + i, linebuf); - break; - - case DUMP_PREFIX_OFFSET: - utstring_printf(pLogStr, "%s%.8x: %s\n", - prefix_str, i, linebuf); - break; - - default: - utstring_printf(pLogStr, "%s%.8x: %s\n", - prefix_str, i, linebuf); - break; - } - } - - pFormatStr = strdup(utstring_body(pLogStr)); - utstring_free(pLogStr); - - return pFormatStr; -} - -#endif diff --git a/log/log.c b/log/log.c deleted file mode 100644 index 0802634..0000000 --- a/log/log.c +++ /dev/null @@ -1,1332 +0,0 @@ -/** @file log.c - @brief 系统日志接口文件 - @version 1.0.0 -*/ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef PLATFORM_R16 -#include -#endif - -#include "log.h" -#include "smart_sound.h" -#include "inet_api.h" -#include "crypto.h" -#include "libuv_dbus.h" -#include "server_addr.h" - -#define SHOW_CONSOLE_RED ("\033[31;48m\033[1m%s\033[0m%c") -#define SHOW_CONSOLE_YELLOW ("\033[33;48m\033[1m%s\033[0m%c") -#define SHOW_CONSOLE_GREEN ("\033[32;48m\033[1m%s\033[0m%c") -#define SHOW_CONSOLE_BLUE ("\033[34;48m\033[1m%s\033[0m%c") - -#ifdef PLATFORM_CPU -#define LOG_FILE_BASEDIR (".") -#else -#define LOG_FILE_BASEDIR ("/tmp") -#endif - -#ifdef PLATFORM_R16 -#define NIC_NAME ("wlan0") -#else -#define NIC_NAME ("enp3s0") -#endif - -#define MAX_LOG_ITEM (1000) -#define MAX_LOG_FILE_SIZE (1024 * 1024) -#define LOG_PRE_SIZE (512) - -#if 0 -#define LOG_MAIL_USERNAME ("pv1_es2@hotmail.com") -#define LOG_MAIL_PASSWORD ("netEase163") -#define LOG_MAIL_SERVER ("smtp://smtp-mail.outlook.com") -#define LOG_MAIL_PORT (587) -#else -#define LOG_MAIL_USERNAME ("pv1_es2@163.com") -#define LOG_MAIL_LOGPASSWD ("netEase163") -#define LOG_MAIL_PASSWORD ("pv1Dev163") -#define LOG_MAIL_SERVER ("smtp.163.com") -#define LOG_MAIL_PORT (25) -#endif - -#define LOG_MAIL_RECEIVER ("pv1_es2@163.com") - -#define SYS_POINT_UPLOAD_TIME (600) - -typedef struct -{ - char* pDeviceId; - char savePath[MAX_PATH]; - int iMaxCacheSize; - int iEveryUploadTime; - time_t lastPostTime; - time_t lastMarkTime; - FILE* pMarkFile; - uv_rwlock_t uvRwLock; - uv_thread_t uvIOThread; -} SYSPOINT_INFO, *PSYSPOINT_INFO; - -typedef struct SYSPOINT_ITEM -{ - char* pContent; - struct SYSPOINT_ITEM *next, *prev; -} *PSYSPOINT_ITEM; - -typedef struct LOG_ITEM -{ - LOG_LEVEL level; - int isPrinted; - int isAddTags; - struct timeval timestamp; - char *pLogContent; - struct LOG_ITEM *next, *prev; -}*PLOG_ITEM; - -typedef struct LOG_BACKUP -{ - time_t timestamp; - char *plogFilePath; - char *pGzFilePath; - unsigned int sendTimes; - unsigned int tolLogs; - struct LOG_BACKUP *next, *prev; -} *PLOG_BACKUP; - -typedef struct -{ - pid_t pid; - char* pChipId; - char* pChipSerial; - char exeName[MAX_PATH]; - char logFilePath[MAX_PATH]; - FILE *pLogFile; -} LOG_PROCESS_INFO, *PLOG_PROCESS_INFO; - -static int g_bEnableLog = FALSE; // 是否启用 Log 功能 -static int g_bEnMailBackup = FALSE; -static char* g_pEmailBox = NULL; -static int g_bEnLogToFile = TRUE; -static int g_bEnLogToServer = TRUE; -static char g_strLogTag[32]; // Log 标志 -static unsigned int g_LogRdPos = 0; -static pthread_t g_logThreadId; -static pthread_t g_backupThreadId; -static LOG_PROCESS_INFO g_LogProcessInfo; -static uv_rwlock_t g_uvLogLock; -static uv_rwlock_t g_uvLogBackLock; -static PLOG_ITEM g_pLogItemList = NULL; -static PLOG_BACKUP g_pLogBackupList = NULL; -static int g_logSock = -1; -struct sockaddr_in g_logAddr; - -static SYSPOINT_INFO g_SysPonitInfo; -static PSYSPOINT_ITEM g_pSysPointArray = NULL; -static PHTTP_POST_ATTACH g_pLogParamsArray = NULL; - - -static int g_iMinLevel = LOG_Fatal | LOG_Error | LOG_Warn | LOG_Debug | LOG_Info | LOG_Step; - -/** - * @brief Log 调试等级转字符串 - * @param level 调试等级 - * @return 调试等级对应的字符串 - */ -const char* LogLevelToStr(LOG_LEVEL level) -{ - switch(level) - { - case LOG_Test: - return "T"; - - case LOG_Info: - return "I"; - - case LOG_Call: - return "C"; - - case LOG_Debug: - return "D"; - - case LOG_Warn: - return "W"; - - case LOG_Error: - return "E"; - - case LOG_Fatal: - return "F"; - - case LOG_Step: - return "S"; - - case LOG_Devp: - return "V"; - - case LOG_Unknown: - return "U"; - - case LOG_All: - return "A"; - - default: - return "?"; - } - - return "U"; -} - -#pragma pack (push) -#pragma pack (1) -typedef struct -{ - unsigned short logSeq; - unsigned int pid; - unsigned int timeStamp; - unsigned int nanotime; - unsigned int logLevel; - char logContent[0]; -} LOG_PROTO_CONTENT, *PLOG_PROTO_CONTENT; -#pragma pack (pop) - -static struct HTTP_POST_ATTACH g_PostLogParams[] = -{ - {"CPUID", "", NULL, NULL}, - {"MAC", "", NULL, NULL}, - {"Version", "", NULL, NULL}, - {"BuildTime", "", NULL, NULL}, - {"SerialNumber", "", NULL, NULL}, - {"Datetime", "", NULL, NULL}, - {"content", "", NULL, NULL}, -}; - -static void __initPostLogParams(void) -{ - char *pMacAddr = NULL; - struct tm localTime; - time_t timeStamp = time((time_t*)NULL); - - GetShellExecResult("ifconfig wlan0 | grep HWaddr | awk \'{print $5}\'", &pMacAddr); - - localtime_r(&timeStamp, &localTime); - - strncpy(g_PostLogParams[0].keyValue, g_LogProcessInfo.pChipId, MAX_HTTP_POST_SIZE); - strncpy(g_PostLogParams[1].keyValue, (pMacAddr && strlen(pMacAddr) > 0) ? pMacAddr : "00:00:00:00:00:00", MAX_HTTP_POST_SIZE); - strncpy(g_PostLogParams[2].keyValue, GetCurrentVersion(), MAX_HTTP_POST_SIZE); - sprintf(g_PostLogParams[3].keyValue, "Build: %s %s", __DATE__, __TIME__); - strncpy(g_PostLogParams[4].keyValue, g_LogProcessInfo.pChipSerial, MAX_HTTP_POST_SIZE); - - for(int i = 0; i < sizeof(g_PostLogParams) / sizeof(g_PostLogParams[0]); i++) - { - LL_APPEND(g_pLogParamsArray, &g_PostLogParams[i]); - } - - if(pMacAddr) - { - free(pMacAddr); - } -} - -int HttpPostLogFile(char* pSession) -{ - int ret; - struct tm localTime; - const char* pFileName = "/tmp/backuplog.tar.gz"; - const char* pLastFile = "/mnt/UDISK/backuplog_nand.tar.gz"; - char* pLogServerURL = GetCurServerAddr(LOG_MODULE); - time_t timeStamp = time((time_t*)NULL); - - ret = system(" /usr/sbin/backuplocalfiles.sh"); - - if(access(pFileName, F_OK) != 0 - && access(pLastFile, F_OK) != 0) - { - return -ERR_FILE_NOT_EXISTS; - } - - localtime_r(&timeStamp, &localTime); - - memset(g_PostLogParams[5].keyValue, 0, MAX_HTTP_POST_SIZE); - sprintf(g_PostLogParams[5].keyValue, "%04u-%02u-%02u %02u:%02u:%02u", - localTime.tm_year + 1900, - localTime.tm_mon + 1, - localTime.tm_mday, - localTime.tm_hour, - localTime.tm_min, - localTime.tm_sec); - - memset(g_PostLogParams[6].keyValue, 0, MAX_HTTP_POST_SIZE); - - if(pSession && strlen(pSession) >= 2) - { - strncpy(g_PostLogParams[6].keyValue, pSession, MAX_HTTP_POST_SIZE); - } - else - { - strncpy(g_PostLogParams[6].keyValue, "{}", MAX_HTTP_POST_SIZE); - } - - if(access(pFileName, F_OK) == 0) - { - ret = InetHttpUploadFileSync(pLogServerURL, pFileName, g_pLogParamsArray); - - if(ret == 0) - { - LOG_EX(LOG_Debug, "Upload Log Data [%s] To Server [%s]\n", pFileName, pLogServerURL); - unlink(pFileName); - } - else - { - LOG_EX(LOG_Error, "Upload Log Data [%s] To Server [%s]\n", pFileName, pLogServerURL); - } - } - - if(access(pLastFile, F_OK) == 0) - { - ret = InetHttpUploadFileSync(pLogServerURL, pLastFile, g_pLogParamsArray); - - if(ret == 0) - { - LOG_EX(LOG_Debug, "Upload Log Data [%s] To Server [%s]\n", pLastFile, pLogServerURL); - unlink(pLastFile); - } - else - { - LOG_EX(LOG_Error, "Upload Log Data [%s] To Server [%s]\n", pLastFile, pLogServerURL); - } - } - - //fprintf(stdout, "Upload Log Data [%s] To Server [%s], size = %d\n", pFileName, UPL_HTTP_URL, fileSize); - - return ret; -} - -static int __logNetworkSend(PLOG_ITEM pItem) -{ - PLOG_PROTO_CONTENT pLogInfo; - unsigned char *pBuf; - int ret, totalSize = 0; - static unsigned short sendSeq = 0; - - if(pItem == NULL || pItem->pLogContent == NULL || strlen(pItem->pLogContent) == 0) - { - return (-ERR_INPUT_PARAMS); - } - - totalSize = sizeof(LOG_PROTO_CONTENT) + strlen(pItem->pLogContent); - - pBuf = (unsigned char *)malloc(totalSize); - - if(pBuf == NULL) - { - return (-ERR_MALLOC_MEMORY); - } - - memset(pBuf, 0, totalSize); - - pLogInfo = (PLOG_PROTO_CONTENT)pBuf; - - pLogInfo->logSeq = htons(sendSeq++); - pLogInfo->timeStamp = htonl(pItem->timestamp.tv_sec); - pLogInfo->nanotime = htonl(pItem->timestamp.tv_usec); - pLogInfo->pid = htonl(g_LogProcessInfo.pid); - pLogInfo->logLevel = htonl(pItem->level); - - memcpy(pLogInfo->logContent, pItem->pLogContent, strlen(pItem->pLogContent)); - - ret = sendto(g_logSock, pBuf, totalSize, 0, - (struct sockaddr *)&g_logAddr, sizeof(g_logAddr)); - - if(ret == totalSize) - { - return (0); - } - else - { - //LOG_EX(LOG_Error, "Send %d bytes, need %d bytes\n", ret, totalSize); - return (-ERR_NETWORK_SEND); - } -} - -static void __cleanupBackupItem(PLOG_BACKUP pItem) -{ - if(pItem) - { - LL_DELETE(g_pLogBackupList, pItem); - - if(pItem->plogFilePath) - { - if(access(pItem->plogFilePath, F_OK) == 0) - { - unlink(pItem->plogFilePath); - } - - free(pItem->plogFilePath); - } - - if(pItem->pGzFilePath) - { - if(access(pItem->pGzFilePath, F_OK) == 0) - { - unlink(pItem->pGzFilePath); - } - - free(pItem->pGzFilePath); - } - - free(pItem); - } -} - -static void* __uvLogBackupProc(void *pParams) -{ - SMTP_MAIL_CONFIG smtpCfg; - char gzLogPath[MAX_PATH]; - struct tm localTime; - const char *pFrom = LOG_MAIL_USERNAME; - const char *pTo[] = {g_pEmailBox, NULL}; - char *pMacAddr = NULL; - - //const char *pCc[] = {"xajhuang@qq.com", "xajhuang@163.com", NULL}; - - memset(&smtpCfg, 0, sizeof(SMTP_MAIL_CONFIG)); - - smtpCfg.pUserName = LOG_MAIL_USERNAME; - smtpCfg.pPassword = LOG_MAIL_PASSWORD; - smtpCfg.pSmtpServer = LOG_MAIL_SERVER; - smtpCfg.smtpPort = LOG_MAIL_PORT; - -#ifdef PLATFORM_CPU - GetShellExecResult("ifconfig enp3s0 | grep HWaddr | awk \'{print $5}\'", &pMacAddr); -#else - GetShellExecResult("ifconfig wlan0 | grep HWaddr | awk \'{print $5}\'", &pMacAddr); -#endif - - if(pMacAddr == NULL || strlen(pMacAddr) == 0) - { - pMacAddr = strdup("00:00:00:00:00:00"); - } - - while(TRUE) - { - PLOG_BACKUP pItem = NULL, pTmp = NULL; - time_t timeStamp = time((time_t*)NULL); - localtime_r(&timeStamp, &localTime); - - uv_rwlock_wrlock(&g_uvLogBackLock); - - LL_FOREACH_SAFE(g_pLogBackupList, pItem, pTmp) - { - const char *pAttact[2]; - UT_string *pTitle, *pMessage, *pDatetime; - char* pMD5Val; - - pAttact[1] = NULL; - - if(pItem->plogFilePath == NULL || strlen(pItem->plogFilePath) == 0) - { - __cleanupBackupItem(pItem); - continue; - } - - if(timeStamp - pItem->timestamp >= 3600) - { - __cleanupBackupItem(pItem); - continue; - } - - if(pItem->sendTimes >= 3) - { - __cleanupBackupItem(pItem); - continue; - } -#if 0 - if(g_bEnLogToServer) - { - __logHttpPostFile(pItem->plogFilePath); - //InetHttpUploadFileSync(UPL_HTTP_URL, pItem->pGzFilePath, NULL); - } -#endif - if(pItem->pGzFilePath == NULL) - { - memset(gzLogPath, 0, MAX_PATH); - sprintf(gzLogPath, "%s/%d_%s_%u.log.gz", - LOG_FILE_BASEDIR, g_LogProcessInfo.pid, g_LogProcessInfo.exeName, pItem->tolLogs); - - if(GZipFileCompress(pItem->plogFilePath, gzLogPath) != 0) - { - LOG_EX(LOG_Error, "Create Gzip File Error: %s\n", gzLogPath); - continue; - } - else - { - pItem->pGzFilePath = strdup(gzLogPath); - } - } - - pMD5Val = (char*)EvpMD5HashFile(pItem->pGzFilePath); - - utstring_new(pTitle); - utstring_new(pMessage); - utstring_new(pDatetime); - - utstring_printf(pDatetime, "%04u-%02u-%02u %02u:%02u:%02u", - localTime.tm_year + 1900, - localTime.tm_mon + 1, - localTime.tm_mday, - localTime.tm_hour, - localTime.tm_min, - localTime.tm_sec); - - utstring_printf(pTitle, "Log [%s]-[%s]-[%s]", - g_LogProcessInfo.exeName, - g_LogProcessInfo.pChipSerial, - utstring_body(pDatetime)); - - utstring_printf(pMessage, "\r\n" - "

Summary information:

" - "


" - "

" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "" - "
Items
%u
Process PID
%d
Process Name
%s
CPU ID
%s
Serial
%s
Mac Address
%s
File Checksum
%s
Log Level
0x%08X
Datetime
%s
" - "

" - "\r\n", - pItem->tolLogs, - g_LogProcessInfo.pid, - g_LogProcessInfo.exeName, - g_LogProcessInfo.pChipId, - g_LogProcessInfo.pChipSerial, - pMacAddr, - SAFE_STRING_VALUE(pMD5Val), - g_iMinLevel, - utstring_body(pDatetime)); - - pAttact[0] = pItem->pGzFilePath; -#if 0 - if(g_bEnMailBackup && - InetSmtpSendEmail(pFrom, pTo, NULL, utstring_body(pTitle), - utstring_body(pMessage), pAttact, &smtpCfg) == 0) - { - __cleanupBackupItem(pItem); - } - else - { - LOG_EX(LOG_Error, "Send email error: %s\n", pItem->pGzFilePath); - } -#endif - pItem->sendTimes++; - - if(pMD5Val) - { - free(pMD5Val); - } - - utstring_free(pTitle); - utstring_free(pMessage); - utstring_free(pDatetime); - } - - uv_rwlock_wrunlock(&g_uvLogBackLock); - - sleep(1); - } - - free(pMacAddr); - pthread_detach(pthread_self()); - return (NULL); -} - -static void __logColorOutput(const char* pColFmt, UT_string* pLog) -{ - if(pLog == NULL) - { - return; - } - - if(pColFmt == NULL) - { - print("%s", utstring_body(pLog)); - } - else - { - if(utstring_find(pLog, -1, "\n", 1) == utstring_len(pLog) - 1) - { - char* pLogArray = utstring_body(pLog); - pLogArray[utstring_len(pLog) - 1] = 0; - - print(pColFmt, pLogArray, '\n'); - - strcat(pLogArray, "\n"); - } - else - { - print(pColFmt, utstring_body(pLog), '\0'); - } - } -} - -static void* __logOutputThread(void *p) -{ - while(TRUE) - { - int isWriteLog = FALSE; - PLOG_ITEM pItem = NULL, pTmp = NULL; - - uv_rwlock_wrlock(&g_uvLogLock); - - LL_FOREACH_SAFE(g_pLogItemList, pItem, pTmp) - { - UT_string *pLogStr; - struct tm lTime; - int logFileSize = 0; - - if(++g_LogRdPos % 100 == 0) - { - GET_FILE_SIZE(g_LogProcessInfo.logFilePath, logFileSize); - } - - localtime_r(&(pItem->timestamp.tv_sec), &lTime); - - utstring_new(pLogStr); - - if(pItem->isAddTags) - { - utstring_printf(pLogStr, "[%04d-%02d-%02d %02d:%02d:%02d.%03ld] [%s] %s", - lTime.tm_year + 1900, lTime.tm_mon + 1, lTime.tm_mday, - lTime.tm_hour, lTime.tm_min, lTime.tm_sec, pItem->timestamp.tv_usec / 1000, - LogLevelToStr(pItem->level), pItem->pLogContent); - } - else - { - utstring_printf(pLogStr, "%s", pItem->pLogContent); - } - - if(pItem->isPrinted == FALSE) - { - if(pItem->level & LOG_Error - || pItem->level & LOG_Fatal) - { - __logColorOutput(SHOW_CONSOLE_RED, pLogStr); - } - else if(pItem->level & LOG_Warn - || pItem->level & LOG_Unknown) - { - __logColorOutput(SHOW_CONSOLE_YELLOW, pLogStr); - } - else if(pItem->level & LOG_Test - || pItem->level & LOG_Call) - { - __logColorOutput(SHOW_CONSOLE_BLUE, pLogStr); - } - else if(pItem->level & LOG_Devp) - { - __logColorOutput(SHOW_CONSOLE_GREEN, pLogStr); - } - else - { - print("%s", utstring_body(pLogStr)); - } - - pItem->isPrinted = TRUE; - } - - if(g_logSock != -1 && GetCurrWIFIConnStatus() == WIFI_CONNECTED) - { - __logNetworkSend(pItem); - } - - if(g_LogProcessInfo.pLogFile != NULL && g_bEnLogToFile) - { - if(logFileSize >= MAX_LOG_FILE_SIZE) - { - fflush(g_LogProcessInfo.pLogFile); - fclose(g_LogProcessInfo.pLogFile); -#if 0 - if(g_bEnMailBackup) - { - PLOG_BACKUP pBackup = (PLOG_BACKUP)malloc(sizeof(struct LOG_BACKUP)); - char path[MAX_PATH]; - - memset(path, 0, MAX_PATH); - sprintf(path, "%s/%s.bak_%u.log", - LOG_FILE_BASEDIR, - basename_v2(g_LogProcessInfo.logFilePath), - g_LogRdPos); - rename(g_LogProcessInfo.logFilePath, path); - - if(pBackup) - { - memset(pBackup, 0, sizeof(struct LOG_BACKUP)); - pBackup->timestamp = time(NULL); - pBackup->plogFilePath = strdup(path); - pBackup->sendTimes = 0; - pBackup->tolLogs = g_LogRdPos - 1; - - uv_rwlock_wrlock(&g_uvLogBackLock); - LL_APPEND(g_pLogBackupList, pBackup); - uv_rwlock_wrunlock(&g_uvLogBackLock); - } - } -#endif - g_LogProcessInfo.pLogFile = fopen(g_LogProcessInfo.logFilePath, "w+"); - } - - if(g_LogProcessInfo.pLogFile) - { - fwrite(utstring_body(pLogStr), 1, utstring_len(pLogStr), g_LogProcessInfo.pLogFile); - } - - isWriteLog = TRUE; - } - - LL_DELETE(g_pLogItemList, pItem); - - utstring_free(pLogStr); - free(pItem->pLogContent); - free(pItem); - - if(g_LogRdPos % 100 == 0) - { - break; - } - } - - uv_rwlock_wrunlock(&g_uvLogLock); - - usleep(1000); - if(g_LogProcessInfo.pLogFile != NULL && isWriteLog) - { - fflush(g_LogProcessInfo.pLogFile); - } - } - - pthread_detach(pthread_self()); - return (NULL); -} - -/** - * @brief 设置调试等级 - * @param level 调试等级 - * @param iEnable 1 打开调试等级, 0 关闭调试等级 - */ -void IHW_EnableLogLevel(LOG_LEVEL level, int iEnable) -{ - if(iEnable > 0) - { - g_iMinLevel |= level; - } - else - { - g_iMinLevel &= ~(level); - } -} - -static int __getCfgFromCfgFile(void) -{ - int ret = 0; - g_bEnableLog = CfgGetBoolValue("Global.Log.Enable", g_bEnableLog); - g_iMinLevel = CfgGetIntValue("Global.Log.Level", g_iMinLevel); - g_bEnMailBackup = CfgGetBoolValue("Global.Log.LogToEMail.Enable", g_bEnMailBackup); - g_pEmailBox = CfgGetStringValue("Global.Log.LogToEMail.EMail", LOG_MAIL_RECEIVER); - g_bEnLogToFile = CfgGetBoolValue("Global.Log.LogToFile", g_bEnLogToFile); - g_bEnLogToServer = CfgGetBoolValue("Global.Log.LogToServer", g_bEnLogToServer); - -#if 0 - LOG_EX(LOG_Debug, "g_bEnableLog = %d\n", g_bEnableLog); - LOG_EX(LOG_Debug, "g_iMinLevel = 0x%X\n", g_iMinLevel); - LOG_EX(LOG_Debug, "g_bEnMailBackup = %d\n", g_bEnMailBackup); - LOG_EX(LOG_Debug, "g_pEmailBox = %s\n", g_pEmailBox); - LOG_EX(LOG_Debug, "g_bEnLogToFile = %d\n", g_bEnLogToFile); - LOG_EX(LOG_Debug, "g_bEnLogToServer = %d\n", g_bEnLogToServer); -#endif - - ret = CfgGetBoolValue("Global.Log.LogToUDPServer.Enable", FALSE); - - if(ret) - { - char *pIpAddr = NULL; - int udpPortBase = CfgGetBoolValue("Global.Log.LogToUDPServer.UdpBasePort", 10000); - int port = udpPortBase + DBusLibGetModName(); - - if(g_logSock != -1) - { - close(g_logSock); - g_logSock = -1; - } - - pIpAddr = CfgGetStringValue("Global.Log.LogToUDPServer.UdpServerIp", NULL); - - LOG_EX(LOG_Debug, "UDP Ipaddr = %s, port = %d\n", pIpAddr, port); - - if(pIpAddr) - { - memset(&g_logAddr, 0, sizeof(g_logAddr)); - g_logAddr.sin_family = AF_INET; - g_logAddr.sin_port = htons(port); - g_logAddr.sin_addr.s_addr = inet_addr(pIpAddr); - - g_logSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - } - } -} -/** - * @brief 初始化系统日志功能 - * @param pLogTag 系统日志标志 - * @param pPath 系统日志保存路径 - * @param bEnable 打开/关闭调试信息 - */ -void IHW_InitLOG(const char* pLogTag, const char* pPath, int bEnable) -{ - int ret; - char strPath[MAX_PATH]; - - memset(&g_logAddr, 0, sizeof(g_logAddr)); - uv_rwlock_init(&g_uvLogLock); - g_LogRdPos = 0; - memset(g_strLogTag, 0, 32); - - memset(&g_LogProcessInfo, 0, sizeof(LOG_PROCESS_INFO)); - - if(pLogTag == NULL) - { - strcpy(g_strLogTag, ""); - } - else - { - strncpy(g_strLogTag, pLogTag, 31); - } - - memset(strPath, 0, MAX_PATH); - - g_LogProcessInfo.pid = getpid(); - if(readlink("/proc/self/exe", strPath, MAX_PATH) == -1) - { - strcpy(g_LogProcessInfo.exeName, pLogTag); - } - else - { - char *pExeName = strrchr(strPath, '/'); - - if(pExeName == NULL) - { - strncpy(g_LogProcessInfo.exeName, strPath, MAX_PATH - 1); - } - else - { - strncpy(g_LogProcessInfo.exeName, pExeName + 1, MAX_PATH - 1); - } - } - - //fprintf(stdout, "pid = %d, name = %s\n", g_LogProcessInfo.pid, g_LogProcessInfo.exeName); - g_LogProcessInfo.pChipId = GetCpuChipId(); - g_LogProcessInfo.pChipSerial = GetCpuSerial(); - memset(g_LogProcessInfo.logFilePath, 0, MAX_PATH); - sprintf(g_LogProcessInfo.logFilePath, "%s/%s_%d.log", LOG_FILE_BASEDIR, g_LogProcessInfo.exeName, g_LogProcessInfo.pid); - - memset(strPath, 0, MAX_PATH); - sprintf(strPath, "rm -f %s/%s_*.log > /dev/zero", LOG_FILE_BASEDIR, g_LogProcessInfo.exeName); - ret = system(strPath); - - g_LogProcessInfo.pLogFile = fopen(g_LogProcessInfo.logFilePath, "w+"); - - g_bEnableLog = bEnable; - - __getCfgFromCfgFile(); - -#if 0 - LOG_CFG_PROTOCOL logCfg; - - memset(&logCfg, 0, sizeof(LOG_CFG_PROTOCOL)); - logCfg.cfgCmd = CMD_LOG_NETWORK; - logCfg.iParams1 = inet_addr("10.240.84.163"); - logCfg.iParams2 = htons(10000); - UpgradLogConfigure(&logCfg); -#endif - - __initPostLogParams(); -} - -void IHW_RunLogService(void) -{ - pthread_create(&g_logThreadId, NULL, __logOutputThread, NULL); - pthread_create(&g_backupThreadId, NULL, __uvLogBackupProc, NULL); -} - -static void __logTo(LOG_LEVEL level, int isAddTag, char* pMsg, int isPrint) -{ - PLOG_ITEM pLogItem; - - pLogItem = (PLOG_ITEM)malloc(sizeof(struct LOG_ITEM)); - - if(pLogItem == NULL) - { - return; - } - - pLogItem->pLogContent = strdup(pMsg); - pLogItem->isPrinted = isPrint ? FALSE : TRUE; - pLogItem->level = level; - pLogItem->isAddTags = isAddTag ? TRUE : FALSE; - gettimeofday(&(pLogItem->timestamp), NULL); - - uv_rwlock_wrlock(&g_uvLogLock); - LL_APPEND(g_pLogItemList, pLogItem); - uv_rwlock_wrunlock(&g_uvLogLock); -} - -void IHW_LogStrWithoutPrint(int level, char* pMsg) -{ - __logTo(level, TRUE, pMsg, FALSE); -} - -void IHW_LogRawString(int level, char* pMsg) -{ - __logTo(level, TRUE, pMsg, TRUE); -} - -/** - * @brief 输出调试信息 - * @param cFlag 调试信息开关 - * @param pMsg 调试信息内容 - */ -void IHW_LOG_UNTAG(LOG_LEVEL level, const char* pMsg, ...) -{ - va_list arg_ptr; - UT_string *pLogContent; - - if(!g_bEnableLog) - { - return; - } - - // 检查调试等级 - if(!(g_iMinLevel & level)) - { - return; - } - - utstring_new(pLogContent); - va_start(arg_ptr, pMsg); - utstring_printf_va(pLogContent, pMsg, arg_ptr); - va_end(arg_ptr); - - __logTo(level, FALSE, utstring_body(pLogContent), TRUE); - - utstring_free(pLogContent); -} - -/** - * @brief 输出调试信息 - * @param cFlag 调试信息开关 - * @param pMsg 调试信息内容 - */ -void IHW_LOG(LOG_LEVEL level, const char* pMsg, ...) -{ - UT_string* pLogContent = NULL; - va_list arg_ptr; - - if(!g_bEnableLog) - { - return; - } - - // 检查调试等级 - if(!(g_iMinLevel & level)) - { - return; - } - - utstring_new(pLogContent); - va_start(arg_ptr, pMsg); - utstring_printf_va(pLogContent, pMsg, arg_ptr); - va_end(arg_ptr); - - __logTo(level, TRUE, utstring_body(pLogContent), TRUE); - - utstring_free(pLogContent); -} - -void IHW_DisableLogOut(void) -{ - g_bEnableLog = FALSE; -} - -void IHW_EnableLogOut(void) -{ - g_bEnableLog = TRUE; -} - -#if 0 -void LogUploadCurLogFile(void) -{ - UT_string *pFn = NULL, *pCmd = NULL; - utstring_new(pFn); - utstring_new(pCmd); - - utstring_printf(pFn, "/tmp/%s_%s.bak.log", g_LogProcessInfo.exeName, g_LogProcessInfo.pChipId); - utstring_printf(pCmd, "cp %s %s", g_LogProcessInfo.logFilePath, utstring_body(pFn)); - - __logHttpPostFile(utstring_body(pFn)); - //InetHttpUploadFileSync(UPL_HTTP_URL, utstring_body(pFn), NULL); - - utstring_free(pFn); - utstring_free(pCmd); -} -#endif - -#if 0 -void UploadLogFile(char* pFilePath) -{ - int fileSize = 0; - - if(pFilePath == NULL || strlen(pFilePath) == 0) - { - return; - } - - GET_FILE_SIZE(pFilePath, fileSize); - - if(fileSize <= 0) - { - LOG_EX(LOG_Warn, "File Size Error: %d\n", fileSize); - return; - } - - __logHttpPostFile(pFilePath); -} -#endif - -void UpgradLogConfigure(PLOG_CFG_PROTOCOL pCfg) -{ - switch(pCfg->cfgCmd) - { - case CMD_LOG_ENABLE: - g_bEnableLog = pCfg->iParams1; - break; - - case CMD_LOG_FILE: - if(pCfg->iParams1 == FALSE) - { - g_bEnMailBackup = g_bEnLogToFile = FALSE; - } - else - { - g_bEnLogToFile = TRUE; - } - break; - - case CMD_LOG_MAIL: - g_bEnMailBackup = pCfg->iParams1; - break; - - case CMD_LOG_LEVEL: - if(pCfg->iParams2 == FALSE) - { - if(pCfg->iParams1 == 0) - { - g_iMinLevel = LOG_Fatal | LOG_Error | LOG_Devp; - } - else - { - g_iMinLevel &= ~(pCfg->iParams1); - } - } - else - { - g_iMinLevel |= pCfg->iParams1; - } - break; - - case CMD_LOG_NETWORK: - if(pCfg->iParams1 == 0) - { - memset(&g_logAddr, 0, sizeof(g_logAddr)); - close(g_logSock); - g_logSock = -1; - } - else - { - if(g_logSock != -1) - { - close(g_logSock); - } - - memset(&g_logAddr, 0, sizeof(g_logAddr)); - g_logAddr.sin_family = AF_INET; - g_logAddr.sin_port = htons((pCfg->iParams2 & 0xFFFF)); - g_logAddr.sin_addr.s_addr = (pCfg->iParams1); - - g_logSock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); - } - break; - - case CMD_LOG_SERVER: - g_bEnLogToServer = pCfg->iParams1; - break; - - default: break; - } -} - -const char* LogLeveToString(LOG_LEVEL lv) -{ - switch(lv) - { - case LOG_Fatal: return "LOG_Fatal"; - case LOG_Error: return "LOG_Error"; - case LOG_Warn: return "LOG_Warn"; - case LOG_Debug: return "LOG_Debug"; - case LOG_Info: return "LOG_Info"; - case LOG_Test: return "LOG_Test"; - case LOG_Call: return "LOG_Call"; - case LOG_Devp: return "LOG_Devp"; - case LOG_Step: return "LOG_Step"; - case LOG_Unknown: return "LOG_Unknown"; - case LOG_All: return "LOG_All"; - case LOG_Close: return "LOG_Close"; - } - - return "Unknown"; -} - -static void __uvSysPointIOProc(void *pParams) -{ - while(TRUE) - { - PSYSPOINT_ITEM pItem = NULL, pTmp = NULL; - int iFileSize; - time_t tmNow = time(NULL); - - if(g_SysPonitInfo.pMarkFile) - { - uv_rwlock_wrlock(&g_SysPonitInfo.uvRwLock); - LL_FOREACH_SAFE(g_pSysPointArray, pItem, pTmp) - { - fwrite(pItem->pContent, 1, strlen(pItem->pContent), g_SysPonitInfo.pMarkFile); - free(pItem->pContent); - LL_DELETE(g_pSysPointArray, pItem); - free(pItem); - } - uv_rwlock_wrunlock(&g_SysPonitInfo.uvRwLock); - } - - GET_FILE_SIZE(g_SysPonitInfo.savePath, iFileSize); - - if(g_SysPonitInfo.lastPostTime == 0 || tmNow < g_SysPonitInfo.lastPostTime) - { - g_SysPonitInfo.lastPostTime = g_SysPonitInfo.lastMarkTime = tmNow; - tmNow = 0; - } -#if 0 - LOG_EX(LOG_Debug, "iFile = %d, MaxSize = %d, upTime = %d\n", - iFileSize, g_SysPonitInfo.iMaxCacheSize, g_SysPonitInfo.iEveryUploadTime); - - LOG_EX(LOG_Debug, "tm = %d, last = %d\n", tmNow, g_SysPonitInfo.lastPostTime); -#endif - if(iFileSize > g_SysPonitInfo.iMaxCacheSize - || tmNow - g_SysPonitInfo.lastPostTime > g_SysPonitInfo.iEveryUploadTime) - { - int fileSize = 0; - - GET_FILE_SIZE(g_SysPonitInfo.savePath, fileSize); - - if(fileSize > 0) - { - SysPointMarkUpload(); - g_SysPonitInfo.lastPostTime = tmNow; - } - - if(tmNow - g_SysPonitInfo.lastPostTime > g_SysPonitInfo.iEveryUploadTime) - { - SysPointMarkUpload(); - g_SysPonitInfo.lastPostTime = tmNow; - } - } - - if(g_SysPonitInfo.pMarkFile) - { - fflush(g_SysPonitInfo.pMarkFile); - } - - sleep(1); - } - - pthread_detach(pthread_self()); -} - -int SysPointMarkInit(char* pDevId, int iMaxSize, int iPostTime) -{ - LOG_EX(LOG_Debug, "pDevId = %s, iMaxSize = %d, iPostTime = %d\n", pDevId, iMaxSize, iPostTime); - - if(g_SysPonitInfo.pDeviceId != NULL) - { - if(pDevId && strlen(pDevId) > 0) - { - free(g_SysPonitInfo.pDeviceId); - g_SysPonitInfo.pDeviceId = strdup(pDevId); - } - - if(iMaxSize > 0) - { - g_SysPonitInfo.iMaxCacheSize = iMaxSize; - } - else - { - g_SysPonitInfo.iMaxCacheSize = 1024 * 10; - } - - if(iPostTime > 0) - { - g_SysPonitInfo.iEveryUploadTime = iPostTime; - } - else - { - g_SysPonitInfo.iEveryUploadTime = SYS_POINT_UPLOAD_TIME; - } - } - else - { - memset(&g_SysPonitInfo, 0, sizeof(SYSPOINT_INFO)); - - if(pDevId && strlen(pDevId) > 0) - { - g_SysPonitInfo.pDeviceId = strdup(pDevId); - } - - if(iMaxSize > 0) - { - g_SysPonitInfo.iMaxCacheSize = iMaxSize; - } - else - { - g_SysPonitInfo.iMaxCacheSize = 1024 * 1024; - } - - if(iPostTime > 0) - { - g_SysPonitInfo.iEveryUploadTime = iPostTime; - } - else - { - g_SysPonitInfo.iEveryUploadTime = SYS_POINT_UPLOAD_TIME; - } - - sprintf(g_SysPonitInfo.savePath, "%s/sys_point_mark.log", LOG_FILE_BASEDIR); - - g_SysPonitInfo.pMarkFile = fopen(g_SysPonitInfo.savePath, "w+"); - - if(g_SysPonitInfo.pMarkFile == NULL) - { - LOG_EX(LOG_Error, "Create File: %s Error\n", g_SysPonitInfo.savePath); - return -ERR_OPEN_FILE; - } - - uv_rwlock_init(&g_SysPonitInfo.uvRwLock); - - uv_thread_create(&g_SysPonitInfo.uvIOThread, __uvSysPointIOProc, NULL); - } - - return 0; -} - -int SysPointMark(char* pMarkInfo) -{ - PSYSPOINT_ITEM pItem; - - if(pMarkInfo == NULL || strlen(pMarkInfo) == 0) - { - return -ERR_INPUT_PARAMS; - } - - if(g_SysPonitInfo.iMaxCacheSize <= 0) - { - return -ERR_UNSUPPORT; - } - - pItem = (PSYSPOINT_ITEM)malloc(sizeof(struct SYSPOINT_ITEM)); - - if(pItem == NULL) - { - return -ERR_MALLOC_MEMORY; - } - - pItem->pContent = strdup(pMarkInfo); - g_SysPonitInfo.lastMarkTime = time(NULL); - - uv_rwlock_wrlock(&g_SysPonitInfo.uvRwLock); - LL_APPEND(g_pSysPointArray, pItem); - uv_rwlock_wrunlock(&g_SysPonitInfo.uvRwLock); - - //LOG_EX(LOG_Debug, "SysMark: %s\n", pItem->pContent); - - return 0; -} - -int SysPointMarkUpload(void) -{ - int ret, size = 0; - char path[MAX_PATH]; - - memset(path, 0, MAX_PATH); - sprintf(path, "%s.txt", g_SysPonitInfo.savePath); - - if(access(path, F_OK) == 0) - { - unlink(path); - } - - GET_FILE_SIZE(g_SysPonitInfo.savePath, size); - - if(size <= 0) - { - LOG_EX(LOG_Debug, "Upload System Mark Data [%s] Is Empty, Skip......\n", g_SysPonitInfo.savePath); - return 0; - } - - rename(g_SysPonitInfo.savePath, path); - - fclose(g_SysPonitInfo.pMarkFile); - g_SysPonitInfo.pMarkFile = fopen(g_SysPonitInfo.savePath, "w+"); - - size = 0; - - do - { - ret = InetHttpUploadFileSync(GetCurServerAddr(MARK_POINT_MODULE), path, NULL); - sleep(1); - } while(ret != 0 && ++size < 3); - - LOG_EX(LOG_Debug, "Upload System Mark Data [%s] To Server [%s]\n", path, GetCurServerAddr(MARK_POINT_MODULE)); - - unlink(path); - - return 0; -} - diff --git a/log/mark_point.c b/log/mark_point.c new file mode 100644 index 0000000..ddc4a06 --- /dev/null +++ b/log/mark_point.c @@ -0,0 +1,270 @@ +/** @file log.c + @brief 系统日志接口文件 + @version 1.0.0 +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "smart_sound.h" +#include "inet_api.h" +#include "libuv_dbus.h" +#include "server_addr.h" + + +#ifdef PLATFORM_CPU +#define LOG_FILE_BASEDIR (".") +#else +#define LOG_FILE_BASEDIR ("/tmp") +#endif + +#define SYS_POINT_UPLOAD_TIME (600) + +typedef struct +{ + char* pDeviceId; + char savePath[MAX_PATH]; + int iMaxCacheSize; + int iEveryUploadTime; + time_t lastPostTime; + time_t lastMarkTime; + FILE* pMarkFile; + uv_rwlock_t uvRwLock; + uv_thread_t uvIOThread; +} SYSPOINT_INFO, *PSYSPOINT_INFO; + +typedef struct SYSPOINT_ITEM +{ + char* pContent; + struct SYSPOINT_ITEM *next, *prev; +} *PSYSPOINT_ITEM; + + +static SYSPOINT_INFO g_SysPonitInfo; +static PSYSPOINT_ITEM g_pSysPointArray = NULL; +static PHTTP_POST_ATTACH g_pLogParamsArray = NULL; + +static void __uvSysPointIOProc(void *pParams) +{ + while(TRUE) + { + PSYSPOINT_ITEM pItem = NULL, pTmp = NULL; + int iFileSize; + time_t tmNow = time(NULL); + + if(g_SysPonitInfo.pMarkFile) + { + uv_rwlock_wrlock(&g_SysPonitInfo.uvRwLock); + LL_FOREACH_SAFE(g_pSysPointArray, pItem, pTmp) + { + fwrite(pItem->pContent, 1, strlen(pItem->pContent), g_SysPonitInfo.pMarkFile); + free(pItem->pContent); + LL_DELETE(g_pSysPointArray, pItem); + free(pItem); + } + uv_rwlock_wrunlock(&g_SysPonitInfo.uvRwLock); + } + + GET_FILE_SIZE(g_SysPonitInfo.savePath, iFileSize); + + if(g_SysPonitInfo.lastPostTime == 0 || tmNow < g_SysPonitInfo.lastPostTime) + { + g_SysPonitInfo.lastPostTime = g_SysPonitInfo.lastMarkTime = tmNow; + tmNow = 0; + } +#if 0 + LOG_EX(LOG_Debug, "iFile = %d, MaxSize = %d, upTime = %d\n", + iFileSize, g_SysPonitInfo.iMaxCacheSize, g_SysPonitInfo.iEveryUploadTime); + + LOG_EX(LOG_Debug, "tm = %d, last = %d\n", tmNow, g_SysPonitInfo.lastPostTime); +#endif + if(iFileSize > g_SysPonitInfo.iMaxCacheSize + || tmNow - g_SysPonitInfo.lastPostTime > g_SysPonitInfo.iEveryUploadTime) + { + int fileSize = 0; + + GET_FILE_SIZE(g_SysPonitInfo.savePath, fileSize); + + if(fileSize > 0) + { + SysPointMarkUpload(); + g_SysPonitInfo.lastPostTime = tmNow; + } + + if(tmNow - g_SysPonitInfo.lastPostTime > g_SysPonitInfo.iEveryUploadTime) + { + SysPointMarkUpload(); + g_SysPonitInfo.lastPostTime = tmNow; + } + } + + if(g_SysPonitInfo.pMarkFile) + { + fflush(g_SysPonitInfo.pMarkFile); + } + + sleep(1); + } + + pthread_detach(pthread_self()); +} + +int SysPointMarkInit(char* pDevId, int iMaxSize, int iPostTime) +{ + LOG_EX(LOG_Debug, "pDevId = %s, iMaxSize = %d, iPostTime = %d\n", pDevId, iMaxSize, iPostTime); + + if(g_SysPonitInfo.pDeviceId != NULL) + { + if(pDevId && strlen(pDevId) > 0) + { + free(g_SysPonitInfo.pDeviceId); + g_SysPonitInfo.pDeviceId = strdup(pDevId); + } + + if(iMaxSize > 0) + { + g_SysPonitInfo.iMaxCacheSize = iMaxSize; + } + else + { + g_SysPonitInfo.iMaxCacheSize = 1024 * 10; + } + + if(iPostTime > 0) + { + g_SysPonitInfo.iEveryUploadTime = iPostTime; + } + else + { + g_SysPonitInfo.iEveryUploadTime = SYS_POINT_UPLOAD_TIME; + } + } + else + { + memset(&g_SysPonitInfo, 0, sizeof(SYSPOINT_INFO)); + + if(pDevId && strlen(pDevId) > 0) + { + g_SysPonitInfo.pDeviceId = strdup(pDevId); + } + + if(iMaxSize > 0) + { + g_SysPonitInfo.iMaxCacheSize = iMaxSize; + } + else + { + g_SysPonitInfo.iMaxCacheSize = 1024 * 1024; + } + + if(iPostTime > 0) + { + g_SysPonitInfo.iEveryUploadTime = iPostTime; + } + else + { + g_SysPonitInfo.iEveryUploadTime = SYS_POINT_UPLOAD_TIME; + } + + sprintf(g_SysPonitInfo.savePath, "%s/sys_point_mark.log", LOG_FILE_BASEDIR); + + g_SysPonitInfo.pMarkFile = fopen(g_SysPonitInfo.savePath, "w+"); + + if(g_SysPonitInfo.pMarkFile == NULL) + { + LOG_EX(LOG_Error, "Create File: %s Error\n", g_SysPonitInfo.savePath); + return -ERR_OPEN_FILE; + } + + uv_rwlock_init(&g_SysPonitInfo.uvRwLock); + + uv_thread_create(&g_SysPonitInfo.uvIOThread, __uvSysPointIOProc, NULL); + } + + return 0; +} + +int SysPointMark(char* pMarkInfo) +{ + PSYSPOINT_ITEM pItem; + + if(pMarkInfo == NULL || strlen(pMarkInfo) == 0) + { + return -ERR_INPUT_PARAMS; + } + + if(g_SysPonitInfo.iMaxCacheSize <= 0) + { + return -ERR_UNSUPPORT; + } + + pItem = (PSYSPOINT_ITEM)malloc(sizeof(struct SYSPOINT_ITEM)); + + if(pItem == NULL) + { + return -ERR_MALLOC_MEMORY; + } + + pItem->pContent = strdup(pMarkInfo); + g_SysPonitInfo.lastMarkTime = time(NULL); + + uv_rwlock_wrlock(&g_SysPonitInfo.uvRwLock); + LL_APPEND(g_pSysPointArray, pItem); + uv_rwlock_wrunlock(&g_SysPonitInfo.uvRwLock); + + //LOG_EX(LOG_Debug, "SysMark: %s\n", pItem->pContent); + + return 0; +} + +int SysPointMarkUpload(void) +{ + int ret, size = 0; + char path[MAX_PATH]; + + memset(path, 0, MAX_PATH); + sprintf(path, "%s.txt", g_SysPonitInfo.savePath); + + if(access(path, F_OK) == 0) + { + unlink(path); + } + + GET_FILE_SIZE(g_SysPonitInfo.savePath, size); + + if(size <= 0) + { + LOG_EX(LOG_Debug, "Upload System Mark Data [%s] Is Empty, Skip......\n", g_SysPonitInfo.savePath); + return 0; + } + + rename(g_SysPonitInfo.savePath, path); + + fclose(g_SysPonitInfo.pMarkFile); + g_SysPonitInfo.pMarkFile = fopen(g_SysPonitInfo.savePath, "w+"); + + size = 0; + + do + { + ret = InetHttpUploadFileSync(GetCurServerAddr(MARK_POINT_MODULE), path, NULL); + sleep(1); + } while(ret != 0 && ++size < 3); + + LOG_EX(LOG_Debug, "Upload System Mark Data [%s] To Server [%s]\n", path, GetCurServerAddr(MARK_POINT_MODULE)); + + unlink(path); + + return 0; +} +