Init projects

This commit is contained in:
HuangXin 2018-07-05 10:19:12 +08:00
commit b83dc29e99
67 changed files with 26265 additions and 0 deletions

BIN
Example/global.db Normal file

Binary file not shown.

2039
Example/main.c Normal file

File diff suppressed because it is too large Load Diff

110
Framework/Compress/zlib.c Normal file
View File

@ -0,0 +1,110 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>
#include "crypto.h"
#define CHUNK_BLOCK (16384)
/* Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
version of the library linked do not match, or Z_ERRNO if there is
an error reading or writing the files. */
int GZipFileCompress(const char* pInput, const char* pOutput)
{
int ret, isFlush;
unsigned int have;
z_stream strm;
char strPath[256];
unsigned char in[CHUNK_BLOCK];
unsigned char out[CHUNK_BLOCK];
FILE *source, *dest;
if (pInput == NULL)
{
return (Z_ERRNO);
}
if(access(pInput, F_OK) != 0)
{
return (Z_ERRNO);
}
//fprintf(stdout, "in: %s\n", pInput);
source = fopen(pInput, "r+");
memset(strPath, 0, 256);
if (pOutput == NULL || strlen(pOutput) == 0)
{
sprintf(strPath, "%s.gz", pInput);
dest = fopen(strPath, "w+");
//fprintf(stdout, "out: %s\n", strPath);
}
else
{
dest = fopen(pOutput, "w+");
//fprintf(stdout, "out: %s\n", pOutput);
}
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
//ret = deflateInit(&strm, level);
ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, MAX_WBITS + 16, 8, Z_DEFAULT_STRATEGY);
if (ret != Z_OK)
{
fclose(source);
fclose(dest);
return ret;
}
/* compress until end of file */
do {
strm.avail_in = fread(in, 1, CHUNK_BLOCK, source);
if (ferror(source)) {
(void)deflateEnd(&strm);
fclose(source);
fclose(dest);
return Z_ERRNO;
}
isFlush = feof(source) ? Z_FINISH : Z_NO_FLUSH;
strm.next_in = in;
/* run deflate() on input until output buffer not full, finish
compression if all of source has been read in */
do {
strm.avail_out = CHUNK_BLOCK;
strm.next_out = out;
ret = deflate(&strm, isFlush); /* no bad return value */
have = CHUNK_BLOCK - strm.avail_out;
if (fwrite(out, 1, have, dest) != have || ferror(dest)) {
(void)deflateEnd(&strm);
fclose(source);
fclose(dest);
return Z_ERRNO;
}
} while (strm.avail_out == 0);
/* done when last data in file processed */
} while (isFlush != Z_FINISH);
/* clean up and return */
(void)deflateEnd(&strm);
fflush(dest);
fclose(source);
fclose(dest);
return Z_OK;
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,217 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/file.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <libconfig.h>
#include "log.h"
#include "libuv_dbus.h"
#include "server_addr.h"
#ifdef PLATFORM_R16
#define DEVICE_CFG_FILE ("/mnt/UDISK/dev.conf")
#else
#define DEVICE_CFG_FILE ("./dev.conf")
#endif
static config_t g_cfgInfo;
void InitCfgToCfgFile(config_t* pCfg)
{
config_setting_t *pRoot, *pSetting, *pGlobalgrp, *pLogGrp, *pSubGrp;
if(pCfg == NULL)
{
return;
}
pRoot = config_root_setting(pCfg);
pGlobalgrp = config_setting_add(pRoot, "Global", CONFIG_TYPE_GROUP);
pSetting = config_setting_add(pGlobalgrp, "ServerMode", CONFIG_TYPE_INT);
config_setting_set_int(pSetting, PUBLISH_MODE);
pLogGrp = config_setting_add(pGlobalgrp, "Log", CONFIG_TYPE_GROUP);
pSetting = config_setting_add(pLogGrp, "Enable", CONFIG_TYPE_BOOL);
config_setting_set_bool(pSetting, TRUE);
pSetting = config_setting_add(pLogGrp, "Level", CONFIG_TYPE_INT);
config_setting_set_format(pSetting, CONFIG_FORMAT_HEX);
config_setting_set_int(pSetting, 0x000003FF);
pSubGrp = config_setting_add(pLogGrp, "LogToEMail", CONFIG_TYPE_GROUP);
pSetting = config_setting_add(pSubGrp, "Enable", CONFIG_TYPE_BOOL);
config_setting_set_bool(pSetting, FALSE);
pSetting = config_setting_add(pSubGrp, "EMail", CONFIG_TYPE_STRING);
config_setting_set_string(pSetting, "pv1_es2@163.com");
pSetting = config_setting_add(pLogGrp, "LogToFile", CONFIG_TYPE_BOOL);
config_setting_set_bool(pSetting, TRUE);
pSetting = config_setting_add(pLogGrp, "LogToServer", CONFIG_TYPE_BOOL);
config_setting_set_bool(pSetting, TRUE);
pSubGrp = config_setting_add(pLogGrp, "LogToUDPServer", CONFIG_TYPE_GROUP);
pSetting = config_setting_add(pSubGrp, "Enable", CONFIG_TYPE_BOOL);
config_setting_set_bool(pSetting, FALSE);
pSetting = config_setting_add(pSubGrp, "UdpServerIp", CONFIG_TYPE_STRING);
config_setting_set_string(pSetting, "10.240.84.163");
pSetting = config_setting_add(pSubGrp, "UdpBasePort", CONFIG_TYPE_INT);
config_setting_set_int(pSetting, 10000);
if(!config_write_file(pCfg, DEVICE_CFG_FILE))
{
LOG_EX(LOG_Error, "Create Configure File %s Error\n", DEVICE_CFG_FILE);
}
}
int CfgGetIntValue(const char* pTags, int defValue)
{
int iValue = defValue;
if(pTags == NULL || strlen(pTags) == 0)
{
return defValue;
}
if(!config_lookup_int(&g_cfgInfo, pTags, &iValue))
{
return defValue;
}
return iValue;
}
void CfgSetIntValue(const char* pTags, int iValue)
{
config_setting_t *pRoot, *pGlobalgrp, *pSet;
LOG_EX(LOG_Debug, "Set: %s --> %d\n", pTags, iValue);
if(pTags == NULL || strlen(pTags) == 0)
{
LOG_EX(LOG_Error, "Input Params error: pTags = [%s]\n", pTags ? pTags : "NULL");
return;
}
pRoot = config_root_setting(&g_cfgInfo);
if(pRoot == NULL)
{
LOG_EX(LOG_Error, "pRoot = NULL\n");
return;
}
pGlobalgrp = config_setting_get_member(pRoot, "Global");
if(pGlobalgrp == NULL)
{
LOG_EX(LOG_Error, "pGlobalgrp = NULL\n");
return;
}
pSet = config_setting_get_member(pGlobalgrp, pTags);
if(!pSet)
{
pSet = config_setting_add(pGlobalgrp, pTags, CONFIG_TYPE_INT);
}
if(pSet == NULL)
{
LOG_EX(LOG_Error, "pSet = NULL\n");
return;
}
config_setting_set_int(pSet, iValue);
if(!config_write_file(&g_cfgInfo, DEVICE_CFG_FILE))
{
LOG_EX(LOG_Error, "Set %s Value Error\n", pTags);
}
}
char* CfgGetStringValue(const char* pTags, char* pDefValue)
{
char* pValue = pDefValue;
if(pTags == NULL || strlen(pTags) == 0)
{
return pDefValue;
}
if(!config_lookup_string(&g_cfgInfo, pTags, (const char**)&pValue))
{
return pDefValue;
}
return pValue;
}
double CfgGetFloatValue(const char* pTags, double defValue)
{
double dValue = defValue;
if(pTags == NULL || strlen(pTags) == 0)
{
return defValue;
}
if(!config_lookup_float(&g_cfgInfo, pTags, &dValue))
{
return defValue;
}
return dValue;
}
int CfgGetBoolValue(const char* pTags, int defValue)
{
int iValue = defValue;
if(pTags == NULL || strlen(pTags) == 0)
{
return defValue;
}
if(!config_lookup_bool(&g_cfgInfo, pTags, &iValue))
{
return defValue;
}
return iValue;
}
void CfgFileInit(void)
{
//config_setting_t *pRoot, *pSetting;
config_init(&g_cfgInfo);
#if 0
config_set_options(&g_cfgInfo,
(CONFIG_OPTION_SEMICOLON_SEPARATORS
| CONFIG_OPTION_COLON_ASSIGNMENT_FOR_GROUPS
| CONFIG_OPTION_OPEN_BRACE_ON_SEPARATE_LINE));
#endif
config_set_tab_width(&g_cfgInfo, 4);
if(access(DEVICE_CFG_FILE, F_OK) != 0)
{
InitCfgToCfgFile(&g_cfgInfo);
}
else if(!config_read_file(&g_cfgInfo, DEVICE_CFG_FILE))
{
LOG_EX(LOG_Error, "Read Configure File %s Error\n", DEVICE_CFG_FILE);
return;
}
}

104
Framework/Crypto/aes.c Normal file
View File

@ -0,0 +1,104 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "log.h"
#include "smart_sound.h"
#include "crypto.h"
#include "libuv_dbus.h"
int EvpAESEncrypto(unsigned char* pInBuf,
int iSize,
unsigned char* pOutBuf,
int* pOutSize,
unsigned char* pKey)
{
int enBytes = 0;
EVP_CIPHER_CTX ctx;
//int decDataLen = 0;
if(!pInBuf || !pOutBuf || !pOutSize || !pKey)
{
return -ERR_INPUT_PARAMS;
}
*pOutSize = 0;
//decDataLen = ((iSize + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE;
EVP_CIPHER_CTX_init(&ctx);
if(EVP_EncryptInit_ex(&ctx, EVP_aes_128_ecb(), NULL, pKey, NULL) == 0)
{
LOG_EX(LOG_Error, "EVP_EncryptInit_ex Error\n");
return -ERR_EVP_INIT_KEY;
}
if(EVP_EncryptUpdate(&ctx, pOutBuf, &enBytes, pInBuf, iSize) == 0)
{
LOG_EX(LOG_Error, "EVP_EncryptUpdate Error\n");
return -ERR_EVP_UPDATE;
}
pOutBuf += enBytes;
pInBuf += enBytes;
*pOutSize += enBytes;
if(EVP_EncryptFinal_ex(&ctx, pOutBuf, &enBytes) == 0)
{
LOG_EX(LOG_Error, "EVP_EncryptFinal_ex Error\n");
return -ERR_EVP_FINALE;
}
*pOutSize += enBytes;
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
int EvpAESDecrypto(unsigned char* pInBuf,
int iSize,
unsigned char* pOutBuf,
int* pOutSize,
unsigned char* pKey)
{
int deBytes = 0;
EVP_CIPHER_CTX ctx;
if(!pInBuf || !pOutBuf || !pOutSize || !pKey)
{
return -ERR_INPUT_PARAMS;
}
EVP_CIPHER_CTX_init(&ctx);
*pOutSize = 0;
if(EVP_DecryptInit_ex(&ctx, EVP_aes_128_ecb(), NULL, pKey, NULL) == 0)
{
LOG_EX(LOG_Error, "EVP_DecryptInit_ex Error\n");
return -ERR_EVP_INIT_KEY;
}
if(EVP_DecryptUpdate(&ctx, pOutBuf, &deBytes, pInBuf, iSize) == 0)
{
LOG_EX(LOG_Error, "EVP_EncryptUpdate Error\n");
return -ERR_EVP_UPDATE;
}
pOutBuf += deBytes;
pInBuf += deBytes;
*pOutSize += deBytes;
if(EVP_DecryptFinal_ex(&ctx, pOutBuf, &deBytes) == 0)
{
LOG_EX(LOG_Error, "EVP_EncryptFinal_ex Error\n");
return -ERR_EVP_FINALE;
}
*pOutSize += deBytes;
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}

158
Framework/Crypto/base64.c Normal file
View File

@ -0,0 +1,158 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "log.h"
#include "crypto.h"
const char* EvpBase64Encode(const char* pSrc)
{
EVP_ENCODE_CTX ctx;
int enSize = 0;
int sLen, size;
char* pEncode = NULL;
if(pSrc == NULL || strlen(pSrc) == 0)
{
return (NULL);
}
sLen = strlen(pSrc);
size = ((sLen / 3) * 4) + 4 + (sLen / 64) + sLen % 64;
pEncode = (char*)malloc(size);
memset(pEncode, 0, size);
EVP_EncodeInit(&ctx);
EVP_EncodeUpdate(&ctx, pEncode, &enSize, pSrc, strlen(pSrc));
EVP_EncodeFinal(&ctx, pEncode + enSize, &enSize);
// fprintf(stdout, "Src: \n[%s]\n", pSrc);
// fprintf(stdout, "Base64(%d --> %d | %d) Bytes: \n[%s]\n", sLen, size, strlen(pEncode), pEncode);
return pEncode;
}
const char* EvpBase64Decode(const char* pBase64)
{
EVP_ENCODE_CTX ctx;
int enSize = 0;
int size = 0;
char *pDecode = NULL;
if(pBase64 == NULL || strlen(pBase64) == 0)
{
return (NULL);
}
size = strlen(pBase64);
pDecode = (char*)malloc(size);
memset(pDecode, 0, size);
EVP_DecodeInit(&ctx);
EVP_DecodeUpdate(&ctx, pDecode, &enSize, pBase64, strlen(pBase64));
EVP_DecodeFinal(&ctx, pDecode + enSize, &enSize);
// fprintf(stdout, "Decode(%d --> %d) Bytes: \n[%s]\n", size, strlen(pDecode), pDecode);
return pDecode;
}
const char* EvpBase64EncodeNoAlign(const char* pSrc)
{
int size, sLen;
char* pEncode = NULL;
if(pSrc == NULL || strlen(pSrc) == 0)
{
return (NULL);
}
sLen = strlen(pSrc);
size = ((sLen / 3) * 4) + 4 + (sLen / 64) + sLen % 64;
pEncode = (char*)malloc(size);
memset(pEncode, 0, size);
EVP_EncodeBlock(pEncode, (const unsigned char *)pSrc, sLen);
// fprintf(stdout, "Src: \n[%s]\n", pSrc);
// fprintf(stdout, "Base64(%d --> %d | %d) Bytes: \n[%s]\n", sLen, size, strlen(pEncode), pEncode);
return pEncode;
}
const char* EvpBase64EncodeNoAlignV2(unsigned char* pSrc, int sLen)
{
int size;
char* pEncode = NULL;
if(pSrc == NULL || sLen <= 0)
{
return (NULL);
}
size = ((sLen / 3) * 4) + 4 + (sLen / 64) + sLen % 64;
pEncode = (char*)malloc(size);
memset(pEncode, 0, size);
EVP_EncodeBlock(pEncode, (const unsigned char *)pSrc, sLen);
// fprintf(stdout, "Src: \n[%s]\n", pSrc);
// fprintf(stdout, "Base64(%d --> %d | %d) Bytes: \n[%s]\n", sLen, size, strlen(pEncode), pEncode);
return pEncode;
}
const char* EvpBase64DecodeNoAlign(const char *pBase64)
{
int size = 0;
char *pDecode = NULL;
if(pBase64 == NULL || strlen(pBase64) == 0)
{
return (NULL);
}
size = strlen(pBase64);
pDecode = (char*)malloc(size);
memset(pDecode, 0, size);
//CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
EVP_DecodeBlock(pDecode, (const unsigned char *)pBase64, size);
//CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
// fprintf(stdout, "Decode(%d --> %d) Bytes: \n[%s]\n", size, strlen(pDecode), pDecode);
return pDecode;
}
unsigned char* EvpBase64DecodeNoAlignV2(const char *pBase64, int* pOutSize)
{
int size = 0;
unsigned char *pDecode = NULL;
if(pBase64 == NULL || strlen(pBase64) == 0)
{
return (NULL);
}
size = strlen(pBase64);
pDecode = (char*)malloc(size);
memset(pDecode, 0, size);
//CRYPTO_w_lock(CRYPTO_LOCK_DYNLOCK);
size = EVP_DecodeBlock(pDecode, (const unsigned char *)pBase64, size);
//CRYPTO_w_unlock(CRYPTO_LOCK_DYNLOCK);
// fprintf(stdout, "Decode(%d --> %d) Bytes: \n[%s]\n", size, strlen(pDecode), pDecode);
if(pOutSize)
{
*pOutSize = size;
}
return (pDecode);
}

187
Framework/Crypto/crypto.c Normal file
View File

@ -0,0 +1,187 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include "log.h"
#include "smart_sound.h"
#include "crypto.h"
#include "libuv_dbus.h"
static uv_mutex_t *pEvpMutex = NULL;
typedef struct
{
CRYPTO_TYPE type;
unsigned char* pInData;
int iInSize;
unsigned char* pOutData;
unsigned char pKey[EVP_MAX_KEY_LENGTH + 1];
OnEVPCrypto onEvpEventCb;
} CRYPT_TASK_PARAMS, *PCRYPT_TASK_PARAMS;
static void FreeEVPWorkCb(uv_work_t* pWork, int status)
{
PCRYPT_TASK_PARAMS pTask = (PCRYPT_TASK_PARAMS)pWork->data;
free(pTask->pInData);
free(pTask);
free(pWork);
}
static void OnEVPWorkCb(uv_work_t* pWork)
{
PCRYPT_TASK_PARAMS pTask = (PCRYPT_TASK_PARAMS)pWork->data;
int iOutSize = 0;
int iError = 0;
switch(pTask->type)
{
case CRYPTO_AES_ENCRYPT:
iError = EvpAESEncrypto(pTask->pInData,
pTask->iInSize,
pTask->pOutData,
&iOutSize,
pTask->pKey);
break;
case CRYPTO_AES_DECRYPT:
iError = EvpAESDecrypto(pTask->pInData,
pTask->iInSize,
pTask->pOutData,
&iOutSize,
pTask->pKey);
break;
case CRYPTO_BASE64_ENCODE:
pTask->pOutData = (unsigned char*)EvpBase64Encode((const char*)pTask->pInData);
iOutSize = strlen((char*)pTask->pOutData);
break;
case CRYPTO_BASE64_DECODE:
pTask->pOutData = (unsigned char*)EvpBase64Decode((const char*)pTask->pInData);
iOutSize = strlen((char*)pTask->pOutData);
break;
case CRYPTO_MD5_FILE:
pTask->pOutData = (unsigned char*)EvpMD5HashFile((const char*)pTask->pInData);
iOutSize = strlen((char*)pTask->pOutData);
break;
default:
iError = -ERR_UNSUP_EVP_TYPE;
}
if(iError != 0)
{
pTask->onEvpEventCb(pTask->type, pTask->pOutData, 0, pTask->pInData, iError);
}
else
{
pTask->onEvpEventCb(pTask->type, pTask->pOutData, iOutSize, pTask->pInData, 0);
}
}
int EvpAddCryptoTask(CRYPTO_TYPE type,
unsigned char* pInBuf,
int iSize,
unsigned char* pOutBuf,
char* pKey,
OnEVPCrypto onEvpCryptCb)
{
uv_work_t* puvWork = NULL;
PCRYPT_TASK_PARAMS pTask = NULL;
PLIBUV_DBUS_PARAMS pContext = DBusLibuvGetRuntime();
if(!pContext || !onEvpCryptCb)
{
return -ERR_INPUT_PARAMS;
}
if(type == CRYPTO_AES_ENCRYPT || type == CRYPTO_AES_DECRYPT)
{
if(pKey == NULL || pOutBuf == NULL)
{
return -ERR_INPUT_PARAMS;
}
switch(strlen(pKey) * 8)
{
case 128:
case 192:
case 256:
break;
default:
return -ERR_EVP_KEY_SIZE;
}
}
else if(type == CRYPTO_MD5_FILE)
{
uv_fs_t uvFs;
if(uv_fs_access(pContext->pLoop, &uvFs, (const char*)pInBuf, F_OK, NULL) != 0)
{
return -ERR_FILE_NOT_EXISTS;
}
}
pTask = (PCRYPT_TASK_PARAMS)malloc(sizeof(CRYPT_TASK_PARAMS));
puvWork = (uv_work_t*)malloc(sizeof(uv_work_t));
puvWork->data = (void*)pTask;
pTask->type = type;
pTask->pInData = (unsigned char*)malloc(iSize + 1);
pTask->iInSize = iSize;
pTask->pOutData = pOutBuf;
pTask->onEvpEventCb = onEvpCryptCb;
memset(pTask->pInData, 0, iSize + 1);
memset(pTask->pKey, 0, EVP_MAX_KEY_LENGTH + 1);
if(pKey)
{
strncpy(pTask->pKey, pKey, EVP_MAX_KEY_LENGTH);
}
memcpy(pTask->pInData, pInBuf, iSize);
uv_queue_work(pContext->pLoop, puvWork, OnEVPWorkCb, FreeEVPWorkCb);
return 0;
}
static void __evpLockCb(int mode, int n, const char *pFile, int line)
{
if(n >= CRYPTO_num_locks())
{
return;
}
if(mode & CRYPTO_LOCK)
{
uv_mutex_lock(&pEvpMutex[n]);
}
else
{
uv_mutex_unlock(&pEvpMutex[n]);
}
}
static unsigned long __evpIdCb(void)
{
return ((unsigned long)uv_thread_self());
}
void EvpSystemInit(void)
{
int i = 0;
pEvpMutex = (uv_mutex_t *)malloc(CRYPTO_num_locks() * sizeof(uv_mutex_t));
for(i = 0; i < CRYPTO_num_locks(); i++)
{
uv_mutex_init(&pEvpMutex[i]);
}
CRYPTO_set_id_callback(__evpIdCb);
CRYPTO_set_locking_callback(__evpLockCb);
}

156
Framework/Crypto/md5.c Normal file
View File

@ -0,0 +1,156 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <unistd.h>
#include "log.h"
#include "crypto.h"
#include "libuv_dbus.h"
const char* EvpMD5HashFile(const char* pFileName)
{
int rdSize = 0;
int fd, size;
uint8_t md5[EVP_MAX_MD_SIZE];
uint8_t buf[1024];
EVP_MD_CTX ctx;
char* pString = NULL;
memset(md5, 0, EVP_MAX_MD_SIZE);
EVP_MD_CTX_init(&ctx);
EVP_DigestInit_ex(&ctx, EVP_md5(), NULL);
fd = open(pFileName, O_RDONLY);
if(fd == -1)
{
LOG_EX(LOG_Error, "Open File \'%s\' error\n", pFileName);
return NULL;
}
do
{
rdSize = read(fd, buf, 1024);
if(rdSize > 0)
{
EVP_DigestUpdate(&ctx, buf, rdSize);
}
} while(rdSize > 0);
close(fd);
EVP_DigestFinal_ex(&ctx, md5, &rdSize);
EVP_MD_CTX_cleanup(&ctx);
size = rdSize * 2 + 1;
pString = (char*)malloc(size);
memset(pString, 0, size);
IHW_bin2hex(pString, md5, rdSize);
// print_hex_dump_bytes("MD5_", DUMP_PREFIX_ADDRESS, md5, rdSize);
// fprintf(stdout, "MD5: [%s]\n", pString);
return (const char*)pString;
}
int EvpMD5HashFileV2(const char* pFileName, unsigned char md5[16])
{
int rdSize = 0;
int fd;
uint8_t buf[1024];
EVP_MD_CTX ctx;
//char* pString = NULL;
memset(md5, 0, 16);
EVP_MD_CTX_init(&ctx);
EVP_DigestInit_ex(&ctx, EVP_md5(), NULL);
fd = open(pFileName, O_RDONLY);
if(fd == -1)
{
LOG_EX(LOG_Error, "Open File %s error\n", pFileName);
return (-ERR_OPEN_FILE);
}
do
{
rdSize = read(fd, buf, 1024);
EVP_DigestUpdate(&ctx, buf, rdSize);
} while(rdSize > 0);
close(fd);
EVP_DigestFinal_ex(&ctx, md5, &rdSize);
EVP_MD_CTX_cleanup(&ctx);
// print_hex_dump_bytes("MD5_", DUMP_PREFIX_ADDRESS, md5, rdSize);
// fprintf(stdout, "MD5: [%s]\n", pString);
return 0;
}
int EvpMD5HashBuf(const unsigned char* pBuf, int iBufLen, unsigned char* pOutBuf, int* pOutSize)
{
EVP_MD_CTX ctx;
if(pBuf == NULL || pOutBuf == NULL)
{
return (-ERR_INPUT_PARAMS);
}
memset(pOutBuf, 0, EVP_MAX_MD_SIZE);
EVP_MD_CTX_init(&ctx);
EVP_DigestInit_ex(&ctx, EVP_md5(), NULL);
EVP_DigestUpdate(&ctx, pBuf, iBufLen);
EVP_DigestFinal_ex(&ctx, pOutBuf, &iBufLen);
EVP_MD_CTX_cleanup(&ctx);
if(pOutSize)
{
*pOutSize = iBufLen;
}
//print_hex_dump_bytes("MD5_", DUMP_PREFIX_ADDRESS, pOutBuf, iBufLen);
return 0;
}
const char* EvpMD5HashBufV2(const unsigned char* pBuf, int iBufLen)
{
int size = 0;
EVP_MD_CTX ctx;
uint8_t md5[EVP_MAX_MD_SIZE];
char* pString = NULL;
if(pBuf == NULL || iBufLen <= 0)
{
return NULL;
}
memset(md5, 0, EVP_MAX_MD_SIZE);
EVP_MD_CTX_init(&ctx);
EVP_DigestInit_ex(&ctx, EVP_md5(), NULL);
EVP_DigestUpdate(&ctx, pBuf, iBufLen);
EVP_DigestFinal_ex(&ctx, md5, &iBufLen);
EVP_MD_CTX_cleanup(&ctx);
//print_hex_dump_bytes("MD5_", DUMP_PREFIX_ADDRESS, pOutBuf, iBufLen);
size = iBufLen * 2 + 1;
pString = (char*)malloc(size);
memset(pString, 0, size);
IHW_bin2hex(pString, md5, iBufLen);
// print_hex_dump_bytes("MD5_", DUMP_PREFIX_ADDRESS, md5, rdSize);
// fprintf(stdout, "MD5: [%s]\n", pString);
return (const char*)pString;
}

554
Framework/Fifo/fifo.c Normal file
View File

@ -0,0 +1,554 @@
/*
* A generic kernel FIFO implementation
*
* Copyright (C) 2009/2010 Stefani Seibold <stefani@seibold.net>
*
* 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 <linux/kernel.h>
#include <linux/export.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/log2.h>
#include <linux/uaccess.h>
#include <linux/kfifo.h>
#endif
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#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);
#ifdef PLATFORM_R16
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;
}

View File

@ -0,0 +1,197 @@
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include "log.h"
#include "libuv_dbus.h"
typedef struct
{
MODULE_NAME modName;
uint32_t hTm[MODULE_MAX];
int isDaemonWork[MODULE_MAX];
int isConnected[MODULE_MAX];
OnDaemonMsg pOnHeartLostCb;
} HEART_DAEMON, *PHEART_DAEMON;
uint32_t g_hblTout = HEART_LOST_DELAY; ///< nano second: heart lost timeout, default 1s
static uv_loop_t *g_DeamonLoop;
static uv_idle_t g_uvDeamonIdle;
static HEART_DAEMON g_heartDaemon;
static unsigned int g_Cnt = 0;
static int timerExpire(uint32_t tm, uint32_t tExp)
{
uint32_t now = LIBUV_CURRENT_TIME_MS();
int64_t diff = now - tm;
if(tm == 0 || tExp == 0)
{
return 0;
}
if(diff > tExp * 1000)
{
return 0;
}
else if(diff >= tExp)
{
return 1;
}
return (0);
}
static void RunPingSvr(void)
{
int ret = 0;
unsigned int tm = LIBUV_CURRENT_TIME_MS();
PING_MSG pMsg;
struct timeval tv;
gettimeofday(&tv, NULL);
pMsg.PING = (double)tm / 1000;
pMsg.tmSec = tv.tv_sec;
pMsg.tmMSec = tv.tv_usec;
ret = DBusJsonBoardcastCommand(NULL, 0xFFFFFFFF, CMD_MISC_PING, JSON_ENGINE_PING, &pMsg, FALSE);
if(ret != 0)
{
LOG_EX(LOG_Error, "DBus boardcast message error: %d\n", ret);
}
}
void HeartDaemonHblCheck(void)
{
if(g_heartDaemon.modName != MODULE_CONTROLLER)
{
if(g_heartDaemon.isDaemonWork[MODULE_CONTROLLER] && timerExpire(g_heartDaemon.hTm[MODULE_CONTROLLER], g_hblTout))
{
g_heartDaemon.pOnHeartLostCb(MODULE_CONTROLLER, TRUE);
g_heartDaemon.hTm[MODULE_CONTROLLER] = 0;
g_heartDaemon.isConnected[MODULE_CONTROLLER] = FALSE;
}
}
else
{
int i;
for(i = 0; i < MODULE_MAX; i++)
{
if(g_heartDaemon.isDaemonWork[i]
&& i != MODULE_CONTROLLER
&& timerExpire(g_heartDaemon.hTm[i], g_hblTout))
{
g_heartDaemon.pOnHeartLostCb(i, TRUE);
g_heartDaemon.hTm[i] = 0;
g_heartDaemon.isConnected[i] = FALSE;
}
}
}
}
void HeartDaemonUpgrade(int iWatcher)
{
if(iWatcher >= MODULE_MAX)
{
return;
}
if(g_heartDaemon.hTm[iWatcher] == 0)
{
if(g_heartDaemon.modName == MODULE_CONTROLLER)
{
g_heartDaemon.pOnHeartLostCb(iWatcher, FALSE);
}
else if(iWatcher == MODULE_CONTROLLER)
{
g_heartDaemon.pOnHeartLostCb(iWatcher, FALSE);
}
g_heartDaemon.isConnected[iWatcher] = TRUE;
RunPingSvr();
}
g_heartDaemon.hTm[iWatcher] = LIBUV_CURRENT_TIME_MS();
}
static int __isSendPingOnTime(void)
{
static unsigned int tmPre = 0;
unsigned int tm = LIBUV_CURRENT_TIME_MS();
unsigned int tmOut = HEART_SEND_DELAY;
if(g_heartDaemon.modName != MODULE_CONTROLLER
&& g_heartDaemon.isConnected[MODULE_CONTROLLER] == FALSE)
{
tmOut = 5000;
}
if(tmPre != 0 && tm - tmPre < tmOut)
{
return (FALSE);
}
tmPre = tm;
return (TRUE);
}
static void __uvIdleCb(uv_idle_t* phuvIdle)
{
if(DBusLibuvGetRuntime()->onHblCb
&& __isSendPingOnTime())
{
RunPingSvr();
}
HeartDaemonHblCheck();
sleep(1);
}
static void __uvThreadDaemon(void *pParams)
{
g_DeamonLoop = uv_loop_new();
uv_idle_init(g_DeamonLoop, &g_uvDeamonIdle);
uv_idle_start(&g_uvDeamonIdle, __uvIdleCb);
uv_run(g_DeamonLoop, UV_RUN_DEFAULT);
pthread_detach(pthread_self());
}
void HeartDaemonInit(MODULE_NAME mod, int msHblTout, OnDaemonMsg cb)
{
uv_thread_t uvDaemonThread;
int i;
memset(&g_heartDaemon, 0, sizeof(HEART_DAEMON));
if(msHblTout > 0)
{
g_hblTout = msHblTout;
}
g_heartDaemon.modName = mod;
for(i = 0; i < MODULE_MAX; i++)
{
if(mod == MODULE_CONTROLLER)
{
g_heartDaemon.isDaemonWork[i] = (g_pModInfoTable[i].modName != MODULE_CONTROLLER) ? TRUE : FALSE;
}
else
{
g_heartDaemon.isDaemonWork[i] = (g_pModInfoTable[i].modName == MODULE_CONTROLLER) ? TRUE : FALSE;
}
g_heartDaemon.isConnected[i] = FALSE;
}
g_heartDaemon.pOnHeartLostCb = cb;
uv_thread_create(&uvDaemonThread, __uvThreadDaemon, NULL);
}

File diff suppressed because it is too large Load Diff

347
Framework/Monitor/monitor.c Normal file
View File

@ -0,0 +1,347 @@
#ifdef ENABLE_COUNT_DEBUG
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <uv.h>
#include <dbus/dbus.h>
#include <errno.h>
#include <time.h>
#include <limits.h>
#include <sqlite3.h>
#include <uthash/uthash.h>
#include <uthash/utlist.h>
#include <uthash/utstring.h>
#include "log.h"
#include "libuv_dbus.h"
#define LOG_SAVE_TIME (1000)
typedef struct
{
long long maxValue;
long long minValue;
long long avgValue;
} STATISTICAL_VALUE, *PSTATISTICAL_VALUE;
typedef struct
{
long long curVaule;
long long tolValue;
unsigned int tolCount;
STATISTICAL_VALUE cVal;
} CSTATISTICAL_INFO, *PSTATISTICAL_INFO;
typedef struct
{
char* pMonName;
unsigned long nCount;
CSTATISTICAL_INFO nCstInfo;
uv_rwlock_t rwLock;
uv_timer_t logTimer;
unsigned int logTime;
UT_hash_handle hh; ///< UT Hash handle
} MONITOR_INFO, *PMONITOR_INFO;
static uv_rwlock_t g_uvMonRwLock;
static PMONITOR_INFO g_MonTbl = NULL;
static uv_loop_t* g_MonLogLoop = NULL;
static void __uvMonLogProc(void *pParams)
{
RunUVLoop(g_MonLogLoop);
while(TRUE)
{
usleep(1000);
}
pthread_detach(pthread_self());
}
static void __logMonTimerProc(uv_timer_t* pTimer)
{
PMONITOR_INFO pInfo = (PMONITOR_INFO)pTimer->data;
if(pInfo && (pInfo->nCount + pInfo->nCstInfo.tolCount > 0))
{
UT_string* pMsg = NULL;
utstring_new(pMsg);
uv_rwlock_rdlock(&pInfo->rwLock);
utstring_printf(pMsg, "%s Statistical Information:\n", pInfo->pMonName);
//LOG_EX(LOG_Debug, "%s Statistical Information:\n", pInfo->pMonName);
if(pInfo->nCount)
{
UT_string* pMsgCount = NULL;
utstring_new(pMsgCount);
utstring_printf(pMsgCount, " Total Count = %lu\n", pInfo->nCount);
utstring_concat(pMsg, pMsgCount);
utstring_free(pMsgCount);
//LOG_EX(LOG_Debug, " Total Count = %u\n", pInfo->nCount);
}
if(pInfo->nCstInfo.tolCount > 0)
{
UT_string* pMsgStat = NULL;
utstring_new(pMsgStat);
utstring_printf(pMsgStat, " Max Value = %lld\n"
" Min Value = %lld\n"
" Avg Value = %lld\n"
" ---- Statistical by total %lld of %u times\n",
pInfo->nCstInfo.cVal.maxValue,
pInfo->nCstInfo.cVal.minValue,
pInfo->nCstInfo.cVal.avgValue,
pInfo->nCstInfo.tolValue,
pInfo->nCstInfo.tolCount);
utstring_concat(pMsg, pMsgStat);
utstring_free(pMsgStat);
#if 0
LOG_EX(LOG_Debug, " Max Value = %lld\n", pInfo->nCstInfo.cVal.maxValue);
LOG_EX(LOG_Debug, " Min Value = %lld\n", pInfo->nCstInfo.cVal.minValue);
LOG_EX(LOG_Debug, " Avg Value = %lld\n", pInfo->nCstInfo.cVal.avgValue);
LOG_EX(LOG_Debug, " ---- Statistical by total %lld of %u times\n",
pInfo->nCstInfo.tolValue, pInfo->nCstInfo.tolCount);
#endif
}
LOG_EX(LOG_Debug, "%s", utstring_body(pMsg));
uv_rwlock_rdunlock(&pInfo->rwLock);
utstring_free(pMsg);
}
}
int MonitorInit(void)
{
uv_thread_t uvMonLogThread;
g_MonLogLoop = uv_loop_new();
uv_rwlock_init(&g_uvMonRwLock);
uv_thread_create(&uvMonLogThread, __uvMonLogProc, NULL);
return 0;
}
int MonAddNewItem(const char* pName, int logSaveTime)
{
PMONITOR_INFO pInfo;
if(pName == NULL || strlen(pName) == 0)
{
return -ERR_INPUT_PARAMS;
}
uv_rwlock_rdlock(&g_uvMonRwLock);
HASH_FIND_STR(g_MonTbl, pName, pInfo);
uv_rwlock_rdunlock(&g_uvMonRwLock);
if(pInfo != NULL)
{
return -ERR_CFG_ITEM_EXIST;
}
pInfo = (PMONITOR_INFO)malloc(sizeof(MONITOR_INFO));
if(pInfo == NULL)
{
return -ERR_MALLOC_MEMORY;
}
memset(pInfo, 0, sizeof(MONITOR_INFO));
pInfo->nCstInfo.cVal.minValue = INT_MAX;
pInfo->logTime = logSaveTime;
pInfo->pMonName = strdup(pName);
if(pInfo->logTime > 0)
{
pInfo->logTimer.data = pInfo;
uv_timer_init(g_MonLogLoop, &pInfo->logTimer);
uv_timer_start(&pInfo->logTimer, __logMonTimerProc, pInfo->logTime, pInfo->logTime);
}
else
{
pInfo->logTime = 0;
}
uv_rwlock_init(&pInfo->rwLock);
uv_rwlock_wrlock(&g_uvMonRwLock);
HASH_ADD_STR(g_MonTbl, pMonName, pInfo);
uv_rwlock_wrunlock(&g_uvMonRwLock);
return 0;
}
int MonIncreaseCount(const char* pName)
{
PMONITOR_INFO pInfo;
if(pName == NULL || strlen(pName) == 0)
{
return -ERR_INPUT_PARAMS;
}
uv_rwlock_rdlock(&g_uvMonRwLock);
HASH_FIND_STR(g_MonTbl, pName, pInfo);
uv_rwlock_rdunlock(&g_uvMonRwLock);
if(pInfo == NULL)
{
return -ERR_CFG_NOITEM;
}
uv_rwlock_wrlock(&pInfo->rwLock);
pInfo->nCount++;
uv_rwlock_wrunlock(&pInfo->rwLock);
return 0;
}
int MonDiffStatistical(const char* pName, long long newVal)
{
PMONITOR_INFO pInfo;
if(pName == NULL || strlen(pName) == 0)
{
return -ERR_INPUT_PARAMS;
}
uv_rwlock_rdlock(&g_uvMonRwLock);
HASH_FIND_STR(g_MonTbl, pName, pInfo);
uv_rwlock_rdunlock(&g_uvMonRwLock);
if(pInfo == NULL)
{
return -ERR_CFG_NOITEM;
}
uv_rwlock_wrlock(&pInfo->rwLock);
if(pInfo->nCstInfo.curVaule != 0)
{
long long diffValue = newVal - pInfo->nCstInfo.curVaule;
pInfo->nCstInfo.tolValue += diffValue;
pInfo->nCstInfo.tolCount++;
if(pInfo->nCstInfo.tolCount > 10)
{
pInfo->nCstInfo.cVal.avgValue = pInfo->nCstInfo.tolValue / pInfo->nCstInfo.tolCount;
if(pInfo->nCstInfo.cVal.maxValue < diffValue)
{
pInfo->nCstInfo.cVal.maxValue = diffValue;
}
if(pInfo->nCstInfo.cVal.minValue > diffValue)
{
pInfo->nCstInfo.cVal.minValue = diffValue;
}
}
}
pInfo->nCstInfo.curVaule = newVal;
uv_rwlock_wrunlock(&pInfo->rwLock);
//fprintf(stdout, "%s value %lld diffValue %lld\n", pName, newVal, diffValue);
return 0;
}
int MonUpgradeStatistical(const char* pName, long newVal)
{
PMONITOR_INFO pInfo;
if(pName == NULL || strlen(pName) == 0)
{
return -ERR_INPUT_PARAMS;
}
uv_rwlock_rdlock(&g_uvMonRwLock);
HASH_FIND_STR(g_MonTbl, pName, pInfo);
uv_rwlock_rdunlock(&g_uvMonRwLock);
if(pInfo == NULL)
{
return -ERR_CFG_NOITEM;
}
uv_rwlock_wrlock(&pInfo->rwLock);
pInfo->nCstInfo.curVaule = newVal;
pInfo->nCstInfo.tolValue += newVal;
pInfo->nCstInfo.tolCount++;
pInfo->nCstInfo.cVal.avgValue = pInfo->nCstInfo.tolValue / pInfo->nCstInfo.tolCount;
if(pInfo->nCstInfo.cVal.maxValue < newVal)
{
pInfo->nCstInfo.cVal.maxValue = newVal;
}
if(pInfo->nCstInfo.cVal.minValue > newVal)
{
pInfo->nCstInfo.cVal.minValue = newVal;
}
uv_rwlock_wrunlock(&pInfo->rwLock);
//fprintf(stdout, "%s value %ld\n", pName, newVal);
return 0;
}
int MonItemLogout(const char* pName)
{
PMONITOR_INFO pInfo;
if(pName == NULL || strlen(pName) == 0)
{
return -ERR_INPUT_PARAMS;
}
uv_rwlock_rdlock(&g_uvMonRwLock);
HASH_FIND_STR(g_MonTbl, pName, pInfo);
uv_rwlock_rdunlock(&g_uvMonRwLock);
if(pInfo == NULL)
{
return -ERR_CFG_NOITEM;
}
if(pInfo->nCount + pInfo->nCstInfo.tolCount == 0)
{
LOG_EX(LOG_Debug, "%s Statistical Unchanged\n", pInfo->pMonName);
return 0;
}
uv_rwlock_rdlock(&pInfo->rwLock);
LOG_EX(LOG_Debug, "%s Statistical Information:\n", pInfo->pMonName);
if(pInfo->nCount)
{
LOG_EX(LOG_Debug, " Total Count = %u\n", pInfo->nCount);
}
if(pInfo->nCstInfo.tolCount > 0)
{
LOG_EX(LOG_Debug, " Max Value = %lld\n", pInfo->nCstInfo.cVal.maxValue);
LOG_EX(LOG_Debug, " Min Value = %lld\n", pInfo->nCstInfo.cVal.minValue);
LOG_EX(LOG_Debug, " Avg Value = %lld\n", pInfo->nCstInfo.cVal.avgValue);
LOG_EX(LOG_Debug, " ---- Statistical by total %lld of %u times\n",
pInfo->nCstInfo.tolValue, pInfo->nCstInfo.tolCount);
}
uv_rwlock_rdunlock(&pInfo->rwLock);
return 0;
}
#endif

1396
Framework/Network/inet_api.c Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,320 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/file.h>
#include <unistd.h>
#include <errno.h>
#include <sqlite3.h>
#include <uthash/utstring.h>
#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;
}
}

1442
Framework/Skins/skins.c Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,224 @@
#include "server_addr.h"
#include "log.h"
#include "config_engine.h"
#include "libuv_dbus.h"
const char* g_ServerModuleStr[] =
{
"YUNXIN_MODULE",
"VOICE_MODULE",
"VOICE_AI_MODULE",
"SERVER_MODULE",
"LOG_MODULE",
"MARK_POINT_MODULE",
"TTS_MODULE",
"DC_MODULE",
"UNKNOWN_MODULE"
};
const char* g_ServerModeStr[] =
{
"DEV_MODE",
"TEST_MODE",
"PUBLISH_MODE",
"UNKNOWN_MODE"
};
const char* g_KeyMapStr[] =
{
"VOICE_APP_KEY",
"VOICE_APP_SECRET",
"UNKNOWN_KEYMAP"
};
const char* SvrModuleStr(SERVER_MODULE_TYPE module)
{
return g_ServerModuleStr[module];
}
const char* SvrModeStr(SERVER_MODE_TYPE mode)
{
return g_ServerModeStr[mode];
}
const char* g_VoiceKeyMap[VOICE_MAX][MAX_MODE] = {
{ // VOICE_APP_KEY
"vbox-dev",
"vbox-dev",
"vbox-online",
},
{ // VOICE_APP_SECRET
"b1ec33c03df80ea3035bc9ccaa4af09c",
"b1ec33c03df80ea3035bc9ccaa4af09c",
"8714d6de1c83f21dda5fc9a905a59ac1",
},
};
const char* g_ServerAddr[MAX_MODULE][MAX_MODE] = {
{ // YUNXIN_MODULE
"2e37bc56a9b7ec3f6b8f41f60b81eb92",
"2e37bc56a9b7ec3f6b8f41f60b81eb92",
"dbb00213c23ea3709aae12ceb4c4e54e",
},
{ // VOICE_MODULE
"ws://vbox-test.netease.com/netty/websocket",
"ws://vbox-test.netease.com/netty3/websocket",
"wss://vbox-asr.3.163.com/websocket",
},
{ // VOICE_AI_MODULE
"http://api.multimedia.netease.com/imgtest/yqbot31_8686/",
"http://api.multimedia.netease.com/imgtest/yqbot29_8686/",
"https://vbox-smart.3.163.com/ ",
},
{ // SERVER_MODULE
"http://api.multimedia.netease.com/imgtest/yqbot27_7677/",
"http://api.multimedia.netease.com/imgtest/yqbot31_7676/",
"https://vbox-server.3.163.com/",
},
{ // LOG_MODULE
"http://vbox-log-test.netease.com/logCollectDev/vbox/logCollect/uploadLog",
"http://vbox-log-test.netease.com/logCollect/vbox/logCollect/uploadLog",
"https://vbox-log.3.163.com/vbox/logCollect/uploadLog",
},
{ // MARK_POINT_MODULE
"http://vbox-log-test.netease.com/buriedDev/vbox/log/add",
"http://vbox-log-test.netease.com/buriedTest/vbox/log/add",
"https://vbox-log.3.163.com/vbox/log/add",
},
{ // TTS_MODULE
"http://api.openai.netease.com/vbox-tts-dev/vbox/tts/transform",
"http://api.openai.netease.com/vbox-tts-test/vbox/tts/transform",
"https://vbox-tts.3.163.com/vbox/tts/transform",
},
{ // DC_MODULE
"http://api.multimedia.netease.com/imgtest/yqbot27_7677/vbox/uploadFile",
"http://api.multimedia.netease.com/imgtest/yqbot31_7676/vbox/uploadFile",
"https://vbox-server.3.163.com/vbox/uploadFile",
},
};
static unsigned int g_SvrMode = PUBLISH_MODE;
void DumpCurServerAddr(const char* pTags)
{
if(pTags && strlen(pTags) > 0)
{
LOG_EX2(LOG_Info, "%s\t Current Server Mode: %s\n", pTags, SvrModeStr(g_SvrMode));
}
else
{
LOG_EX2(LOG_Info, "Current Server Mode: %s\n", SvrModeStr(g_SvrMode));
}
#if 0
LOG_EX2(LOG_Info, "Voice Key = [%s], Secret = [%s]\n",
GetCurVoiceKeyValue(VOICE_APP_KEY), GetCurVoiceKeyValue(VOICE_APP_SECRET));
LOG_EX2(LOG_Info, "--------------------------------------------------------"
"----------------------------------------------\n");
LOG_EX2(LOG_Info, "| Module | "
"Server URL |\n");
LOG_EX2(LOG_Info, "--------------------------------------------------------"
"----------------------------------------------\n");
for(int i = 0; i < MAX_MODULE; i++)
{
LOG_EX2(LOG_Info, "| %-17s | %-78s |\n", SvrModuleStr(i), GetCurServerAddr(i));
}
LOG_EX2(LOG_Info, "--------------------------------------------------------"
"----------------------------------------------\n");
#endif
}
SERVER_MODE_TYPE GetCurrentServerMode(void)
{
return g_SvrMode;
}
void SetCurrentServerMode(SERVER_MODE_TYPE mode)
{
if(mode >= 0 && mode < MAX_MODE)
{
if(g_SvrMode != mode)
{
LOG_EX(LOG_Debug, "Change server mode from %s(%d) to %s(%d)\n",
g_ServerModeStr[g_SvrMode], g_SvrMode, g_ServerModeStr[mode], mode);
g_SvrMode = mode;
CfgSetIntValue("ServerMode", mode);
}
else
{
LOG_EX(LOG_Warn, "Current mode is %s(%d) yet\n", g_ServerModeStr[mode], mode);
}
}
else
{
LOG_EX(LOG_Error, "Unknown Mode: %d, current mode: %s(%d)\n",
mode, g_ServerModeStr[g_SvrMode], g_SvrMode);
}
}
char* GetCurServerAddr(SERVER_MODULE_TYPE module)
{
if(module >= 0 && module < MAX_MODULE)
{
return (char*)g_ServerAddr[module][g_SvrMode];
}
else
{
LOG_EX(LOG_Error, "Unknown Module: %s(%d)\n", g_ServerModuleStr[module], module);
return "";
}
}
char* GetCurVoiceKeyValue(VOICE_KEYMAP_TYPE keyMap)
{
if(keyMap >= 0 && keyMap < VOICE_MAX)
{
return (char*)g_VoiceKeyMap[keyMap][g_SvrMode];
}
else
{
LOG_EX(LOG_Error, "Unknown KeyMap Type: %s(%d)\n", g_KeyMapStr[keyMap], keyMap);
return "";
}
}
static PDBUS_MSG_PACK __dusOnMsg(uv_loop_t* pLoop, DBusConnection* pConn, PDBUS_MSG_PACK pMsg)
{
return NULL;
}
static void uvLoopProc(void *pParams)
{
RunUVLoop(GetDBusDefaultLoop());
pthread_detach(pthread_self());
}
void ServerManagerInit(void)
{
int ret = 0;
uv_thread_t uvThread;
LOG_EX(LOG_Warn, "+++++++++++++++++++++++System Uninit\n");
DBusConnection* pBus = DBusWithLibuvInit(GetDBusDefaultLoop(),
g_pModInfoTable[MODULE_SKINS].modAliase,
__dusOnMsg,
NULL,
NULL, //KeyEventCb,
&ret);
if(pBus == NULL)
{
LOG_EX(LOG_Error, "DBusWithLibuvInit Error: %d\n", ret);
return;
}
uv_thread_create(&uvThread, uvLoopProc, NULL);
}

769
Framework/Timer/timer.c Normal file
View File

@ -0,0 +1,769 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <uv.h>
#include <dbus/dbus.h>
#include <errno.h>
#include <time.h>
#include <uthash/uthash.h>
#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(&timestamp, &setTime);
switch(pInfo->repeatMode)
{
case REPEAT_MODE_EVERY_DAY:
localtime_r(&timestamp, &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(&timestamp, &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(&timestamp, &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(&timestamp, &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(&timestamp, &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(&timestamp, &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:
case REPEAT_MODE_EVERY_YEAR_DAY:
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(&timestamp, &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(&timestamp, &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(&timestamp, &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(&timestamp, &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(&timestamp, &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(&timestamp, &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);
}

View File

@ -0,0 +1,93 @@
pv1_log_proto = Proto("PV1_Log", "PV1 ES2 Log Protocol")
log_level_str =
{
[ 1 ] = "[F]",
[ 2 ] = "[E]",
[ 4 ] = "[W]",
[ 8 ] = "[D]",
[ 16 ] = "[I]",
[ 32 ] = "[T]",
[ 64 ] = "[I]",
[ 128 ] = "[V]",
[ 256 ] = "[S]",
[ 512 ] = "[U]",
[ 0xFFFFFFFF ] = "[A]",
}
local log_content = ProtoField.string("logContent", "Message:\t")
local log_Seq = ProtoField.uint16("logSeq", "Sequence: \t", base.DEC)
local log_pid = ProtoField.uint32("logPid", "PID: \t\t", base.DEC)
local log_datetime = ProtoField.string("logDateTime", "DateTime:\t\t")
local log_time = ProtoField.string("logTime", "Date:\t\t")
local log_level = ProtoField.uint32("logLevel", "Level: \t\t", base.DEC, log_level_str)
pv1_log_proto.fields = {
log_Seq, log_content, log_pid, log_datetime, log_level
}
function pv1_log_proto.dissector(buffer, pinfo, tree)
pinfo.cols.protocol:set("LOG")
local offset = 0
local buf_len = buffer:len()
local logInfoTree = tree:add(pv1_log_proto, buffer(0, 18), "Log Message Information")
logInfoTree:add(log_Seq, buffer(offset, 2))
offset = offset + 2
local l_pid = buffer(offset, 4):uint()
logInfoTree:add(log_pid, buffer(offset, 4))
offset = offset + 4
local l_second = buffer(offset, 4):uint()
offset = offset + 4
local l_nsecond = buffer(offset, 4):uint()
offset = offset + 4
logInfoTree:add(log_datetime, "[" .. os.date("%c", l_second) .. "." .. string.format("%03d", l_nsecond / 1000) .. "]")
local l_level = buffer(offset, 4):uint()
local l_lvStr
if l_level == 1 then
l_lvStr = "F"
elseif l_level == 2 then
l_lvStr = "E"
elseif l_level == 4 then
l_lvStr = "W"
elseif l_level == 8 then
l_lvStr = "D"
elseif l_level == 16 then
l_lvStr = "I"
elseif l_level == 32 then
l_lvStr = "T"
elseif l_level == 64 then
l_lvStr = "C"
elseif l_level == 128 then
l_lvStr = "V"
elseif l_level == 256 then
l_lvStr = "S"
elseif l_level == 0xFFFFFFFF then
l_lvStr = "A"
else
l_lvStr = "U"
end
logInfoTree:add(log_level, buffer(offset, 4))
offset = offset + 4
local logInfo = buffer(offset, buf_len - 19):string()
local logMsgTree = tree:add(pv1_log_proto, buffer(18, buf_len - 18), "Log Message Content")
logMsgTree:add(log_content, logInfo)
if buffer(buf_len - 1, 1):string() == '\n' then
pinfo.cols.info:set("{" .. tostring(l_pid) .. "} [" .. os.date("%X", l_second) .. "." .. string.format("%03d", l_nsecond / 1000) .. "] [" .. tostring(l_lvStr) .. "] " .. buffer(18, buf_len - 19):string())
else
pinfo.cols.info:set("{" .. tostring(l_pid) .. "} [" .. os.date("%X", l_second) .. "." .. string.format("%03d", l_nsecond / 1000) .. "] [" .. tostring(l_lvStr) .. "] " .. buffer(18, buf_len - 18):string())
end
end
local pv1_log_udp_port_table = DissectorTable.get("udp.port")
--local pv1_log_port = 10000
pv1_log_udp_port_table:add("10000-10020", pv1_log_proto)

File diff suppressed because it is too large Load Diff

90
Makefile Normal file
View File

@ -0,0 +1,90 @@
SHELL := /bin/sh
DIS_BUILD_WARRING ?= FALSE
EN_MAKE_MSG ?= TRUE
ifeq ($(EN_MAKE_MSG), TRUE)
MAKE_FLAGS :=
else
MAKE_FLAGS := -s
endif
ifneq ($(OPT), clean)
ifneq ($(OPT), install)
MAKE_FLAGS += -j$(shell cat /proc/cpuinfo | grep processor | wc -l)
endif
endif
ifeq ($(DIR), )
DEMO_INS_PATH := ./release
else
DEMO_INS_PATH := $(DIR)
endif
.PHONY : uvdbus example cfgserver alarm ota voice logctrl
all: uvdbus example alarm ota logctrl
uvdbus:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.lib.cross cleanall MAKE_TARGET=uvdbus
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.lib.cross install DIR=$(DIR) MAKE_TARGET=uvdbus
else
@make all $(MAKE_FLAGS) -C build -f Makefile.lib.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=uvdbus
endif
example:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.app.cross cleanall MAKE_TARGET=example
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.app.cross install DIR=$(DIR) MAKE_TARGET=example
else
@make all $(MAKE_FLAGS) -C build -f Makefile.app.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=example
endif
cfgserver:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.cfgsvr.cross cleanall MAKE_TARGET=cfgserver
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.cfgsvr.cross install DIR=$(DIR) MAKE_TARGET=cfgserver
else
@make all $(MAKE_FLAGS) -C build -f Makefile.cfgsvr.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=cfgserver
endif
alarm:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.alarm.cross cleanall MAKE_TARGET=alarm
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.alarm.cross install DIR=$(DIR) MAKE_TARGET=alarm
else
@make all $(MAKE_FLAGS) -C build -f Makefile.alarm.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=alarm
endif
ota:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.ota.cross cleanall MAKE_TARGET=ota
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.ota.cross install DIR=$(DIR) MAKE_TARGET=ota
else
@make all $(MAKE_FLAGS) -C build -f Makefile.ota.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=ota
endif
voice:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.voice.cross cleanall MAKE_TARGET=voice
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.voice.cross install DIR=$(DIR) MAKE_TARGET=voice
else
@make all $(MAKE_FLAGS) -C build -f Makefile.voice.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=voice
endif
logctrl:
ifeq ($(OPT), clean)
@make $(MAKE_FLAGS) -C build -f Makefile.logctrl.cross cleanall MAKE_TARGET=logctrl
else ifeq ($(OPT), install)
@make $(MAKE_FLAGS) -C build -f Makefile.logctrl.cross install DIR=$(DIR) MAKE_TARGET=logctrl
else
@make all $(MAKE_FLAGS) -C build -f Makefile.logctrl.cross DISABLE_WARRING=$(DIS_BUILD_WARRING) MAKE_TARGET=logctrl
endif

789
Modules/Alarm/assistant.c Normal file
View File

@ -0,0 +1,789 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <uv.h>
#include <dbus/dbus.h>
#include <errno.h>
#include <time.h>
#include <uthash/utlist.h>
#if defined(PLATFORM_R16) || defined (PLATFORM_CPU)
#include "log.h"
#include "libuv_dbus.h"
#include "crypto.h"
#include "json_struct.h"
#include "config_engine.h"
#include "assistant.h"
#else
#include <uvdbus/log.h>
#include <uvdbus/libuv_dbus.h>
#include <uvdbus/crypto.h>
#include <uvdbus/json_struct.h>
#include <uvdbus/config_engine.h>
#include <uvdbus/assistant.h>
#endif
#define SYNC_TIME_DELAY (5)
static PASSISTANT_ARRAY_INFO g_pAlarmArray = NULL,
g_pRemaindArray = NULL,
g_pSessionArray = NULL;
static uv_rwlock_t g_uvListRwLock;
static unsigned char g_syncFlags;
static unsigned int g_sessionId = 0;
static void __onAlarmCb(unsigned int tmId, unsigned int status, void *pUserData);
static int __getTimerPriorty(ASSISTANT_TYPE itemType)
{
switch(itemType)
{
case ASSISTANT_TYPE_CLOCK:
return (2);
case ASSISTANT_TYPE_REMAIND:
return (3);
case ASSISTANT_TYPE_SESSION:
return (1);
}
return (0);
}
static void __addTaskToTimer(PASSISTANT_ARRAY_INFO pItem)
{
int ret = 0;
unsigned int alarmId;
pItem->alarmItem.second = 0;
alarmId = AlarmTimerAdd(pItem->alarmItem.year,
pItem->alarmItem.month,
pItem->alarmItem.day,
pItem->alarmItem.hour,
pItem->alarmItem.minute,
pItem->alarmItem.second,
pItem->alarmItem.weekDay,
pItem->alarmItem.repeatMode,
__onAlarmCb,
__getTimerPriorty(pItem->alarmItem.itemType),
&pItem->alarmItem,
&ret);
if(alarmId != 0xFFFFFFFF && ret == 0)
{
pItem->alarmItem.timerId = alarmId;
}
else
{
pItem->alarmItem.timerId = 0xFFFFFFFF;
}
}
static int __assistantRspStatus(int cmd, int val)
{
int ret = 0;
ASSISTANT_RSP_STATUS oStatus;
memset(&oStatus, 0, sizeof(ASSISTANT_RSP_STATUS));
oStatus.cmd = cmd;
oStatus.val = val;
ret = DBusJsonSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ASSISTANT_STATUS,
JSON_ENGINE_ASSISTANT_STATUS,
&oStatus, TRUE);
return (ret);
}
static int __assistantRunningEvent(PASSISTANT_ITEM_INFO pInfo)
{
int ret = 0;
ret = DBusJsonSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ASSISTANT_RUNNING,
JSON_ENGINE_ASSISTANT_RUNNING,
pInfo, FALSE);
return (ret);
}
static int __assistantNotifyChange(int cmdNotify, int nItems, ASSISTANT_TYPE nType, PASSISTANT_ITEM_INFO pInfo)
{
int ret = 0;
ASSISTANT_NOTIFY_INFO notifyInfo;
memset(&notifyInfo, 0, sizeof(ASSISTANT_NOTIFY_INFO));
notifyInfo.type = nType;
notifyInfo.cmd = cmdNotify;
if(pInfo)
{
notifyInfo.nItems = nItems;
for(int i = 0; i < nItems; i++)
{
notifyInfo.ids[i] = pInfo[i].itemId;
}
}
ret = DBusJsonSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ASSISTANT_NOTIFY,
JSON_ENGINE_ASSISTANT_NOTIFY,
&notifyInfo, TRUE);
return (ret);
}
static int __assistantArrayNotifyChange(int cmdNotify, int nItems, ASSISTANT_TYPE nType, unsigned long long* pArray)
{
int ret = 0;
ASSISTANT_NOTIFY_INFO notifyInfo;
memset(&notifyInfo, 0, sizeof(ASSISTANT_NOTIFY_INFO));
notifyInfo.type = nType;
notifyInfo.cmd = cmdNotify;
if(pArray)
{
notifyInfo.nItems = nItems;
for(int i = 0; i < nItems; i++)
{
notifyInfo.ids[i] = pArray[i];
}
}
ret = DBusJsonSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ASSISTANT_NOTIFY,
JSON_ENGINE_ASSISTANT_NOTIFY,
&notifyInfo, TRUE);
return (ret);
}
static void __cleanupAlarmArray(void)
{
PASSISTANT_ARRAY_INFO pItem = NULL, pTmp = NULL;
uv_rwlock_wrlock(&g_uvListRwLock);
DL_FOREACH_SAFE(g_pAlarmArray, pItem, pTmp)
{
AlarmTimerRemove(pItem->alarmItem.timerId);
DL_DELETE(g_pAlarmArray, pItem);
free(pItem);
}
uv_rwlock_wrunlock(&g_uvListRwLock);
}
static void __cleanupRemaindArray(void)
{
PASSISTANT_ARRAY_INFO pItem = NULL, pTmp = NULL;
uv_rwlock_wrlock(&g_uvListRwLock);
DL_FOREACH_SAFE(g_pRemaindArray, pItem, pTmp)
{
AlarmTimerRemove(pItem->alarmItem.timerId);
DL_DELETE(g_pRemaindArray, pItem);
free(pItem);
}
uv_rwlock_wrunlock(&g_uvListRwLock);
}
static void __cleanupSessionArray(void)
{
PASSISTANT_ARRAY_INFO pItem = NULL, pTmp = NULL;
uv_rwlock_wrlock(&g_uvListRwLock);
DL_FOREACH_SAFE(g_pSessionArray, pItem, pTmp)
{
AlarmTimerRemove(pItem->alarmItem.timerId);
DL_DELETE(g_pSessionArray, pItem);
free(pItem);
}
uv_rwlock_wrunlock(&g_uvListRwLock);
}
static int __addNewItems(PASSISTANT_SYNC_INFO pInfo)
{
struct tm localTime;
time_t loclStamp, tmStamp = time((time_t*)NULL);
localtime_r(&tmStamp, &localTime);
loclStamp = mktime(&localTime);
for(int i = 0; i < pInfo->nItems; i++)
{
PASSISTANT_ARRAY_INFO pItem = (PASSISTANT_ARRAY_INFO)malloc(sizeof(struct ASSISTANT_ARRAY_INFO));
if(pItem == NULL)
{
LOG_EX(LOG_Error, "Malloc Memory Error\n");
return (-ERR_MALLOC_MEMORY);
}
memset(pItem, 0, sizeof(struct ASSISTANT_ARRAY_INFO));
strcpy(pItem->alarmItem.strTips, pInfo->pAlarmInfo[i].strTips);
strcpy(pItem->alarmItem.resUrl, pInfo->pAlarmInfo[i].resUrl);
strcpy(pItem->alarmItem.voiceRes, pInfo->pAlarmInfo[i].voiceRes);
strcpy(pItem->alarmItem.voiceResType, pInfo->pAlarmInfo[i].voiceResType);
pItem->alarmItem.itemType = pInfo->pAlarmInfo[i].itemType;
pItem->alarmItem.repeatMode = pInfo->pAlarmInfo[i].repeatMode;
pItem->alarmItem.voiceId = pInfo->pAlarmInfo[i].voiceId;
pItem->alarmItem.year = pInfo->pAlarmInfo[i].year;
pItem->alarmItem.month = pInfo->pAlarmInfo[i].month;
pItem->alarmItem.day = pInfo->pAlarmInfo[i].day;
pItem->alarmItem.hour = pInfo->pAlarmInfo[i].hour;
pItem->alarmItem.minute = pInfo->pAlarmInfo[i].minute;
pItem->alarmItem.second = pInfo->pAlarmInfo[i].second;
pItem->alarmItem.weekDay = pInfo->pAlarmInfo[i].weekDay;
if(ASSISTANT_TYPE_SESSION == pItem->alarmItem.itemType)
{
pItem->alarmItem.itemId = g_sessionId++;
}
else
{
pItem->alarmItem.itemId = pInfo->pAlarmInfo[i].itemId;
}
if(pItem->alarmItem.repeatMode == REPEAT_MODE_NONE)
{
struct tm setTime;
time_t onTimeStamp;
int tmDiff;
setTime.tm_year = pItem->alarmItem.year;
setTime.tm_mon = pItem->alarmItem.month;
setTime.tm_mday = pItem->alarmItem.day;
setTime.tm_hour = pItem->alarmItem.hour;
setTime.tm_min = pItem->alarmItem.minute;
setTime.tm_sec = pItem->alarmItem.second;
onTimeStamp = mktime(&setTime);
tmDiff = (int)difftime(loclStamp, onTimeStamp);
if(tmDiff >= 3)
{
LOG_EX(LOG_Warn, "%llu: Was Expired %d!!!!!!\n", pItem->alarmItem.itemId, tmDiff);
continue;
}
}
uv_rwlock_wrlock(&g_uvListRwLock);
if(ASSISTANT_TYPE_CLOCK == pItem->alarmItem.itemType)
{
DL_APPEND(g_pAlarmArray, pItem);
}
else if(ASSISTANT_TYPE_REMAIND == pItem->alarmItem.itemType)
{
DL_APPEND(g_pRemaindArray, pItem);
}
else if(ASSISTANT_TYPE_SESSION == pItem->alarmItem.itemType)
{
DL_APPEND(g_pSessionArray, pItem);
}
else
{
LOG_EX(LOG_Error, "Unknown Type: %d\n", pItem->alarmItem.itemType);
}
uv_rwlock_wrunlock(&g_uvListRwLock);
__addTaskToTimer(pItem);
}
return (0);
}
static void __removeAlarmItem(PASSISTANT_NOTIFY_INFO pRemove)
{
PASSISTANT_ARRAY_INFO pItem = NULL, pTmp = NULL;
for(int i = 0; i < pRemove->nItems; i++)
{
uv_rwlock_wrlock(&g_uvListRwLock);
DL_FOREACH_SAFE(g_pAlarmArray, pItem, pTmp)
{
if(pItem->alarmItem.itemId == pRemove->ids[i]
&& pItem->alarmItem.itemType == pRemove->type)
{
AlarmTimerRemove(pItem->alarmItem.timerId);
DL_DELETE(g_pAlarmArray, pItem);
free(pItem);
}
}
uv_rwlock_wrunlock(&g_uvListRwLock);
}
}
static void __removeRemaindItem(PASSISTANT_NOTIFY_INFO pRemove)
{
PASSISTANT_ARRAY_INFO pItem = NULL, pTmp = NULL;
for(int i = 0; i < pRemove->nItems; i++)
{
uv_rwlock_wrlock(&g_uvListRwLock);
DL_FOREACH_SAFE(g_pRemaindArray, pItem, pTmp)
{
if(pItem->alarmItem.itemId == pRemove->ids[i]
&& pItem->alarmItem.itemType == pRemove->type)
{
AlarmTimerRemove(pItem->alarmItem.timerId);
DL_DELETE(g_pRemaindArray, pItem);
free(pItem);
}
}
uv_rwlock_wrunlock(&g_uvListRwLock);
}
}
static int __alarmItemCmp(PASSISTANT_ARRAY_INFO pSrc, PASSISTANT_ARRAY_INFO pDst)
{
#if 0
fprintf(stdout, "id: %llu --> %llu, type: %u --> %u\n",
pSrc->alarmItem.itemId, pDst->alarmItem.itemId,
pSrc->alarmItem.itemType, pDst->alarmItem.itemType);
#endif
if(pSrc->alarmItem.itemId == pDst->alarmItem.itemId
&& pSrc->alarmItem.itemType == pDst->alarmItem.itemType)
{
return (0);
}
else
{
return (1);
}
}
static void __onAlarmCb(unsigned int tmId, unsigned int status, void *pUserData)
{
PASSISTANT_ITEM_INFO pAlarm = (PASSISTANT_ITEM_INFO)pUserData;
PASSISTANT_ARRAY_INFO pItem = NULL;
struct ASSISTANT_ARRAY_INFO tmpItem;
struct tm localTime;
time_t tmStamp = time((time_t*)NULL);
localtime_r(&tmStamp, &localTime);
LOG_EX(LOG_Debug, "Timer[%lld] %u On at [%04u-%02u-%02u %02u:%02u:%02u], status = %u\n", pAlarm->itemId, tmId,
localTime.tm_year + 1900, localTime.tm_mon + 1, localTime.tm_mday,
localTime.tm_hour, localTime.tm_min, localTime.tm_sec,
status);
memset(&tmpItem, 0, sizeof(struct ASSISTANT_ARRAY_INFO));
tmpItem.alarmItem.itemId = pAlarm->itemId;
tmpItem.alarmItem.itemType = pAlarm->itemType;
uv_rwlock_rdlock(&g_uvListRwLock);
if(pAlarm->itemType == ASSISTANT_TYPE_CLOCK)
{
DL_SEARCH(g_pAlarmArray, pItem, &tmpItem, __alarmItemCmp);
}
else if(pAlarm->itemType == ASSISTANT_TYPE_REMAIND)
{
DL_SEARCH(g_pRemaindArray, pItem, &tmpItem, __alarmItemCmp);
}
else if(pAlarm->itemType == ASSISTANT_TYPE_SESSION)
{
DL_SEARCH(g_pSessionArray, pItem, &tmpItem, __alarmItemCmp);
}
else
{
LOG_EX(LOG_Error, "Unknown type: %d\n", pAlarm->itemType);
}
uv_rwlock_rdunlock(&g_uvListRwLock);
if(pItem)
{
pItem->alarmItem.year += 1900;
pItem->alarmItem.month += 1;
__assistantRunningEvent(&pItem->alarmItem);
if((pItem->alarmItem.repeatMode & 0xFF) == REPEAT_MODE_NONE)
{
uv_rwlock_wrlock(&g_uvListRwLock);
if(pAlarm->itemType == ASSISTANT_TYPE_CLOCK)
{
DL_DELETE(g_pAlarmArray, pItem);
}
else if(pAlarm->itemType == ASSISTANT_TYPE_REMAIND)
{
DL_DELETE(g_pRemaindArray, pItem);
}
else if(pAlarm->itemType == ASSISTANT_TYPE_SESSION)
{
DL_DELETE(g_pSessionArray, pItem);
}
else
{
LOG_EX(LOG_Error, "Unknown type: %d\n", pAlarm->itemType);
}
uv_rwlock_wrunlock(&g_uvListRwLock);
free(pItem);
}
}
}
static PDBUS_MSG_PACK __dBusOnMessage(uv_loop_t *pLoop, DBusConnection *pConn, PDBUS_MSG_PACK pMsg)
{
PASSISTANT_SYNC_INFO pInfo = NULL;
PASSISTANT_NOTIFY_INFO pNotifyInfo = NULL;
int err = 0;
if(!pMsg || !pLoop || !pConn)
{
return (NULL);
}
if(pMsg->msgDests == 0xFFFFFFFF)
{
return (NULL);
}
LOG_EX(LOG_Debug, "JSON(%08X) %s: %s\n", pMsg->busCmd, DBusCmdToString(pMsg->busCmd), (const char *)pMsg->pMsg);
switch(pMsg->busCmd)
{
case CMD_SESSION_ALARM_SYNC:
pInfo = (PASSISTANT_SYNC_INFO)Json2Struct((const char *)pMsg->pMsg, JSON_ENGINE_ASSISTANT_SYNC_RSP, FALSE, &err);
if(pInfo)
{
__printAssistantSyncInfo(DBusCmdToString(pMsg->busCmd), pInfo);
__cleanupSessionArray();
if(pInfo->pAlarmInfo && pInfo->nItems > 0)
{
err = __addNewItems(pInfo);
}
__assistantRspStatus(pMsg->busCmd, err);
free(pInfo->pAlarmInfo);
free(pInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_ALARM_SYNC_RSP:
pInfo = (PASSISTANT_SYNC_INFO)Json2Struct((const char *)pMsg->pMsg, JSON_ENGINE_ASSISTANT_SYNC_RSP, FALSE, &err);
if(pInfo)
{
g_syncFlags |= 1 << ASSISTANT_TYPE_CLOCK;
__printAssistantSyncInfo(DBusCmdToString(pMsg->busCmd), pInfo);
__cleanupAlarmArray();
if(pInfo->pAlarmInfo && pInfo->nItems > 0)
{
err = __addNewItems(pInfo);
}
__assistantRspStatus(pMsg->busCmd, err);
free(pInfo->pAlarmInfo);
free(pInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_ALARM_ADD:
pInfo = (PASSISTANT_SYNC_INFO)Json2Struct((const char *)pMsg->pMsg, JSON_ENGINE_ASSISTANT_SYNC_RSP, TRUE, &err);
if(pInfo)
{
__printAssistantSyncInfo(DBusCmdToString(pMsg->busCmd), pInfo);
if(pInfo->pAlarmInfo && pInfo->nItems > 0)
{
err = __addNewItems(pInfo);
__assistantRspStatus(pMsg->busCmd, err);
if(err == 0)
{
__assistantNotifyChange(pMsg->busCmd, pInfo->nItems, ASSISTANT_TYPE_CLOCK, pInfo->pAlarmInfo);
}
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
free(pInfo->pAlarmInfo);
free(pInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_ALARM_REMOVE:
pNotifyInfo = (PASSISTANT_NOTIFY_INFO)Json2Struct((const char *)pMsg->pMsg,
JSON_ENGINE_ASSISTANT_NOTIFY, FALSE, &err);
if(pNotifyInfo)
{
__printAssistantNofifyInfo(DBusCmdToString(pMsg->busCmd), pNotifyInfo);
if(pNotifyInfo->nItems > 0)
{
__removeAlarmItem(pNotifyInfo);
__assistantRspStatus(pMsg->busCmd, 0);
__assistantArrayNotifyChange(pMsg->busCmd, pNotifyInfo->nItems, ASSISTANT_TYPE_CLOCK, pNotifyInfo->ids);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
free(pNotifyInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_ALARM_REMOVEALL:
__cleanupAlarmArray();
__assistantRspStatus(pMsg->busCmd, 0);
__assistantNotifyChange(pMsg->busCmd, 0, ASSISTANT_TYPE_CLOCK, NULL);
break;
case CMD_REMAIND_SYNC_RSP:
pInfo = (PASSISTANT_SYNC_INFO)Json2Struct((const char *)pMsg->pMsg, JSON_ENGINE_ASSISTANT_SYNC_RSP, FALSE, &err);
if(pInfo)
{
g_syncFlags |= 1 << ASSISTANT_TYPE_REMAIND;
__printAssistantSyncInfo(DBusCmdToString(pMsg->busCmd), pInfo);
__cleanupRemaindArray();
if(pInfo->pAlarmInfo && pInfo->nItems > 0)
{
err = __addNewItems(pInfo);
}
__assistantRspStatus(pMsg->busCmd, err);
free(pInfo->pAlarmInfo);
free(pInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_REMAIND_ADD:
pInfo = (PASSISTANT_SYNC_INFO)Json2Struct((const char *)pMsg->pMsg, JSON_ENGINE_ASSISTANT_SYNC_RSP, TRUE, &err);
if(pInfo)
{
__printAssistantSyncInfo(DBusCmdToString(pMsg->busCmd), pInfo);
if(pInfo->pAlarmInfo && pInfo->nItems > 0)
{
err = __addNewItems(pInfo);
__assistantRspStatus(pMsg->busCmd, err);
if(err == 0)
{
__assistantNotifyChange(pMsg->busCmd, pInfo->nItems, ASSISTANT_TYPE_REMAIND, pInfo->pAlarmInfo);
}
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
free(pInfo->pAlarmInfo);
free(pInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_REMAIND_REMOVE:
pNotifyInfo = (PASSISTANT_NOTIFY_INFO)Json2Struct((const char *)pMsg->pMsg,
JSON_ENGINE_ASSISTANT_NOTIFY, FALSE, &err);
if(pNotifyInfo)
{
__printAssistantNofifyInfo(DBusCmdToString(pMsg->busCmd), pNotifyInfo);
if(pNotifyInfo->nItems > 0)
{
__removeRemaindItem(pNotifyInfo);
__assistantRspStatus(pMsg->busCmd, 0);
__assistantArrayNotifyChange(pMsg->busCmd, pNotifyInfo->nItems, ASSISTANT_TYPE_REMAIND, pNotifyInfo->ids);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
free(pNotifyInfo);
}
else
{
__assistantRspStatus(pMsg->busCmd, -ERR_INPUT_PARAMS);
}
break;
case CMD_REMAIND_REMOVEALL:
__cleanupRemaindArray();
__assistantRspStatus(pMsg->busCmd, 0);
__assistantNotifyChange(pMsg->busCmd, 0, ASSISTANT_TYPE_REMAIND, NULL);
break;
}
return (NULL);
}
static void __dBusDeameonCb(MODULE_NAME modName, int status)
{
if(status)
{
LOG_EX(LOG_Error, "Daemon(%d) Msg: [%s]\n", modName, status == 0 ? "Connect" : "Disconnect");
}
else
{
LOG_EX(LOG_Info, "Daemon(%d) Msg: [%s]\n", modName, status == 0 ? "Connect" : "Disconnect");
}
#if 0
if(modName == MODULE_CONTROLLER && status == 0)
{
int ret = DBusSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ALARM_SYNC_REQ, "");
LOG_EX(LOG_Debug, "Send CMD_ALARM_SYNC_REQ Command: %d\n", ret);
ret = DBusSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_REMAIND_SYNC_REQ, "");
LOG_EX(LOG_Debug, "Send CMD_REMAIND_SYNC_REQ Command: %d\n", ret);
}
#endif
}
static void __assistantSyncThread(void *pParam)
{
int ret, isSynced = -1;
LOG_EX(LOG_Debug, "Beging Sync holiday Database\n");
do
{
if((g_syncFlags & (1 << ASSISTANT_TYPE_CLOCK)) == 0)
{
ret = DBusSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ALARM_SYNC_REQ, "");
LOG_EX(LOG_Debug, "Send CMD_ALARM_SYNC_REQ Command: %d\n", ret);
}
if((g_syncFlags & (1 << ASSISTANT_TYPE_REMAIND)) == 0)
{
ret = DBusSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_REMAIND_SYNC_REQ, "");
// LOG_EX(LOG_Debug, "Send CMD_REMAIND_SYNC_REQ Command: %d\n", ret);
}
if(isSynced < 0)
{
isSynced = CurrentIsWorkDay(0, 0);
}
sleep(SYNC_TIME_DELAY);
} while(g_syncFlags != ((1 << ASSISTANT_TYPE_CLOCK) | (1 << ASSISTANT_TYPE_REMAIND)));
LOG_EX(LOG_Debug, "Sync holiday Database Finished\n");
ret = DBusSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_ALARM_SYNC_REQ, "");
LOG_EX(LOG_Debug, "Send CMD_ALARM_SYNC_REQ Command: %d\n", ret);
ret = DBusSendToCommand(NULL,
g_pModInfoTable[MODULE_CONTROLLER].modAliase,
CMD_REMAIND_SYNC_REQ, "");
LOG_EX(LOG_Debug, "Send CMD_REMAIND_SYNC_REQ Command: %d\n", ret);
pthread_detach(pthread_self());
}
int main(int argc, char **argv)
{
int ret = 0;
DBusConnection* pBus;
uv_loop_t* pLoop = GetDBusDefaultLoop();
uv_thread_t uvSyncThread;
pBus = DBusWithLibuvInit(pLoop, g_pModInfoTable[MODULE_ALARM].modAliase,
__dBusOnMessage,
__dBusDeameonCb,
NULL, &ret);
if(pBus == NULL)
{
fprintf(stderr, "DBusWithLibuvInit Error: %d\n", ret);
return 0;
}
uv_rwlock_init(&g_uvListRwLock);
AlarmTimerInit(pLoop);
g_syncFlags = 0;
uv_thread_create(&uvSyncThread, __assistantSyncThread, NULL);
RunUVLoop(pLoop);
while(TRUE)
{
usleep(1000);
}
return 0;
}

View File

@ -0,0 +1,210 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <uv.h>
#include <dbus/dbus.h>
#include <errno.h>
#ifdef PLATFORM_R16
#include "log.h"
#include "libuv_dbus.h"
#include "crypto.h"
#include "json_struct.h"
#include "config_engine.h"
#else
#include <uvdbus/log.h>
#include <uvdbus/libuv_dbus.h>
#include <uvdbus/crypto.h>
#include <uvdbus/json_struct.h>
#include <uvdbus/config_engine.h>
#endif
static PDBUS_MSG_PACK __dBusOnMessage(uv_loop_t* pLoop, DBusConnection* pConn, PDBUS_MSG_PACK pMsg)
{
#if 0
int err;
int iValue;
double dValue;
PCFG_API_REQ pReq = NULL;
const char *pJsonStr = NULL;
CFG_API_RSP cfgRsp;
char *pEndPtr = NULL;
int overWrite = FALSE;
if(pMsg == NULL || pMsg->pMsg == NULL)
{
return (NULL);
}
pJsonStr = (const char *)pMsg->pMsg;
pReq = (PCFG_API_REQ)Json2Struct(pJsonStr, JSON_ENGINE_CFG_REQ, TRUE, &err);
memset(&cfgRsp, 0, sizeof(CFG_API_RSP));
strncpy(cfgRsp.keyName, pReq->keyName, MAX_CFG_KEY_NAME);
strncpy(cfgRsp.keyValue, pReq->keyValue, MAX_CFG_KEY_VALUE);
cfgRsp.keyType = pReq->keyType;
if(pReq == NULL || err != 0)
{
LOG_EX(LOG_Error, "Decode Json Error: %p, %d\n", pReq, err);
if(pReq)
{
free(pReq);
}
return (NULL);
}
switch(pMsg->busCmd)
{
case CMD_CFG_ADD:
case CMD_CFG_CHANGE:
if(pMsg->busCmd == CMD_CFG_CHANGE)
{
CFG_ITEM item;
PCFG_ITEM pItem = &item;
if(CfgGetKeyValue(pReq->keyName, &pItem) == -ERR_CFG_NOITEM)
{
cfgRsp.errNo = -ERR_CFG_NOITEM;
DBusJsonSendToCommand(NULL, g_pModInfoTable[pMsg->msgSrc].modAliase, CMD_CFG_UPG_NOTIFY, JSON_ENGINE_CFG_RSP, &cfgRsp, TRUE);
return (NULL);
}
overWrite = TRUE;
}
switch(pReq->keyType)
{
case CFG_TYPE_STRING:
cfgRsp.errNo = CfgAddGlobalStringItem(pReq->keyName, pReq->keyValue, overWrite);
break;
case CFG_TYPE_INT:
iValue = strtol(pReq->keyValue, NULL, 10);
if(errno != ERANGE && errno != EINVAL)
{
cfgRsp.errNo = CfgAddGlobalIntItem(pReq->keyName, iValue, overWrite);
if(cfgRsp.errNo != 0)
{
LOG_EX(LOG_Error, "Add Configure [%s](%d) --> [%s] Error: %d\n",
pReq->keyName, pReq->keyType, pReq->keyValue, err);
}
}
else
{
cfgRsp.errNo = -ERR_INPUT_PARAMS;
LOG_EX(LOG_Error, "Input Params Error: [%s](%d) --> [%s]\n",
pReq->keyName, pReq->keyType, pReq->keyValue);
}
break;
case CFG_TYPE_DOUBLE:
dValue = strtod(pReq->keyValue, &pEndPtr);
if((errno == ERANGE) || (dValue == 0 && (strcmp(pReq->keyName, pEndPtr) == 0)))
{
cfgRsp.errNo = -ERR_INPUT_PARAMS;
LOG_EX(LOG_Error, "Input Params Error: [%s](%d) --> [%s]\n",
pReq->keyName, pReq->keyType, pReq->keyValue);
}
else
{
cfgRsp.errNo = CfgAddGlobalIntItem(pReq->keyName, dValue, overWrite);
if(cfgRsp.errNo != 0)
{
LOG_EX(LOG_Error, "Add Configure [%s](%d) --> [%s] Error: %d\n",
pReq->keyName, pReq->keyType, pReq->keyValue, err);
}
}
break;
default:
cfgRsp.errNo = -ERR_UNKNOWN_TYPE;
break;
}
if(cfgRsp.errNo == 0)
{
DBusJsonBoardcastCommand(NULL, 0xFFFFFFFF, CMD_CFG_UPG_NOTIFY, JSON_ENGINE_CFG_RSP, &cfgRsp, TRUE);
}
else
{
DBusJsonSendToCommand(NULL, g_pModInfoTable[pMsg->msgSrc].modAliase, CMD_CFG_UPG_NOTIFY, JSON_ENGINE_CFG_RSP, &cfgRsp, TRUE);
}
break;
case CMD_CFG_GET:
{
PCFG_ITEM pItem = NULL;
if(CfgGetKeyValue(pReq->keyName, &pItem) == -ERR_CFG_NOITEM)
{
cfgRsp.errNo = -ERR_CFG_NOITEM;
DBusJsonSendToCommand(NULL, g_pModInfoTable[pMsg->msgSrc].modAliase, CMD_CFG_UPG_NOTIFY, JSON_ENGINE_CFG_RSP, &cfgRsp, TRUE);
return (NULL);
}
else
{
memset(cfgRsp.keyValue, 0, MAX_CFG_KEY_VALUE);
cfgRsp.keyType = pItem->keyType;
if(pItem->keyType == CFG_TYPE_STRING)
{
strncpy(cfgRsp.keyValue, pItem->pStrValue, MAX_CFG_KEY_VALUE);
}
else if(pItem->keyType == CFG_TYPE_INT)
{
sprintf(cfgRsp.keyValue, "%d", pItem->intValue);
}
else if(pItem->keyType == CFG_TYPE_DOUBLE)
{
sprintf(cfgRsp.keyValue, "%f", pItem->doubleValue);
}
DBusJsonSendToCommand(NULL, g_pModInfoTable[pMsg->msgSrc].modAliase, CMD_CFG_GET, JSON_ENGINE_CFG_RSP, &cfgRsp, TRUE);
}
}
break;
default:
//cfgRsp.errNo = -ERR_UNKNOWN_TYPE;
//DBusJsonSendToCommand(NULL, g_pModInfoTable[pMsg->msgSrc].modAliase, CMD_CFG_UPG_NOTIFY, JSON_ENGINE_CFG_RSP, &cfgRsp, TRUE);
break;
}
#endif
return NULL;
}
static void __dBusHeartLost(MODULE_NAME loster)
{
LOG_EX(LOG_Error, "Found %d Heart Lost\n", loster);
}
int main(int argc, char** argv)
{
int ret = 0;
uv_loop_t* pLoop = GetDBusDefaultLoop();
DBusConnection* pBus = DBusWithLibuvInit(pLoop, g_pModInfoTable[MODULE_CONFIGURE].modAliase,
__dBusOnMessage,
NULL,
NULL, &ret);
if(pBus == NULL)
{
fprintf(stderr, "DBusWithLibuvInit Error: %d\n", ret);
return 0;
}
//DBusWithLibuvCfgInit(__onCfgMsgCb);
//DBusWithLibuvCfgInit();
return uv_run(pLoop, UV_RUN_DEFAULT);
}

323
Modules/LogCtrl/log_ctrl.c Normal file
View File

@ -0,0 +1,323 @@
 #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <uv.h>
#include <dbus/dbus.h>
#include <readline/readline.h>
#if defined(PLATFORM_R16) || defined (PLATFORM_CPU)
#include "log.h"
#include "libuv_dbus.h"
#include "json_struct.h"
#else
#include <uvdbus/log.h>
#include <uvdbus/libuv_dbus.h>
#include <uvdbus/json_struct.h>
#endif
static MOD_INFO_TABLE g_ModInfo;
static PDBUS_MSG_PACK DBusOnMessage(uv_loop_t* pLoop, DBusConnection* pConn, PDBUS_MSG_PACK pMsg)
{
//int i, ret, err;
//uint32_t tm = LIBUV_CURRENT_TIME_US();
if(!pMsg || !pLoop || !pConn)
{
return NULL;
}
//LOG_EX(LOG_Info, "Process Message(%u --> 0x%08X) at [%lu.%06lu]: cmd = %u, size = %u, key = %d, msg(%d) = [%s]\n",
// pMsg->msgSrc, pMsg->msgDests, tm / 1000000, tm % 1000000, pMsg->busCmd, pMsg->msgSize, pMsg->msgKey, pMsg->msgSize, pMsg->pMsg);
return NULL;
}
static void __logCtrlProc(void *pParams)
{
int i = 0;
//int ret;
LOG_LEVEL logLevelInfo[] = {
LOG_Fatal, LOG_Error, LOG_Warn, LOG_Debug, LOG_Info,
LOG_Test, LOG_Call, LOG_Devp, LOG_Step, LOG_Unknown, LOG_All, LOG_Close
};
const char* g_Menu[] = {
"Usage: enable/disable <modName> <operation> [params1] [params2]\n"
" help\n",
" quit\n",
};
const char* pOptMenu[] = {
"\n operation:\n"
" |--------------------------------------------------------------------------|\n",
" | command | operation | params1 | params2 |\n",
" |--------------------------------------------------------------------------|\n",
" | enable | | | |\n",
" |----------| 0: Set log level | Log level | Unused |\n",
" | disable | | | |\n",
" |----------|---------------------|-----------------------|-----------------|\n",
" | enable | | | |\n",
" |----------| 1: Print to file | Unused | Unused |\n",
" | disable | | | |\n",
" |----------|---------------------|-----------------------|-----------------|\n",
" | enable | | | |\n",
" |----------| 2: Backup to email | Unused | Unused |\n",
" | disable | | | |\n",
" |----------|---------------------|-----------------------|-----------------|\n",
" | enable | | Log server ip address | Log server port |\n",
" |----------| 3: Send to network |-----------------------|-----------------|\n",
" | disable | | Unused | Unused |\n",
" |--------------------------------------------------------------------------|\n",
" | enable | | | |\n",
" |----------| 4: Backup to Server | Unused | Unused |\n",
" | disable | | | |\n",
" |----------|---------------------|-----------------------|-----------------|\n",
};
while(TRUE)
{
char *pInput = NULL;
char *pCmd = NULL;
for(i = 0; i < sizeof(g_Menu) / sizeof(g_Menu[0]); i++)
{
LOG_EX2(LOG_Info, "%s", g_Menu[i]);
}
pInput = readline("Enter Command:");
if(pInput == NULL)
{
continue;
}
pCmd = strtok(pInput, " ");
i = 0;
while(pCmd != NULL)
{
if(strcmp(pCmd, "help") == 0)
{
for(i = 0; i < sizeof(g_pModInfoTable) / sizeof(g_pModInfoTable[0]); i++)
{
if(i == 0)
{
LOG_EX2(LOG_Info, " modName : %-2d --> %s\n",
i, ModuleNameToString(g_pModInfoTable[i].modName));
}
else
{
LOG_EX2(LOG_Info, "%15s%-2d --> %s\n", "",
i, ModuleNameToString(g_pModInfoTable[i].modName));
}
}
for(i = 0; i < sizeof(logLevelInfo) / sizeof(logLevelInfo[0]); i++)
{
if(i == 0)
{
LOG_EX2(LOG_Info, "\n Log Level: %-2d --> %s\n", i, LogLeveToString(logLevelInfo[i]));
}
else
{
LOG_EX2(LOG_Info, "%15s%-2d --> %s\n", "", i, LogLeveToString(logLevelInfo[i]));
}
}
for(i = 0; i < sizeof(pOptMenu) / sizeof(pOptMenu[0]); i++)
{
LOG_EX2(LOG_Info, "%s", pOptMenu[i]);
}
}
else if(strcmp(pCmd, "enable") == 0
|| strcmp(pCmd, "disable") == 0)
{
LOG_CFG_PROTOCOL logItem;
int iCmd, iMod;
char *pParams1 = NULL, *pParams2 = NULL;
char* pMod = strtok(NULL, " ");
char* pOperat = strtok(NULL, " ");
if(pMod == NULL || strlen(pMod) == 0)
{
LOG_EX(LOG_Error, "Input <modName> error, see help\n");
break;
}
if(pOperat == NULL || strlen(pOperat) == 0)
{
LOG_EX(LOG_Error, "Input <operation> error, see help\n");
break;
}
iMod = strtol(pMod, NULL, 10);
if(iMod < 0 || iMod >= MODULE_MAX)
{
LOG_EX(LOG_Error, "Input <modName> error: %s(%d)\n", pMod, iMod);
break;
}
iCmd = strtol(pOperat, NULL, 10);
memset(&logItem, 0, sizeof(LOG_CFG_PROTOCOL));
switch(iCmd)
{
case 0:
pParams1 = strtok(NULL, " ");
if(pParams1 && strlen(pParams1) > 0)
{
int logLevel = strtol(pParams1, NULL, 10);
if(logLevel >= 0 && logLevel < sizeof(logLevelInfo) / sizeof(logLevelInfo[0]))
{
LOG_EX2(LOG_Info, "%s %d 0x%08X\n", pCmd, iCmd, logLevelInfo[logLevel]);
logItem.cfgCmd = CMD_LOG_LEVEL;
logItem.iParams2 = (strcmp(pCmd, "disable") == 0) ? FALSE : TRUE;
logItem.iParams1 = logLevelInfo[logLevel];
DBusJsonSendToCommand(NULL,
g_pModInfoTable[iMod].modAliase,
CMD_LOG_CONFIG,
JSON_ENGINE_LOG_CFG_CMD,
&logItem, TRUE);
}
else
{
LOG_EX(LOG_Error, "Input <pParams1> error, see help\n");
}
}
else
{
LOG_EX(LOG_Error, "Input <pParams1> error, see help\n");
}
break;
case 1:
logItem.cfgCmd = CMD_LOG_FILE;
logItem.iParams1 = (strcmp(pCmd, "disable") == 0) ? FALSE : TRUE;
DBusJsonSendToCommand(NULL,
g_pModInfoTable[iMod].modAliase,
CMD_LOG_CONFIG,
JSON_ENGINE_LOG_CFG_CMD,
&logItem, TRUE);
break;
case 2:
logItem.cfgCmd = CMD_LOG_MAIL;
logItem.iParams1 = (strcmp(pCmd, "disable") == 0) ? FALSE : TRUE;
DBusJsonSendToCommand(NULL,
g_pModInfoTable[iMod].modAliase,
CMD_LOG_CONFIG,
JSON_ENGINE_LOG_CFG_CMD,
&logItem, TRUE);
break;
case 3:
pParams1 = strtok(NULL, " ");
logItem.cfgCmd = CMD_LOG_NETWORK;
if(pParams1 == NULL || strlen(pParams1) == 0)
{
logItem.iParams1 = 0;
DBusJsonSendToCommand(NULL,
g_pModInfoTable[iMod].modAliase,
CMD_LOG_CONFIG,
JSON_ENGINE_LOG_CFG_CMD,
&logItem, TRUE);
}
else
{
pParams2 = strtok(NULL, " ");
if(pParams2 != NULL && strlen(pParams2) > 0)
{
logItem.iParams1 = inet_addr(pParams1);
logItem.iParams2 = strtol(pParams2, NULL, 10);
DBusJsonSendToCommand(NULL,
g_pModInfoTable[iMod].modAliase,
CMD_LOG_CONFIG,
JSON_ENGINE_LOG_CFG_CMD,
&logItem, TRUE);
}
else
{
LOG_EX(LOG_Error, "Input <pParams> error, pParams2 = %s\n",
SAFE_STRING_VALUE(pParams2));
}
}
break;
case 4:
logItem.cfgCmd = CMD_LOG_SERVER;
logItem.iParams1 = (strcmp(pCmd, "disable") == 0) ? FALSE : TRUE;
DBusJsonSendToCommand(NULL,
g_pModInfoTable[iMod].modAliase,
CMD_LOG_CONFIG,
JSON_ENGINE_LOG_CFG_CMD,
&logItem, TRUE);
break;
default:
LOG_EX(LOG_Error, "Unknown operation(0-3) %s, see help\n", pOperat);
break;
}
}
else if(strcmp(pCmd, "quit") == 0)
{
return;
}
pCmd = strtok(NULL, " ");
}
usleep(1000);
}
pthread_detach(pthread_self());
}
int main(int argc, char **argv)
{
int ret = 0;
DBusConnection* pBus = NULL;
uv_thread_t uvThread;
uv_loop_t* pLoop = GetDBusDefaultLoop();
memcpy(&g_ModInfo, &g_pModInfoTable[MODULE_LOG_CTRL], sizeof(MOD_INFO_TABLE));
pBus = DBusWithLibuvInit(pLoop, g_ModInfo.modAliase,
DBusOnMessage,
NULL,
NULL,
&ret);
if(pBus == NULL)
{
fprintf(stderr, "DBusWithLibuvInit Error: %d\n", ret);
return 0;
}
uv_thread_create(&uvThread, __logCtrlProc, NULL);
RunUVLoop(pLoop);
while(TRUE)
{
usleep(1000);
}
return (0);
}

1389
Modules/OTA/ota.c Normal file

File diff suppressed because it is too large Load Diff

75
Modules/voice/SrcApi.h Normal file
View File

@ -0,0 +1,75 @@
#ifndef _SRCAPI_H_
#define _SRCAPI_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _SRCParam
{
const char* URL;
const char* appKey;
const char* appSecret;
const char* cuid;
const char* severVadThresh1;
const char* severVadThresh2;
} SRCParam;
enum SRC_ERROR
{
SRC_SUCCESS = 0,
SRC_HTTP_ERROR = 1,
SRC_SERVER_ERROR = 2,
SRC_SESSION_BEGIN_ERROR = 3,
};
enum VAD_STATUS
{
SRC_VAD_LOOKING_FOR_SPEECH = 0,
SRC_VAD_IN_SPEECH = 1,
SRC_VAD_END_SPEECH = 2,
};
enum REC_STATUS
{
SRC_REC_SENT_AUDIO_SUCCESS = 1000,
SRC_REC_SENT_AUDIO_FAILED = 1001,
SRC_REC_SENT_AUDIO_END_DETECTED = 1002,
SRC_REC_RESULT_COMPLETE = 2000,
SRC_REC_TIMEOUT_SERVICE_CLOSING = 2001,
SRC_REC_TIMEOUT_SERVICE_CLOSED = 2002,
SRC_REC_RESULT_NOT_COMPLETE = 2003,
SRC_REC_NLU_SUCCESS = 3100,
SRC_REC_NLU_FAILED = 3101,
SRC_REC_RESULT_PARAM_NULL = 4001,
SRC_REC_MISS_AUTHEN_PARAM = 4002,
SRC_REC_AUTHEN_FAILURE = 4003,
SRC_REC_MISS_IDX_OR_ILLEGAL = 4004,
SRC_REC_MISS_CUID = 4005,
SRC_REC_MISS_CHANNEL = 4006,
SRC_REC_MISS_PTC_OR_ILLEGAL = 4007,
SRC_REC_MISS_RATE_OR_ILLEGAL = 4008,
SRC_REC_MISS_SESSIONID = 4009,
};
void SRCSetUPParam(const char* strKey, const char* strValue);
void SRCSetSPParam(const char* strKey, const char* strValue);
const char* SRCSessionBegin(SRCParam srcParam, int *error);
int SRCAudioWrite(const char* session_id, const short *audioData, unsigned int audioLen, int *vadStat, int *recStat);
const char* SRCGetResult(const char* session_id , int *server_ret);
int SRCSessionEnd(const char* session_id);
const char* SRCGetVersion();
#ifdef __cplusplus
};
#endif
#endif // _SRCAPI_H_

BIN
Modules/voice/data.pcm Normal file

Binary file not shown.

93
Modules/voice/demo.c Normal file
View File

@ -0,0 +1,93 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "SrcApi.h"
#define DEBUG_CODE_LINE() (printf("%s(%d)\n", __FUNCTION__, __LINE__))
#define POSTURL "api-test.vop.netease.com/echo_api?rate=16000&lan=zh"
int main()
{
#if 1
const int kSamples = 1024; //40ms
int rcv_code = 0;
int error_code = 0;
short data[kSamples];
SRCParam srcParam;
srcParam.URL = POSTURL;
srcParam.appKey = "onlinedemo";
srcParam.appSecret = "4ea70c117a5b858cd9e6e384009bbad7";
srcParam.severVadThresh1 = "2.0";
srcParam.severVadThresh2 = "2.0";
srcParam.cuid = "1215468784532";
SRCSetUPParam("uuid","0-A024067C55B0163C");
SRCSetUPParam("aes", "0");
//SRCSetUPParam("state", "{\"filed\":1}");
//SRCSetSPParam("name1", "xxxxxx");
//SRCSetSPParam("name2", "xxxxxx");
const char* session_id;
DEBUG_CODE_LINE();
int status = 0;
FILE *asrFile = fopen("data.pcm", "rb");
session_id = SRCSessionBegin(srcParam, &status);
if (status != SRC_SUCCESS)
{
printf("SRCStartNewSession error:%d\n", status);
}
printf("ssid = %s\n", session_id);
int getResCnt = 0;
rcv_code = 0;
const char *asr_out = NULL;
DEBUG_CODE_LINE();
while (1)
{
if (fread(data, 2, kSamples, asrFile) == 0)
{
fseek(asrFile, 0, 0);
}
int vadFlag = 0;
int recFlag = 0;
DEBUG_CODE_LINE();
status = SRCAudioWrite(session_id, data, kSamples, &vadFlag, &recFlag);
DEBUG_CODE_LINE();
if (status != SRC_SUCCESS)
{
printf("SRCAudioWrite error:%d\n", status);
}
printf("vadFlag = %d, recFlag = %d\n", vadFlag, recFlag);
if (vadFlag == SRC_VAD_END_SPEECH || recFlag == 1002)
break;
usleep(40 * 1000);
}
DEBUG_CODE_LINE();
while (rcv_code != 3100)
{
usleep(100 * 1000);
asr_out = SRCGetResult(session_id, &rcv_code);
getResCnt++;
if (error_code != 0)
{
break;
}
if (getResCnt > 10)
{
break;
}
printf("rcv_code = %d, retry = %d\n", rcv_code, getResCnt);
}
printf("=============%s=============\n", (asr_out));
fclose(asrFile);
SRCSessionEnd(session_id);
#endif
printf("Demo++++++++++++++++++++++\n");
return 0;
}

BIN
Modules/voice/libSRC.so Normal file

Binary file not shown.

BIN
Modules/voice/voice Normal file

Binary file not shown.

View File

@ -0,0 +1,76 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=alarm
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= TRUE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Modules/Alarm/
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = assistant.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS)
# gcc CFLAGS
PLAT_R16_CFLAGS := -I./ -I../include
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/
PLAT_LINUX_CFLAGS += -I../linux32/inc/ -I../linux32/inc/cjson/ -I../linux32/inc/uthash/
#R16_LIBS := -lgobject-2.0 -lffi -lglib-2.0 -ldbus-1 -ldbus-glib-1 -luv
R16_LIBS := $(COMMON_R16_LIBS)
R16_LIBS += ./libuvdbus-r16.so
LINUX_LIBS := $(COMMON_LINUX_LIBS)
LINUX_LIBS += ./libuvdbus-linux.so
ifeq ($(PLAT_R16), TRUE)
DEPEND_LIB += ./debug/libuvdbus-r16.so
USER_CLEAN_ITEMS += ./libuvdbus-r16.so
endif
ifeq ($(PLAT_LINUX), TRUE)
DEPEND_LIB += ./debug/libuvdbus-linux.so
USER_CLEAN_ITEMS += ./libuvdbus-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
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

75
build/Makefile.app.cross Normal file
View File

@ -0,0 +1,75 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=dbus
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= TRUE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Example
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = main.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS)
# gcc CFLAGS
PLAT_R16_CFLAGS := -I./ -I../include
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/
PLAT_LINUX_CFLAGS += -I../linux32/inc/ -I../linux32/inc/cjson/ -I../linux32/inc/uthash/
#R16_LIBS := -lgobject-2.0 -lffi -lglib-2.0 -ldbus-1 -ldbus-glib-1 -luv -lnghttp2
R16_LIBS := $(COMMON_R16_LIBS) -lreadline -lcurses
R16_LIBS += ./libuvdbus-r16.so
LINUX_LIBS := $(COMMON_LINUX_LIBS) -lreadline -lnghttp2
LINUX_LIBS += ./libuvdbus-linux.so
ifeq ($(PLAT_R16), TRUE)
DEPEND_LIB := ./debug/libuvdbus-r16.so
USER_CLEAN_ITEMS += ./libuvdbus-r16.so
endif
ifeq ($(PLAT_LINUX), TRUE)
DEPEND_LIB += ./debug/libuvdbus-linux.so
USER_CLEAN_ITEMS += ./libuvdbus-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
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

View File

@ -0,0 +1,68 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=config_server
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= FALSE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Modules/ConfigServer/
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = config_server.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS)
# gcc CFLAGS
PLAT_R16_CFLAGS := -I./ -I../include
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/
#R16_LIBS := -lgobject-2.0 -lffi -lglib-2.0 -ldbus-1 -ldbus-glib-1 -luv
R16_LIBS := $(COMMON_R16_LIBS)
#LINUX_LIBS := -ldbus-1 -luv -lcrypto -lcjson
R16_LIBS += ./libuvdbus-r16.so
ifeq ($(PLAT_R16), TRUE)
DEPEND_LIB := ./debug/libuvdbus-r16.so
USER_CLEAN_ITEMS += ./libuvdbus-r16.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
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

2
build/Makefile.def.cross Normal file
View File

@ -0,0 +1,2 @@
COMMON_R16_LIBS := -ldbus-1 -luv -lcrypto -lcjson -ls2json -lsqlite3 -lnghttp2 -lquickmail -lz -luuid -lconfig -lcurl -lssl -lpthread
COMMON_LINUX_LIBS := -ldbus-1 -luv -lcrypto -lcurl -lm -lnghttp2 -lsqlite3 -lquickmail -lz -luuid -lconfig -lssl -lpthread

79
build/Makefile.lib.cross Normal file
View File

@ -0,0 +1,79 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=libuvdbus
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = DLL
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= TRUE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Framework ../log ../Modules ../linux32
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = \
libuvEngine/libuv_dbus.c \
HeartDaemon/heart_daemon.c \
JsonUtils/json_struct.c \
Configure/config_engine.c \
Configure/ini_prase.c \
Crypto/aes.c \
Crypto/base64.c \
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 \
Monitor/monitor.c \
log.c \
SvrManager/svr_manager.c \
hexdump.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS) \
src/cJSON.c \
src/s2j.c
# gcc CFLAGS
PLAT_R16_CFLAGS := -I../include -fPIC
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/ -I../linux32/inc/ -I../linux32/inc/cjson/
PLAT_LINUX_CFLAGS += -I../linux32/inc/uthash/
PLAT_R16_LDFLAGS := -shared -fPIC
PLAT_LINUX_LDFLAGS := $(PLAT_R16_LDFLAGS)
R16_LIBS := $(COMMON_R16_LIBS)
LINUX_LIBS := $(COMMON_LINUX_LIBS)
# this line must be at below of thus, because of...
include /opt/common/Makefile.cross
ifeq ($(MAKECMDGOALS), )
$(shell find ./ -name $(TARGET)-*.exe -delete)
else
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

View File

@ -0,0 +1,76 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=logCtrl
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= TRUE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Modules/LogCtrl/
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = log_ctrl.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS)
# gcc CFLAGS
PLAT_R16_CFLAGS := -I./ -I../include
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/
PLAT_LINUX_CFLAGS += -I../linux32/inc/ -I../linux32/inc/cjson/ -I../linux32/inc/uthash/
R16_LIBS := $(COMMON_R16_LIBS) -lreadline -lcurses
R16_LIBS += ./libuvdbus-r16.so
LINUX_LIBS := $(COMMON_LINUX_LIBS) -lreadline
LINUX_LIBS += ./libuvdbus-linux.so
ifeq ($(PLAT_R16), TRUE)
DEPEND_LIB += ./debug/libuvdbus-r16.so
USER_CLEAN_ITEMS += ./libuvdbus-r16.so
endif
ifeq ($(PLAT_LINUX), TRUE)
DEPEND_LIB += ./debug/libuvdbus-linux.so
USER_CLEAN_ITEMS += ./libuvdbus-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
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

76
build/Makefile.ota.cross Normal file
View File

@ -0,0 +1,76 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=ota
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= TRUE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Modules/OTA/
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = ota.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS)
# gcc CFLAGS
PLAT_R16_CFLAGS := -I./ -I../include
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/
PLAT_LINUX_CFLAGS += -I../linux32/inc/ -I../linux32/inc/cjson/ -I../linux32/inc/uthash/
#R16_LIBS := -lgobject-2.0 -lffi -lglib-2.0 -ldbus-1 -ldbus-glib-1 -luv
R16_LIBS := $(COMMON_R16_LIBS)
R16_LIBS += ./libuvdbus-r16.so
LINUX_LIBS := $(COMMON_LINUX_LIBS)
LINUX_LIBS += ./libuvdbus-linux.so
ifeq ($(PLAT_R16), TRUE)
DEPEND_LIB += ./debug/libuvdbus-r16.so
USER_CLEAN_ITEMS += ./libuvdbus-r16.so
endif
ifeq ($(PLAT_LINUX), TRUE)
DEPEND_LIB += ./debug/libuvdbus-linux.so
USER_CLEAN_ITEMS += ./libuvdbus-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
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

View File

@ -0,0 +1,72 @@
include Makefile.def.cross
# target name, the target name must have the same name of c source file
TARGET_NAME=voice
# target
# for linux module driver: KO
# for application: EXE
# for dynamic library: DLL
TARGET_TYPE = EXE
# target object
# for application: APP
# for device driver: DRV
TARGET_OBJ = APP
TARGET_BOX =
#debug mode or release mode
DEBUG = TRUE
PLAT_R16 ?= TRUE
PLAT_LINUX ?= FALSE
PLAT_WIN32 ?= FALSE
PLAT_WIN64 ?= FALSE
VPATH = ../Modules/voice/
# source code
# set the source file, don't used .o because of ...
# MRS Board Source Files
PLAT_R16_SRCS = demo.c
PLAT_LINUX_SRCS := $(PLAT_R16_SRCS)
# gcc CFLAGS
PLAT_R16_CFLAGS := -I./ -I../include
PLAT_LINUX_CFLAGS := $(PLAT_R16_CFLAGS) -I/usr/include/dbus-1.0/ -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include/
PLAT_LINUX_CFLAGS += -I../linux32/inc/ -I../linux32/inc/cjson/ -I../linux32/inc/uthash/
#R16_LIBS := -lgobject-2.0 -lffi -lglib-2.0 -ldbus-1 -ldbus-glib-1 -luv
R16_LIBS := $(COMMON_R16_LIBS)
R16_LIBS += ./libuvdbus-r16.so ./libSRC.so
LINUX_LIBS := $(COMMON_LINUX_LIBS)
LINUX_LIBS += ./libuvdbus-linux.so
ifeq ($(PLAT_R16), TRUE)
DEPEND_LIB += ../Modules/voice/libSRC.so
USER_CLEAN_ITEMS += ./libSRC.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
ifeq ($(MAKECMDGOALS), all)
$(shell find ./ -name "$(TARGET)-*.exe" -delete)
endif
endif

4
compile.sh Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env bash
source /etc/profile
make OPT=clean && make && make OPT=install
#make && make OPT=install

168
include/assistant.h Normal file
View File

@ -0,0 +1,168 @@
#ifndef ASSISTANT_H
#define ASSISTANT_H
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_TIP_LEN (60 * 4 + 1)
#define MAX_ALARM_ITEMS (1024)
typedef enum
{
ASSISTANT_TYPE_CLOCK = 0,
ASSISTANT_TYPE_REMAIND,
ASSISTANT_TYPE_SESSION,
} ASSISTANT_TYPE;
typedef enum
{
STATUS_IDLE = 0,
STATUS_PREPARE_STANDBY,
STATUS_RUNNING,
STATUS_NOT_IN_USE,
STATUS_REMOVE_ITEM,
STATUS_ADD_ITEM,
} ASSISTANT_STATUS;
typedef struct
{
unsigned long long itemId; ///< 提醒、闹钟ID
ASSISTANT_TYPE itemType; ///< 类型: 0 闹钟, 1 提醒
int priority; ///< 优先级: 暂未使用
REPEAT_MODE repeatMode; ///< 重复模式
int year; ///< 年
int month; ///< 月
int day; ///< 日
int hour; ///< 小时
int minute; ///< 分钟
int second; ///< 秒钟
int weekDay; ///< 星期
unsigned int timerId; ///< 关联的定时器ID
unsigned long long voiceId; ///< 闹钟资源ID
char strTips[MAX_TIP_LEN]; ///< 提醒 TTS 文本
char resUrl[2048]; ///< 资源URL
char voiceRes[32]; ///< 资源声音文件ID
char voiceResType[64]; ///< 资源类型
} ASSISTANT_ITEM_INFO, *PASSISTANT_ITEM_INFO;
typedef struct
{
int nItems; ///< 协议包含的数据个数
PASSISTANT_ITEM_INFO pAlarmInfo; ///< 提醒、闹钟数据详细信息
} ASSISTANT_SYNC_INFO, *PASSISTANT_SYNC_INFO;
typedef struct ASSISTANT_ARRAY_INFO
{
ASSISTANT_ITEM_INFO alarmItem;
struct ASSISTANT_ARRAY_INFO *next, *prev;
} *PASSISTANT_ARRAY_INFO;
typedef struct
{
int cmd;
int nItems;
ASSISTANT_TYPE type;
unsigned long long ids[MAX_ALARM_ITEMS];
} ASSISTANT_NOTIFY_INFO, *PASSISTANT_NOTIFY_INFO;
typedef struct
{
int cmd;
int val;
} ASSISTANT_RSP_STATUS, *PASSISTANT_RSP_STATUS;
typedef struct
{
int cmd;
int val;
int errCode;
} ASSISTANT_NOFIFY_EVENT, *PASSISTANT_NOFIFY_EVENT;
static void __printAssistantNofifyInfo(const char *pTags, PASSISTANT_NOTIFY_INFO pInfo)
{
int i;
if(pTags && strlen(pTags) > 0)
{
LOG_EX2(LOG_Debug, "%s:\n", pTags);
LOG_EX2(LOG_Debug, "**************************************************************\n");
}
LOG_EX2(LOG_Debug, "Sync Items : %d\n", pInfo->nItems);
LOG_EX2(LOG_Debug, "-------------------------\n");
LOG_EX2(LOG_Debug, "| Alarm Id | Type |\n");
LOG_EX2(LOG_Debug, "-------------------------\n");
for(i = 0; i < pInfo->nItems; i++)
{
LOG_EX2(LOG_Debug, "| %8llu | %11s |\n",
pInfo->ids[i],
(pInfo->type == ASSISTANT_TYPE_REMAIND) ? "Remaind" : "Alarm Clock");
}
LOG_EX2(LOG_Debug, "-------------------------\n");
}
static void __printAssistantSyncInfo(const char* pTags, PASSISTANT_SYNC_INFO pInfo)
{
int i;
char buf[MAX_PATH];
struct tm localTime;
time_t tmStamp;
if(pTags && strlen(pTags) > 0)
{
LOG_EX2(LOG_Debug, "%s:\n", pTags);
LOG_EX2(LOG_Debug, "**************************************************************\n");
}
//fprintf(stdout, "Command : %d(%08X)\n", pInfo->cmd, pInfo->cmd);
LOG_EX2(LOG_Debug, "Sync Items : %d\n", pInfo->nItems);
LOG_EX2(LOG_Debug, "---------------------------------------------------------------------"
"-----------------------------------------------------------\n");
LOG_EX2(LOG_Debug, "| Alarm Id | Type | Priority | Repeat Mode | Week Day |"
" DateTime | Tips | Resource |\n");
LOG_EX2(LOG_Debug, "---------------------------------------------------------------------"
"-----------------------------------------------------------\n");
for(i = 0; i < pInfo->nItems; i++)
{
memset(buf, 0, MAX_PATH);
sprintf(buf, "%04u-%02u-%02u %02u:%02u:%02u",
(pInfo->pAlarmInfo[i].year == -1) ? 1900 : pInfo->pAlarmInfo[i].year + 1900,
(pInfo->pAlarmInfo[i].month == -1) ? 0 : pInfo->pAlarmInfo[i].month + 1,
(pInfo->pAlarmInfo[i].day == -1) ? 0 : pInfo->pAlarmInfo[i].day,
(pInfo->pAlarmInfo[i].hour == -1) ? 0 : pInfo->pAlarmInfo[i].hour,
(pInfo->pAlarmInfo[i].minute == -1) ? 0 : pInfo->pAlarmInfo[i].minute,
(pInfo->pAlarmInfo[i].second == -1) ? 0 : pInfo->pAlarmInfo[i].second);
LOG_EX2(LOG_Debug, "| %8llu | %11s | %8d | %15s | %d%d%d%d %d%d%d%d | %20s | %20s | %8llu |\n",
pInfo->pAlarmInfo[i].itemId,
(pInfo->pAlarmInfo[i].itemType == ASSISTANT_TYPE_REMAIND) ? "Remaind" : "Alarm Clock",
pInfo->pAlarmInfo[i].priority,
DumpTimerRepeatModeString(pInfo->pAlarmInfo[i].repeatMode),
(pInfo->pAlarmInfo[i].weekDay & (1 << 7))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 6))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 5))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 4))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 3))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 2))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 1))? 1 : 0,
(pInfo->pAlarmInfo[i].weekDay & (1 << 0))? 1 : 0,
buf,
pInfo->pAlarmInfo[i].strTips,
pInfo->pAlarmInfo[i].voiceId);
}
LOG_EX2(LOG_Debug, "---------------------------------------------------------------------"
"-----------------------------------------------------------\n");
}
#ifdef __cplusplus
}
#endif
#endif

58
include/config_engine.h Normal file
View File

@ -0,0 +1,58 @@
#ifndef CONFIG_ENGINE_H
#define CONFIG_ENGINE_H
#include <uthash/uthash.h>
#include <sqlite3.h>
#include "smart_sound.h"
#ifdef __cplusplus
extern "C" {
#endif
#define GLOBAL_CFG_FILE_PATH ("/mnt/UDISK/global.db")
typedef enum
{
CFG_TYPE_STRING = 0,
CFG_TYPE_INT = 1,
CFG_TYPE_DOUBLE = 2,
} CFG_DATA_TYPE;
typedef struct
{
char* pKeyName;
int keyType;
int keyModule;
union
{
char* pStrValue;
int intValue;
double doubleValue;
};
UT_hash_handle hh; ///< UT Hash handle
} CFG_ITEM, *PCFG_ITEM;
typedef void (*OnCfgMsg)(DBUS_CMD cmd, PCFG_ITEM pMsg, int err);
int CfgGlobalEnvInit(void);
void CfgItemPrint(const char* pPrefix, PCFG_ITEM pCfgItem);
int CfgGetKeyValue(const char* pKeyName, PCFG_ITEM* pItem);
int CfgChangeKeyValue(const char *pKeyName, PCFG_ITEM pItem, int saveToDB);
int CfgAddKeyValue(const char *pKeyName, PCFG_ITEM pItem, int saveToDB);
void CfgSetIntValue(const char* pTags, int iValue);
void OnCfgMsgProcess(MODULE_NAME dest, DBUS_CMD busCmd, const char *pJsonStr);
int Sqlite3SyncDB(sqlite3* pSqlMemory, const char* pMemDbName, const char* pDBFilePath, const char* pFileDbName, int isSave);
#ifdef __cplusplus
}
#endif
#endif

81
include/crypto.h Normal file
View File

@ -0,0 +1,81 @@
#ifndef CRYPTO_H
#define CRYPTO_H
#include <openssl/aes.h>
#include <openssl/evp.h>
#ifdef __cplusplus
extern "C" {
#endif
#define ALIGN_AES_BLOCK(size) (((size + AES_BLOCK_SIZE - 1) / AES_BLOCK_SIZE) * AES_BLOCK_SIZE)
#define MD5_VALUE_LEN (16)
#define MD5_STR_VALUE_LEN (MD5_VALUE_LEN * 2)
typedef enum
{
CRYPTO_AES_ENCRYPT = 0,
CRYPTO_AES_DECRYPT,
CRYPTO_BASE64_ENCODE,
CRYPTO_BASE64_DECODE,
CRYPTO_MD5_FILE,
} CRYPTO_TYPE;
void EvpSystemInit(void);
//*****************************************************
// AES
//*****************************************************
typedef void (*OnEVPCrypto)(CRYPTO_TYPE type,
const unsigned char* pData,
int iSize,
const unsigned char* pSrcData,
int iError);
int EvpAESEncrypto(unsigned char* pInBuf,
int iSize,
unsigned char* pOutBuf,
int* pOutSize,
unsigned char* pKey);
int EvpAESDecrypto(unsigned char* pInBuf,
int iSize,
unsigned char* pOutBuf,
int* pOutSize,
unsigned char* pKey);
//*****************************************************
// BASE64
//*****************************************************
const char* EvpBase64Encode(const char* pSrc);
const char* EvpBase64Decode(const char* pBase64);
const char* EvpBase64EncodeNoAlign(const char *pSrc);
const char* EvpBase64DecodeNoAlign(const char *pBase64);
const char* EvpBase64EncodeNoAlignV2(unsigned char *pSrc, int sLen);
unsigned char* EvpBase64DecodeNoAlignV2(const char *pBase64, int *pOutSize);
//*****************************************************
// MD5
//*****************************************************
const char* EvpMD5HashFile(const char* pFileName);
int EvpMD5HashFileV2(const char *pFileName, unsigned char md5[16]);;
int EvpMD5HashBuf(const unsigned char *pBuf, int iBufLen, unsigned char *pOutBuf, int *pOutSize);
const char* EvpMD5HashBufV2(const unsigned char *pBuf, int iBufLen);
//*****************************************************
// Async Engine
//*****************************************************
int EvpAddCryptoTask(CRYPTO_TYPE type,
unsigned char* pInBuf,
int iSize,
unsigned char* pOutBuf,
char* pKey,
OnEVPCrypto onEvpCryptCb);
//*****************************************************
// Compress
//*****************************************************
int GZipFileCompress(const char *pInput, const char *pOutput);
#ifdef __cplusplus
}
#endif
#endif

724
include/fifo.h Normal file
View File

@ -0,0 +1,724 @@
/*
* A generic kernel FIFO implementation
*
* Copyright (C) 2009/2010 Stefani Seibold <stefani@seibold.net>
*
* 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.
*
*/
#ifndef FIFO_H
#define FIFO_H
#include <uv.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
#define __must_check __attribute__((warn_unused_result))
/*
* How to porting drivers to the new generic FIFO API:
*
* - Modify the declaration of the "struct kfifo *" object into a
* in-place "struct kfifo" object
* - Init the in-place object with kfifo_alloc() or kfifo_init()
* Note: The address of the in-place "struct kfifo" object must be
* passed as the first argument to this functions
* - Replace the use of __kfifo_put into kfifo_in and __kfifo_get
* into kfifo_out
* - Replace the use of kfifo_put into kfifo_in_spinlocked and kfifo_get
* into kfifo_out_spinlocked
* Note: the spinlock pointer formerly passed to kfifo_init/kfifo_alloc
* must be passed now to the kfifo_in_spinlocked and kfifo_out_spinlocked
* as the last parameter
* - The formerly __kfifo_* functions are renamed into kfifo_*
*/
/*
* Note about locking : There is no locking required until only * one reader
* and one writer is using the fifo and no kfifo_reset() will be * called
* kfifo_reset_out() can be safely used, until it will be only called
* in the reader thread.
* For multiple writer and one reader there is only a need to lock the writer.
* And vice versa for only one writer and multiple reader there is only a need
* to lock the reader.
*/
struct __kfifo {
unsigned int in;
unsigned int out;
unsigned int mask;
unsigned int esize;
void *data;
uv_mutex_t lock;
};
#define __STRUCT_KFIFO_COMMON(datatype, recsize, ptrtype) \
union { \
struct __kfifo kfifo; \
datatype *type; \
char (*rectype)[recsize]; \
ptrtype *ptr; \
const ptrtype *ptr_const; \
}
#define __STRUCT_KFIFO(type, size, recsize, ptrtype) \
{ \
__STRUCT_KFIFO_COMMON(type, recsize, ptrtype); \
type buf[((size < 2) || (size & (size - 1))) ? -1 : size]; \
}
#define STRUCT_KFIFO(type, size) \
struct __STRUCT_KFIFO(type, size, 0, type)
#define __STRUCT_KFIFO_PTR(type, recsize, ptrtype) \
{ \
__STRUCT_KFIFO_COMMON(type, recsize, ptrtype); \
type buf[0]; \
}
#define STRUCT_KFIFO_PTR(type) \
struct __STRUCT_KFIFO_PTR(type, 0, type)
/*
* define compatibility "struct kfifo" for dynamic allocated fifos
*/
struct kfifo __STRUCT_KFIFO_PTR(unsigned char, 0, void);
#define STRUCT_KFIFO_REC_1(size) \
struct __STRUCT_KFIFO(unsigned char, size, 1, void)
#define STRUCT_KFIFO_REC_2(size) \
struct __STRUCT_KFIFO(unsigned char, size, 2, void)
/*
* define kfifo_rec types
*/
struct kfifo_rec_ptr_1 __STRUCT_KFIFO_PTR(unsigned char, 1, void);
struct kfifo_rec_ptr_2 __STRUCT_KFIFO_PTR(unsigned char, 2, void);
/*
* helper macro to distinguish between real in place fifo where the fifo
* array is a part of the structure and the fifo type where the array is
* outside of the fifo structure.
*/
#define __is_kfifo_ptr(fifo) (sizeof(*fifo) == sizeof(struct __kfifo))
/**
* DECLARE_KFIFO_PTR - macro to declare a fifo pointer object
* @fifo: name of the declared fifo
* @type: type of the fifo elements
*/
#define DECLARE_KFIFO_PTR(fifo, type) STRUCT_KFIFO_PTR(type) fifo
/**
* DECLARE_KFIFO - macro to declare a fifo object
* @fifo: name of the declared fifo
* @type: type of the fifo elements
* @size: the number of elements in the fifo, this must be a power of 2
*/
#define DECLARE_KFIFO(fifo, type, size) STRUCT_KFIFO(type, size) fifo
/**
* INIT_KFIFO - Initialize a fifo declared by DECLARE_KFIFO
* @fifo: name of the declared fifo datatype
*/
#define INIT_KFIFO(fifo) \
(void)({ \
typeof(&(fifo)) __tmp = &(fifo); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
__kfifo->in = 0; \
__kfifo->out = 0; \
__kfifo->mask = __is_kfifo_ptr(__tmp) ? 0 : ARRAY_SIZE(__tmp->buf) - 1;\
__kfifo->esize = sizeof(*__tmp->buf); \
__kfifo->data = __is_kfifo_ptr(__tmp) ? NULL : __tmp->buf; \
})
/**
* DEFINE_KFIFO - macro to define and initialize a fifo
* @fifo: name of the declared fifo datatype
* @type: type of the fifo elements
* @size: the number of elements in the fifo, this must be a power of 2
*
* Note: the macro can be used for global and local fifo data type variables.
*/
#define DEFINE_KFIFO(fifo, type, size) \
DECLARE_KFIFO(fifo, type, size) = \
(typeof(fifo)) { \
{ \
{ \
.in = 0, \
.out = 0, \
.mask = __is_kfifo_ptr(&(fifo)) ? \
0 : \
ARRAY_SIZE((fifo).buf) - 1, \
.esize = sizeof(*(fifo).buf), \
.data = __is_kfifo_ptr(&(fifo)) ? \
NULL : \
(fifo).buf, \
} \
} \
}
static inline unsigned int __must_check
__kfifo_uint_must_check_helper(unsigned int val)
{
return val;
}
static inline int __must_check
__kfifo_int_must_check_helper(int val)
{
return val;
}
/**
* kfifo_initialized - Check if the fifo is initialized
* @fifo: address of the fifo to check
*
* Return %true if fifo is initialized, otherwise %false.
* Assumes the fifo was 0 before.
*/
#define kfifo_initialized(fifo) ((fifo)->kfifo.mask)
/**
* kfifo_esize - returns the size of the element managed by the fifo
* @fifo: address of the fifo to be used
*/
#define kfifo_esize(fifo) ((fifo)->kfifo.esize)
/**
* kfifo_recsize - returns the size of the record length field
* @fifo: address of the fifo to be used
*/
#define kfifo_recsize(fifo) (sizeof(*(fifo)->rectype))
/**
* kfifo_size - returns the size of the fifo in elements
* @fifo: address of the fifo to be used
*/
#define kfifo_size(fifo) ((fifo)->kfifo.mask + 1)
/**
* kfifo_reset - removes the entire fifo content
* @fifo: address of the fifo to be used
*
* Note: usage of kfifo_reset() is dangerous. It should be only called when the
* fifo is exclusived locked or when it is secured that no other thread is
* accessing the fifo.
*/
#define kfifo_reset(fifo) \
(void)({ \
typeof((fifo) + 1) __tmp = (fifo); \
__tmp->kfifo.in = __tmp->kfifo.out = 0; \
})
/**
* kfifo_reset_out - skip fifo content
* @fifo: address of the fifo to be used
*
* Note: The usage of kfifo_reset_out() is safe until it will be only called
* from the reader thread and there is only one concurrent reader. Otherwise
* it is dangerous and must be handled in the same way as kfifo_reset().
*/
#define kfifo_reset_out(fifo) \
(void)({ \
typeof((fifo) + 1) __tmp = (fifo); \
__tmp->kfifo.out = __tmp->kfifo.in; \
})
/**
* kfifo_len - returns the number of used elements in the fifo
* @fifo: address of the fifo to be used
*/
#define kfifo_len(fifo) \
({ \
typeof((fifo) + 1) __tmpl = (fifo); \
__tmpl->kfifo.in - __tmpl->kfifo.out; \
})
/**
* kfifo_is_empty - returns true if the fifo is empty
* @fifo: address of the fifo to be used
*/
#define kfifo_is_empty(fifo) \
({ \
typeof((fifo) + 1) __tmpq = (fifo); \
__tmpq->kfifo.in == __tmpq->kfifo.out; \
})
/**
* kfifo_is_full - returns true if the fifo is full
* @fifo: address of the fifo to be used
*/
#define kfifo_is_full(fifo) \
({ \
typeof((fifo) + 1) __tmpq = (fifo); \
kfifo_len(__tmpq) > __tmpq->kfifo.mask; \
})
/**
* kfifo_avail - returns the number of unused elements in the fifo
* @fifo: address of the fifo to be used
*/
#define kfifo_avail(fifo) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmpq = (fifo); \
const unsigned int __recsize = sizeof(*__tmpq->rectype); \
unsigned int __avail = kfifo_size(__tmpq) - kfifo_len(__tmpq); \
(__recsize) ? ((__avail <= __recsize) ? 0 : \
__kfifo_max_r(__avail - __recsize, __recsize)) : \
__avail; \
}) \
)
/**
* kfifo_skip - skip output data
* @fifo: address of the fifo to be used
*/
#define kfifo_skip(fifo) \
(void)({ \
typeof((fifo) + 1) __tmp = (fifo); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (__recsize) \
__kfifo_skip_r(__kfifo, __recsize); \
else \
__kfifo->out++; \
})
/**
* kfifo_peek_len - gets the size of the next fifo record
* @fifo: address of the fifo to be used
*
* This function returns the size of the next fifo record in number of bytes.
*/
#define kfifo_peek_len(fifo) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
(!__recsize) ? kfifo_len(__tmp) * sizeof(*__tmp->type) : \
__kfifo_len_r(__kfifo, __recsize); \
}) \
)
/**
* kfifo_alloc - dynamically allocates a new fifo buffer
* @fifo: pointer to the fifo
* @size: the number of elements in the fifo, this must be a power of 2
* @gfp_mask: get_free_pages mask, passed to kmalloc()
*
* This macro dynamically allocates a new fifo buffer.
*
* The numer of elements will be rounded-up to a power of 2.
* The fifo will be release with kfifo_free().
* Return 0 if no error, otherwise an error code.
*/
#define kfifo_alloc(fifo, size) \
__kfifo_int_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
__is_kfifo_ptr(__tmp) ? \
__kfifo_alloc(__kfifo, size, sizeof(*__tmp->type)) : \
-EINVAL; \
}) \
)
/**
* kfifo_free - frees the fifo
* @fifo: the fifo to be freed
*/
#define kfifo_free(fifo) \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (__is_kfifo_ptr(__tmp)) \
__kfifo_free(__kfifo); \
})
/**
* kfifo_init - initialize a fifo using a preallocated buffer
* @fifo: the fifo to assign the buffer
* @buffer: the preallocated buffer to be used
* @size: the size of the internal buffer, this have to be a power of 2
*
* This macro initialize a fifo using a preallocated buffer.
*
* The numer of elements will be rounded-up to a power of 2.
* Return 0 if no error, otherwise an error code.
*/
#define kfifo_init(fifo, buffer, size) \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
__is_kfifo_ptr(__tmp) ? \
__kfifo_init(__kfifo, buffer, size, sizeof(*__tmp->type)) : \
-EINVAL; \
})
/**
* kfifo_put - put data into the fifo
* @fifo: address of the fifo to be used
* @val: the data to be added
*
* This macro copies the given value into the fifo.
* It returns 0 if the fifo was full. Otherwise it returns the number
* processed elements.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_put(fifo, val) \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
typeof((val) + 1) __val = (val); \
unsigned int __ret; \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (0) { \
typeof(__tmp->ptr_const) __dummy __attribute__ ((unused)); \
__dummy = (typeof(__val))NULL; \
} \
if (__recsize) \
__ret = __kfifo_in_r(__kfifo, __val, sizeof(*__val), \
__recsize); \
else { \
__ret = !kfifo_is_full(__tmp); \
if (__ret) { \
(__is_kfifo_ptr(__tmp) ? \
((typeof(__tmp->type))__kfifo->data) : \
(__tmp->buf) \
)[__kfifo->in & __tmp->kfifo.mask] = \
*(typeof(__tmp->type))__val; \
__kfifo->in++; \
} \
} \
__ret; \
})
/**
* kfifo_get - get data from the fifo
* @fifo: address of the fifo to be used
* @val: the var where to store the data to be added
*
* This macro reads the data from the fifo.
* It returns 0 if the fifo was empty. Otherwise it returns the number
* processed elements.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_get(fifo, val) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
typeof((val) + 1) __val = (val); \
unsigned int __ret; \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (0) \
__val = (typeof(__tmp->ptr))0; \
if (__recsize) \
__ret = __kfifo_out_r(__kfifo, __val, sizeof(*__val), \
__recsize); \
else { \
__ret = !kfifo_is_empty(__tmp); \
if (__ret) { \
*(typeof(__tmp->type))__val = \
(__is_kfifo_ptr(__tmp) ? \
((typeof(__tmp->type))__kfifo->data) : \
(__tmp->buf) \
)[__kfifo->out & __tmp->kfifo.mask]; \
__kfifo->out++; \
} \
} \
__ret; \
}) \
)
/**
* kfifo_peek - get data from the fifo without removing
* @fifo: address of the fifo to be used
* @val: the var where to store the data to be added
*
* This reads the data from the fifo without removing it from the fifo.
* It returns 0 if the fifo was empty. Otherwise it returns the number
* processed elements.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_peek(fifo, val) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
typeof((val) + 1) __val = (val); \
unsigned int __ret; \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (0) \
__val = (typeof(__tmp->ptr))NULL; \
if (__recsize) \
__ret = __kfifo_out_peek_r(__kfifo, __val, sizeof(*__val), \
__recsize); \
else { \
__ret = !kfifo_is_empty(__tmp); \
if (__ret) { \
*(typeof(__tmp->type))__val = \
(__is_kfifo_ptr(__tmp) ? \
((typeof(__tmp->type))__kfifo->data) : \
(__tmp->buf) \
)[__kfifo->out & __tmp->kfifo.mask]; \
} \
} \
__ret; \
}) \
)
/**
* kfifo_in - put data into the fifo
* @fifo: address of the fifo to be used
* @buf: the data to be added
* @n: number of elements to be added
*
* This macro copies the given buffer into the fifo and returns the
* number of copied elements.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_in(fifo, buf, n) \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
typeof((buf) + 1) __buf = (buf); \
unsigned long __n = (n); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (0) { \
typeof(__tmp->ptr_const) __dummy __attribute__ ((unused)); \
__dummy = (typeof(__buf))NULL; \
} \
(__recsize) ?\
__kfifo_in_r(__kfifo, __buf, __n, __recsize) : \
__kfifo_in(__kfifo, __buf, __n); \
})
/**
* kfifo_in_spinlocked - put data into the fifo using a spinlock for locking
* @fifo: address of the fifo to be used
* @buf: the data to be added
* @n: number of elements to be added
* @lock: pointer to the spinlock to use for locking
*
* This macro copies the given values buffer into the fifo and returns the
* number of copied elements.
*/
#define kfifo_in_locked(fifo, buf, n) \
({ \
unsigned int __ret; \
uv_mutex_t __lock = ((struct __kfifo*)fifo)->lock; \
uv_mutex_lock(&__lock); \
__ret = kfifo_in(fifo, buf, n); \
uv_mutex_unlock(&__lock); \
__ret; \
})
/**
* kfifo_out - get data from the fifo
* @fifo: address of the fifo to be used
* @buf: pointer to the storage buffer
* @n: max. number of elements to get
*
* This macro get some data from the fifo and return the numbers of elements
* copied.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_out(fifo, buf, n) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
typeof((buf) + 1) __buf = (buf); \
unsigned long __n = (n); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (0) { \
typeof(__tmp->ptr) __dummy = NULL; \
__buf = __dummy; \
} \
(__recsize) ?\
__kfifo_out_r(__kfifo, __buf, __n, __recsize) : \
__kfifo_out(__kfifo, __buf, __n); \
}) \
)
/**
* kfifo_out_spinlocked - get data from the fifo using a spinlock for locking
* @fifo: address of the fifo to be used
* @buf: pointer to the storage buffer
* @n: max. number of elements to get
* @lock: pointer to the spinlock to use for locking
*
* This macro get the data from the fifo and return the numbers of elements
* copied.
*/
#define kfifo_out_locked(fifo, buf, n) \
__kfifo_uint_must_check_helper( \
({ \
unsigned int __ret; \
uv_mutex_t __lock = ((struct __kfifo*)fifo)->lock; \
uv_mutex_lock(&__lock); \
__ret = kfifo_out(fifo, buf, n); \
uv_mutex_unlock(&__lock); \
__ret; \
}) \
)
/**
* kfifo_from_user - puts some data from user space into the fifo
* @fifo: address of the fifo to be used
* @from: pointer to the data to be added
* @len: the length of the data to be added
* @copied: pointer to output variable to store the number of copied bytes
*
* This macro copies at most @len bytes from the @from into the
* fifo, depending of the available space and returns -EFAULT/0.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_from_user(fifo, from, len, copied) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
const void __user *__from = (from); \
unsigned int __len = (len); \
unsigned int *__copied = (copied); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
(__recsize) ? \
__kfifo_from_user_r(__kfifo, __from, __len, __copied, __recsize) : \
__kfifo_from_user(__kfifo, __from, __len, __copied); \
}) \
)
/**
* kfifo_to_user - copies data from the fifo into user space
* @fifo: address of the fifo to be used
* @to: where the data must be copied
* @len: the size of the destination buffer
* @copied: pointer to output variable to store the number of copied bytes
*
* This macro copies at most @len bytes from the fifo into the
* @to buffer and returns -EFAULT/0.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_to_user(fifo, to, len, copied) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
void __user *__to = (to); \
unsigned int __len = (len); \
unsigned int *__copied = (copied); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
(__recsize) ? \
__kfifo_to_user_r(__kfifo, __to, __len, __copied, __recsize) : \
__kfifo_to_user(__kfifo, __to, __len, __copied); \
}) \
)
/**
* kfifo_out_peek - gets some data from the fifo
* @fifo: address of the fifo to be used
* @buf: pointer to the storage buffer
* @n: max. number of elements to get
*
* This macro get the data from the fifo and return the numbers of elements
* copied. The data is not removed from the fifo.
*
* Note that with only one concurrent reader and one concurrent
* writer, you don't need extra locking to use these macro.
*/
#define kfifo_out_peek(fifo, buf, n) \
__kfifo_uint_must_check_helper( \
({ \
typeof((fifo) + 1) __tmp = (fifo); \
typeof((buf) + 1) __buf = (buf); \
unsigned long __n = (n); \
const unsigned int __recsize = sizeof(*__tmp->rectype); \
struct __kfifo *__kfifo = &__tmp->kfifo; \
if (0) { \
typeof(__tmp->ptr) __dummy __attribute__ ((unused)) = NULL; \
__buf = __dummy; \
} \
(__recsize) ? \
__kfifo_out_peek_r(__kfifo, __buf, __n, __recsize) : \
__kfifo_out_peek(__kfifo, __buf, __n); \
}) \
)
#define kfifo_peek_locked(fifo, buf, n) \
__kfifo_uint_must_check_helper( \
({ \
unsigned int __ret; \
uv_mutex_t __lock = ((struct __kfifo*)fifo)->lock; \
uv_mutex_lock(&__lock); \
__ret = kfifo_out_peek(fifo, buf, n); \
uv_mutex_unlock(&__lock); \
__ret; \
}) \
)
extern int __kfifo_alloc(struct __kfifo *fifo, unsigned int size, unsigned int esize);
extern void __kfifo_free(struct __kfifo *fifo);
extern int __kfifo_init(struct __kfifo *fifo, void *buffer,
unsigned int size, unsigned int esize);
extern unsigned int __kfifo_in(struct __kfifo *fifo,
const void *buf, unsigned int len);
extern unsigned int __kfifo_out(struct __kfifo *fifo,
void *buf, unsigned int len);
extern unsigned int __kfifo_out_peek(struct __kfifo *fifo,
void *buf, unsigned int len);
extern unsigned int __kfifo_in_r(struct __kfifo *fifo,
const void *buf, unsigned int len, unsigned int recsize);
extern unsigned int __kfifo_out_r(struct __kfifo *fifo,
void *buf, unsigned int len, unsigned int recsize);
extern unsigned int __kfifo_len_r(struct __kfifo *fifo, unsigned int recsize);
extern void __kfifo_skip_r(struct __kfifo *fifo, unsigned int recsize);
extern unsigned int __kfifo_out_peek_r(struct __kfifo *fifo,
void *buf, unsigned int len, unsigned int recsize);
extern unsigned int __kfifo_max_r(unsigned int len, unsigned int recsize);
#endif

51
include/inet_api.h Normal file
View File

@ -0,0 +1,51 @@
#ifndef INET_API_H
#define INET_API_H
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_HTTP_POST_SIZE (1024)
typedef struct HTTP_POST_ATTACH
{
char keyName[64];
char keyValue[MAX_HTTP_POST_SIZE];
struct HTTP_POST_ATTACH *next, *prev;
} *PHTTP_POST_ATTACH;
typedef struct
{
char *pUserName;
char *pPassword;
char *pSmtpServer;
short smtpPort;
} SMTP_MAIL_CONFIG, *PSMTP_MAIL_CONFIG;
int InetSmtpSendEmail(const char *pFrom,
const char *pTo[],
const char *pCc[],
const char *pTitle,
const char *pMessage,
const char *pAttach[],
PSMTP_MAIL_CONFIG pConfig);
#define InetHttpsDownloadFile(pURL, pPath, onRespCb, onPrgCb) InetHttpDlFileAsync(pURL, pPath, onRespCb, onPrgCb)
#define InetHttpsWebServicePost(pURL, pPost, onRespCb) InetHttpWebServicePostAsync(pURL, pPost, onRespCb)
int InetCancelDownload(const char *pTaskUuid);
typedef void (*OnHttpResponse)(void* pData, unsigned int size, const char* pReqUrl, const char* pDlPath, const char* pTaskUuid, int iFinished, void* pUserData);
typedef void (*OnProgressNotify)(const char* pReqUrl, const char* pTaskUuid, unsigned char uPercent, void* pUserData);
int InetInit(void);
void InetUnInit(void);
const char* InetHttpDlFileAsync(const char*, const char*, OnHttpResponse, OnProgressNotify, void*);
const char* InetHttpWebServicePostAsync(const char *pURL, const char *pPost, OnHttpResponse onRespCb, void *pData);
int InetHttpUploadFileSync(const char *pURL, const char* pPath, void* pAttachInfo);
//int InetSmtpSendEmail(void);
#ifdef __cplusplus
}
#endif
#endif

150
include/json_struct.h Normal file
View File

@ -0,0 +1,150 @@
#ifndef JSON_STRUCT_H
#define JSON_STRUCT_H
#include <cjson/s2j.h>
#include "smart_sound.h"
#ifdef __cplusplus
extern "C" {
#endif
#define MAX_MUSIC_UUID (256)
#define MAX_MUSIC_URL (2048)
typedef enum
{
//******************************************
// Player <--> Controller
//******************************************
JSON_ENGINE_P2C = 0,
JSON_ENGINE_C2P,
//******************************************
// Configure Req & Rsp
//******************************************
JSON_ENGINE_CFG_REQ,
JSON_ENGINE_CFG_RSP,
//******************************************
// Alarm Req & Rsp
//******************************************
JSON_ENGINE_ASSISTANT_SYNC_RSP,
JSON_ENGINE_ASSISTANT_NOTIFY,
JSON_ENGINE_ASSISTANT_STATUS,
JSON_ENGINE_ASSISTANT_RUNNING,
//******************************************
// Work Day API Req & Rsp
//******************************************
JSON_ENGINE_WORKDAY_REQ,
//******************************************
// PING Cmd
//******************************************
JSON_ENGINE_PING,
//******************************************
// OTA Cmd
//******************************************
JSON_ENGINE_OTA_REQ,
JSON_ENGINE_OTA_RSP,
//******************************************
// LOG System Configure Cmd
//******************************************
JSON_ENGINE_LOG_CFG_CMD,
//******************************************
// WIFI Status Changed Nofify Cmd
//******************************************
JSON_WIFI_STATUS_NOTIFY,
//******************************************
// mcu test Cmd
//******************************************
JSON_MCU_GUIDE_TEST_CMD,
JSON_MCU_MATRIX_TEST_CMD,
JSON_MCU_TEST_GET_VER_CMD,
JSON_ENGINE_MAX,
} JSON_ENGINE_TYPE;
typedef struct
{
uint32_t playerId;
char musicUuid[MAX_MUSIC_UUID];
int plySt;
uint32_t curPos;
uint32_t duration;
} PLAYER_TO_CTRL, *PPLAYER_TO_CTRL;
typedef struct
{
uint32_t playerId;
char src[MAX_MUSIC_URL];
char srcUuid[MAX_MUSIC_URL];
char ttsText[MAX_MUSIC_UUID * 2];
int skTime;
int plyMode;
int plyListType;
char adSrcType;
int duration;
int volRestoreTime;
char volBegin;
float gain;
char fifo[MAX_MUSIC_UUID];
char channel;
char bytes;
int sampleRate;
char backGroundUrl[MAX_MUSIC_URL];
} CTRL_TO_PLAYER, *PCTRL_TO_PLAYER;
typedef struct
{
char keyName[MAX_CFG_KEY_NAME];
char keyValue[MAX_CFG_KEY_VALUE];
int keyType;
} CFG_API_REQ, *PCFG_API_REQ;
typedef struct
{
int red;
int green;
int blue;
} MCU_TEST_GUIDE_CMD, *PMCU_TEST_GUIDE_CMD;
typedef struct
{
int level;
} MCU_TEST_MATRIX_CMD, *PMCU_TEST_MATRIX_CMD;
typedef struct
{
char McuVer[16];
} MCU_TEST_VER_CMD, *PMCU_TEST_VER_CMD;
typedef struct
{
char keyName[MAX_CFG_KEY_NAME];
char keyValue[MAX_CFG_KEY_VALUE];
int keyType;
int errNo;
} CFG_API_RSP, *PCFG_API_RSP;
typedef struct
{
double PING;
int tmSec;
int tmMSec;
} PING_MSG, *PPING_MSG;
void* Json2Struct(const char* pJsonStr, JSON_ENGINE_TYPE type, int enBase64, int* pErr);
const char* Struct2Json(void* pStruct, JSON_ENGINE_TYPE type, int enBase64, int* pErr);
#ifdef __cplusplus
}
#endif
#endif

225
include/libuv_dbus.h Normal file
View File

@ -0,0 +1,225 @@
#ifndef LIBUV_DEBUS_H
#define LIBUV_DEBUS_H
#include "smart_sound.h"
#include <uv.h>
#include <dbus/dbus.h>
#include "json_struct.h"
#include "config_engine.h"
#ifdef __cplusplus
extern "C" {
#endif
#define SAFE_STRING_VALUE(s) (s ? s : "")
#define R16_TINA_KEY_EVENT_PATH ("/dev/input/event2")
#define DBUS_MESSAGE_INTERFACE_NAME "netease.ihw.SmartAudio"
#define DBUS_PATH_HEAD "/netease/ihw/"
#define DBUS_INTERFACE_HEAD "netease.ihw."
#define DBUS_MSG_MAX_PAD_SIZE (1024 * 1024 * 2)
#define LIBUV_CURRENT_TIME_S() (uv_hrtime() / 1000000000)
#define LIBUV_CURRENT_TIME_MS() (uv_hrtime() / 1000000)
#define LIBUV_CURRENT_TIME_US() (uv_hrtime() / 1000)
#define MODULE_ALIAS_NAME(i) (strrchr(g_pModInfoTable[i].modAliase, '.') + 1)
#define HEART_SEND_DELAY (5000)
#define HEART_LOST_DELAY (20000)
typedef enum
{
WIFI_CONNECTED = 0,
WIFI_DISCONNECTED = 1,
} WIFI_STATUS;
typedef struct
{
int wifi_evt;
} WIFI_STATUS_PRO, *PWIFI_STATUS_PRO;
typedef struct
{
int year;
unsigned char days[366];
} WORKDAY_INFO, *PWORKDAY_INFO;
typedef struct
{
int32_t msgSrc; ///< message who send
uint32_t msgDests; ///< who need receive message(not only one)
#if USED_SHM_TO_DBUS
uint32_t tmTickMSec; ///< timestamp of second
#endif
uint32_t busCmd; ///< command of message
uint32_t msgSize; ///< how many bytes of this message
uint32_t msgKey; ///< share key for copy large message
char* pMsg; ///< message context if has
int isBstMsg;
} DBUS_MSG_PACK, *PDBUS_MSG_PACK;
typedef struct DBUS_MSG_PROC
{
int msgFrom; ///< 0: Boardcast Msg, 1: P2P Message
DBUS_MSG_PACK msgContent;
struct DBUS_MSG_PROC *next, *prev;
} *PDBUS_MSG_PROC;
typedef void (*OnDBusAsyncSendTo)(int err);
typedef PDBUS_MSG_PACK (*OnDBusMessage)(uv_loop_t* pLoop, DBusConnection* pConn, PDBUS_MSG_PACK pMsg);
typedef void (*OnDaemonMsg)(MODULE_NAME modName, int status);
typedef void (*OnKeyEvent)(uint16_t uType, uint16_t uKey, int32_t iValue);
typedef struct
{
MODULE_NAME modName; ///< Module Name
const char* modPath; ///< Attach to dbus path
const char* modAliase; ///< Attach to dbus bus name
} MOD_INFO_TABLE, *PMOD_INFO_TABLE;
typedef struct
{
uv_loop_t* pLoop; ///< libuv default main loop
uv_loop_t* pUserLoop; ///< libuv user main loop
DBusConnection* pBus; ///< D-Bus object
MODULE_NAME modName; ///< Process name
const char* pBusName; ///< D-Bus object's interface name
const char* pBusPath; ///< D-Bus object's path name
OnDBusMessage onMsgCb; ///< D-Bus receive message callback
OnKeyEvent onKeyCb; ///< Keyboard event callback
OnDaemonMsg onHblCb; ///< Process HBL event callback
OnCfgMsg onCfgCb; ///< Configure message callback
// unsigned int uDaemon[MODULE_MAX]; ///< Daemon Service
} LIBUV_DBUS_PARAMS, *PLIBUV_DBUS_PARAMS;
static MOD_INFO_TABLE g_pModInfoTable[] =
{
{MODULE_CONTROLLER, DBUS_PATH_HEAD"controller", DBUS_INTERFACE_HEAD"controller"},
{MODULE_ALARM, DBUS_PATH_HEAD"alarm", DBUS_INTERFACE_HEAD"alarm"},
{MODULE_CALL, DBUS_PATH_HEAD"call", DBUS_INTERFACE_HEAD"call"},
{MODULE_VOICEENGINE, DBUS_PATH_HEAD"voice_engine", DBUS_INTERFACE_HEAD"voice_engine"},
{MODULE_PLAYER, DBUS_PATH_HEAD"player", DBUS_INTERFACE_HEAD"player"},
{MODULE_CONFIGURE, DBUS_PATH_HEAD"config", DBUS_INTERFACE_HEAD"config"},
{MODULE_OTA, DBUS_PATH_HEAD"ota", DBUS_INTERFACE_HEAD"ota"},
{MODULE_WIFI, DBUS_PATH_HEAD"wifi", DBUS_INTERFACE_HEAD"wifi"},
{MODULE_BT, DBUS_PATH_HEAD"bt", DBUS_INTERFACE_HEAD"bt"},
{MODULE_KPLAYER, DBUS_PATH_HEAD"kplayer", DBUS_INTERFACE_HEAD"kplayer"},
{MODULE_KPLAYER_TEST, DBUS_PATH_HEAD"kplayerTest", DBUS_INTERFACE_HEAD"kplayerTest"},
{MODULE_SPLAYER, DBUS_PATH_HEAD"splayer", DBUS_INTERFACE_HEAD"splayer"},
{MODULE_SPLAYER_TEST, DBUS_PATH_HEAD"splayerTest", DBUS_INTERFACE_HEAD"splayerTest"},
{MODULE_LIGHT_MCU, DBUS_PATH_HEAD"light_mcu", DBUS_INTERFACE_HEAD"light_mcu"},
{MODULE_BLUEKC, DBUS_PATH_HEAD"blukc", DBUS_INTERFACE_HEAD"blukc"},
{MODULE_BLUEKC_TEST, DBUS_PATH_HEAD"bluekcTest", DBUS_INTERFACE_HEAD"bluekcTest"},
{MODULE_MANUFACTURE, DBUS_PATH_HEAD"manufacture", DBUS_INTERFACE_HEAD"manufacture"},
{MODULE_BT_DEMO, DBUS_PATH_HEAD"btdemo", DBUS_INTERFACE_HEAD"btdemo"},
{MODULE_SKINS, DBUS_PATH_HEAD"skins", DBUS_INTERFACE_HEAD"skins"},
{MODULE_LOG_CTRL, DBUS_PATH_HEAD"logCtrl", DBUS_INTERFACE_HEAD"logCtrl"},
{MODULE_WIRELESSTEST, DBUS_PATH_HEAD"wirelessTest", DBUS_INTERFACE_HEAD"wirelessTest"},
{MODULE_WIRELESSTEST_DEMO, DBUS_PATH_HEAD"wirelessTestDemo", DBUS_INTERFACE_HEAD"wirelessTestDemo"},
{MODULE_MANUFACTURE_CONTROLLER, DBUS_PATH_HEAD"manufacture_controller", DBUS_INTERFACE_HEAD"manufacture_controller"},
{MODULE_WIFI_DEMO, DBUS_PATH_HEAD"wifiDemo", DBUS_INTERFACE_HEAD"wifiDemo"},
};
PLIBUV_DBUS_PARAMS DBusLibuvGetRuntime(void);
MODULE_NAME DBusLibGetModName(void);
uv_loop_t* GetDBusDefaultLoop(void);
void RunUVLoop(uv_loop_t *pLoop);
PDBUS_MSG_PACK DBusGetMessage(void);
void DBusMsgCleanup(PDBUS_MSG_PACK pMsg);
DBusConnection* DBusWithLibuvInit(uv_loop_t* pUserLoop,
const char* pBusName,
OnDBusMessage cbOnMsg,
OnDaemonMsg cbOnHbl,
OnKeyEvent cbOnKey,
int* pErrno);
int DBusJsonSendToCommandAsync(DBusConnection* pBus,
const char* pBusName,
uint32_t busCmd,
JSON_ENGINE_TYPE type,
void* pStruct,
int iSize,
OnDBusAsyncSendTo cbSendTo,
int enBase64);
int DBusJsonSendToCommand(DBusConnection* pBus,
const char* pBusName,
uint32_t busCmd,
JSON_ENGINE_TYPE type,
void* pStruct,
int enBase64);
int DBusJsonBoardcastCommand(DBusConnection* pBus,
uint32_t msgToMask,
uint32_t busCmd,
JSON_ENGINE_TYPE type,
void* pStruct,
int enBase64);
int DBusBoardcastCommand(DBusConnection *pBus,
uint32_t msgToMask,
uint32_t busCmd,
const char *pContext);
int DBusSendToCommand(DBusConnection *pBus,
const char *pBusName,
uint32_t busCmd,
const char *pContext);
void HeartDaemonUpgrade(int iWatcher);
void HeartDaemonInit(MODULE_NAME mod, int msHblTout, OnDaemonMsg cb);
void HeartDaemonHblCheck(void);
int DBusWithLibuvCfgInit(OnCfgMsg cbOnCfgMsg);
int GetShellExecResult(const char *pCmd, char **pResult);
int CopyFile(const char *pSrc, const char *pDest);
int CopyFileWithSize(const char *pSrc, const char *pDest, int iSize);
int ReadFileToBuf(const char *pSrc, unsigned char *pBuf, int iSize);
void SystemSafeReboot(void);
typedef void (*OnAlarmTimer)(unsigned int tmId, unsigned int status, void* pUserData);
int AlarmTimerInit(uv_loop_t *pLoop);
int AlarmTimerCleanup(void);
int AlarmTimerRemove(unsigned int tmId);
#if 0
unsigned int AlarmTimerAdd(struct tm *pOnTime, unsigned int repMode, OnAlarmTimer pOnTimerCb, void *pUserData, int *pError);
#endif
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 CurrentIsWorkDay(int year, int day);
const char* DumpTimerRepeatModeString(int mode);
unsigned long long GetPartitionFreeSize(const char *pPartPath);
WIFI_STATUS GetCurrWIFIConnStatus(void);
const char* ErrcodeToString(int errCode);
const char* DBusCmdToString(DBUS_CMD cmd);
const char* ModuleNameToString(MODULE_NAME modName);
char* GetCpuSerial(void);
char* GetCpuChipId(void);
char* GetCurrentVersion(void);
void CfgFileInit(void);
int CfgGetIntValue(const char* pTags, int defValue);
char* CfgGetStringValue(const char* pTags, char* pDefValue);
double CfgGetFloatValue(const char* pTags, double defValue);
int CfgGetBoolValue(const char* pTags, int defValue);
void SetHBLAutoExit(int flag);
#ifdef __cplusplus
}
#endif
#endif

233
include/log.h Normal file
View File

@ -0,0 +1,233 @@
/** @file log.h
@brief
@details
@version 1.0.0
*/
#ifndef LOG_H_
#define LOG_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifndef __KERNEL__
#include <string.h>
#include <time.h>
#else
#include <linux/string.h>
#endif
#ifndef TRUE
#define TRUE (1)
#endif
#ifndef FALSE
#define FALSE (0)
#endif
#ifndef MAX
/** @def MAX
@brief
*/
#define MAX(a, b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef MIN
/** @def MIN
@brief
*/
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
#endif
#define TIMEZONE_EAST_8H (8 * 3600)
#ifndef __KERNEL__
#define DUMP_PREFIX_ADDRESS (1)
#define DUMP_PREFIX_OFFSET (2)
#endif
#define DEBUG_SQL_CALLBACK_DATA(argc, argv, azColName) do { \
for(int i = 0; i < argc; i++) { \
fprintf(stdout, "%s = [%s], ", azColName[i], argv[i]); \
} \
fprintf(stdout, "\n"); \
} while(0);
#define print(format, ...) fprintf(stdout, format, __VA_ARGS__)
typedef struct
{
int cfgCmd;
int iParams1;
int iParams2;
} LOG_CFG_PROTOCOL, *PLOG_CFG_PROTOCOL;
typedef enum
{
CMD_LOG_ENABLE = 0,
CMD_LOG_FILE = 1,
CMD_LOG_MAIL = 2,
CMD_LOG_LEVEL = 3,
CMD_LOG_NETWORK = 4,
CMD_LOG_SERVER = 5
} LOG_CFG_CMD;
/** @enum _LOG_LEVEL_
* LOG等级枚举变量
*/
typedef enum
{
LOG_Fatal = (1 << 0),
LOG_Error = (1 << 1),
LOG_Warn = (1 << 2),
LOG_Debug = (1 << 3),
LOG_Info = (1 << 4),
LOG_Test = (1 << 5),
LOG_Call = (1 << 6),
LOG_Devp = (1 << 7),
LOG_Step = (1 << 8),
LOG_Unknown = (1 << 9),
LOG_All = (0xFFFFFFFF),
LOG_Close = 0x0,
} LOG_LEVEL;
/** @var typedef _LOG_LEVEL_ LOG_LEVEL
* @brief
*/
#ifdef DISABLE_LOG
#define LOG_BUF(level, buf, len)
#define LOG_EX(level, format, args...)
#define LOG_EX2(level, format, args...)
#define LOG_TAG_EX(tag, level, format, args...)
#define DEBUG_CODE_LINE()
#define DEBUG_FUNCTION_BEGIN()
#define DEBUG_FUNCTION_END()
#else
#define LOG_BUF(level, buf, len) do { \
const char* pFmtBuf = format_hex_buf("", DUMP_PREFIX_ADDRESS, 16, 1, buf, len, 1); \
IHW_LOG(level, "[%s] - %s(%d): %s[0-%d]:\n%s", basename_v2(__FILE__), __FUNCTION__, __LINE__, \
#buf, len, pFmtBuf); \
free((void*)pFmtBuf); \
} while(0);
/*! \def LOG_EX
\brief
*/
#define LOG_EX(level, format, args...) (IHW_LOG(level, "[%s] - %s(%d):" format , basename_v2(__FILE__), __FUNCTION__, __LINE__, ##args))
/*! \def LOG_TAG_EX
\brief
*/
#define LOG_TAG_EX(tag, level, format, args...) (IHW_LOG(level, "{%s} [%s] %s(%d):" format , tag, basename_v2(__FILE__), __FUNCTION__, __LINE__, ##args))
#define LOG_EX2(level, format, args...) (IHW_LOG_UNTAG(level, format , ##args))
/*! @def APP_BUILD_INFO
@brief
*/
#define APP_BUILD_INFO(appname, appver) (IHW_LOG(LOG_Info, "%s Ver:%s (Build: %s %s GCC Ver:%s) With %d(bits) OS\n", \
appname, appver, __DATE__, __TIME__, __VERSION__, sizeof(int*) * 8))
/*! @def DEBUG_CODE_LINE
@brief
*/
#define DEBUG_CODE_LINE() (LOG_EX(LOG_Info, "\n"))
/*! @def DEBUG_FUNCTION_BEGIN
@brief
*/
#define DEBUG_FUNCTION_BEGIN() (LOG_EX(LOG_Call, "+++++\n"))
/*! @def DEBUG_FUNCTION_END
@brief
*/
#define DEBUG_FUNCTION_END() (LOG_EX(LOG_Call, "-----\n"))
/**
* @brief
* @param level
* @param pMsg
*/
void IHW_LOG(LOG_LEVEL level, const char* pMsg, ...);
void IHW_LOG_UNTAG(LOG_LEVEL level, const char* pMsg, ...);
void IHW_LogStrWithoutPrint(int level, char* pMsg);
void IHW_LogRawString(int level, char* pMsg);
/**
* @brief
* @param level
* @param iEnable 1 0
*/
void IHW_EnableLogLevel(LOG_LEVEL level, int iEnable);
/**
* @brief
* @param pLogTag
* @param pPath
* @param bEnable /
*/
void IHW_InitLOG(const char* pLogTag, const char* pPath, int bEnable);
void IHW_RunLogService(void);
/**
* @brief
* @param pPath -
* @return int 1, 0;
*/
int IHW_IsFileExist(const char* pPath);
void IHW_EnableLogOut(void);
void IHW_DisableLogOut(void);
char* IHW_bin2hex(char *p, const unsigned char *cp, int count);
void UpgradLogConfigure(PLOG_CFG_PROTOCOL pCfg);
//void LogUploadCurLogFile(void);
/* Return the last part of a pathname */
static inline const char* basename_v2(const char* path)
{
const char* tail = strrchr(path, '/');
return tail ? tail + 1 : path;
}
static inline int dirname_v2(const char* path, char* dir)
{
const char* tail = strrchr(path, '/');
if(tail)
{
memcpy(dir, path, tail - path);
dir[tail - path] = 0;
}
else
{
strcpy(dir, "./");
}
return 0;
}
#endif
const char* LogLeveToString(LOG_LEVEL lv);
const char* format_hex_buf(const char* prefix_str, int prefix_type,
int rowsize, int groupsize,
const void* buf, int len, int ascii);
#ifndef __KERNEL__
void print_hex_dump_bytes(const char* prefix_str, int prefix_type,
const void* buf, int len);
#endif
int HttpPostLogFile(char* pSession);
//void UploadLogFile(char* pFilePath);
int SysPointMarkUpload(void);
int SysPointMark(char* pMarkInfo);
int SysPointMarkInit(char* pDevId, int iMaxSize, int iPostTime);
#ifdef __cplusplus
}
#endif
#endif //LOG_H_

13
include/log_info.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef LOG_INFO_H
#define LOG_INFO_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __cplusplus
}
#endif
#endif

21
include/monitor.h Normal file
View File

@ -0,0 +1,21 @@
#ifndef _MONITOR_H
#define _MONITOR_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef ENABLE_COUNT_DEBUG
int MonAddNewItem(const char* pName, int logSaveTime);
int MonIncreaseCount(const char* pName);
int MonUpgradeStatistical(const char* pName, long newVal);
int MonDiffStatistical(const char* pName, long long newVal);
int MonItemLogout(const char* pName);
int MonitorInit(void);
#endif
#ifdef __cplusplus
}
#endif
#endif

156
include/ota.h Normal file
View File

@ -0,0 +1,156 @@
#ifndef OTA_H
#define OTA_H
#ifdef __cplusplus
extern "C" {
#endif
#define SIZE_1K (1024) ///< 1K 字节大小
#define MD5_CHKSUM_LEN (16) ///< MD5校验和长度
#define MD5_CHKSUM_STR_LEN (MD5_CHKSUM_LEN * 2 + 1) ///< MD5校验和字符串格式长度
#define NO_OTA_STATUS_VAL_TAG (0) ///< 状态默认值
/**
*
*/
typedef enum
{
NORMAL_SETUP = 0x1234, ///< 普通启动模式
RECOVERY_SETUP, ///< 恢复模式
SYSTEM_OTA, ///< OTA升级模式
SYSTEM_OTA_OK,
} SETUP_MODE;
/**
* OTA状态命令定义
*/
typedef enum
{
OTA_CURRENT_VERSION = 0, ///< 当前系统版本号
OTA_CURRENT_SETUP_MODE, ///< 当前系统启动模式
OTA_CURRENT_REBOOT_TIME, ///< 当前系统未正常启动次数
OTA_DOWNLOAD_FILE, ///< OTA升级包下载状态
OTA_DOWNLOAD_PROGRESS, ///< OTA升级包下载进度
OTA_VERIFY_FILE, ///< 文件校验结果
OTA_VERIFY_PARTITION, ///< OTA分区校验结果
OTA_DECOMPRESS_FILE, ///< OTA当前进度解压文件
OTA_UPGRADE_READY, ///< OTA更新准备完成
OTA_UPGRADE_START, ///< OTA更新开始
OTA_UPGRADE_PARTITION, ///< OTA写入分区数据
OTA_RECOVERY_START, ///< OTA恢复模式启动
OTA_REREQ_OTA_NOW, ///< OTA请求立即执行OTA更新系统
OTA_REBOOT_SYSTEM, ///< OTA准备重启系统
OTA_SUCCESED, ///< OTA执行成功
OTA_UNKNOWN_CMD, ///< 位置OTA状态命令
OTA_ERR_CODE, ///< OTA过程异常
OTA_DISK_FULL, ///< 存储空间不足
} OTA_STATUS_TYPE;
/**
* OTA模式
*/
typedef enum
{
OTA_MODE_NORMAL = 9029, ///< 普通OTA更新模式
OTA_MODE_FORCE_NOW, ///< 强制OTA更新模式
OTA_MODE_RECOVERY, ///< OTA恢复模式
} OTA_MODE;
/**
* OTA操作命令
*/
typedef enum
{
OTA_CMD_DOWNLOAD = 1234, ///< 下载OTA升级包
OTA_CMD_USED_LOCAL_IMAGE, ///< 从上次备份的OTA升级包升级
OTA_CMD_EXEC, ///< 开始OTA更新系统
} OTA_CMD;
/**
* OTA级包信息
*
*/
typedef struct
{
char url[SIZE_1K]; ///< URL, Base64编码
char md5[MD5_CHKSUM_STR_LEN]; ///< OTA升级包MD5校验和
unsigned int size; ///< OTA升级包文件大小
} OTA_FILE_INFO, *POTA_FILE_INFO;
/**
*
*
* @see OTA_CMD
* @see OTA_MODE
* @see OTA_FILE_INFO
*/
typedef struct
{
int version; ///< OTA版本号
OTA_CMD otaCmd; ///< OTA命令
OTA_MODE otaMode; ///< OTA模式
OTA_FILE_INFO otaFileInfo; ///< OTA升级包信息
} OTA_DATA_INFO, *POTA_DATA_INFO;
/**
* OTA状态信息协议
*
* @see OTA_STATUS_TYPE
*/
typedef struct
{
OTA_STATUS_TYPE status; ///< 状态命令
int val; ///< 状态值
} OTA_RSP_STATUS, *POTA_RSP_STATUS;
static inline const char* otaStatusName(OTA_STATUS_TYPE type)
{
switch(type)
{
case OTA_CURRENT_VERSION:
return ("OTA_CURRENT_VERSION");
case OTA_CURRENT_SETUP_MODE:
return ("OTA_CURRENT_SETUP_MODE");
case OTA_CURRENT_REBOOT_TIME:
return ("OTA_CURRENT_REBOOT_TIME");
case OTA_DOWNLOAD_FILE:
return ("OTA_DOWNLOAD_FILE");
case OTA_DOWNLOAD_PROGRESS:
return ("OTA_DOWNLOAD_PROGRESS");
case OTA_VERIFY_FILE:
return ("OTA_VERIFY_FILE");
case OTA_VERIFY_PARTITION:
return ("OTA_VERIFY_PARTITION");
case OTA_DECOMPRESS_FILE:
return ("OTA_DECOMPRESS_FILE");
case OTA_UPGRADE_READY:
return ("OTA_UPGRADE_READY");
case OTA_UPGRADE_START:
return ("OTA_UPGRADE_START");
case OTA_UPGRADE_PARTITION:
return ("OTA_UPGRADE_PARTITION");
case OTA_RECOVERY_START:
return ("OTA_RECOVERY_START");
case OTA_REREQ_OTA_NOW:
return ("OTA_REREQ_OTA_NOW");
case OTA_REBOOT_SYSTEM:
return ("OTA_REBOOT_SYSTEM");
case OTA_SUCCESED:
return ("OTA_SUCCESED");
case OTA_UNKNOWN_CMD:
return ("OTA_UNKNOWN_CMD");
case OTA_ERR_CODE:
return ("OTA_ERR_CODE");
default:
return ("Unknown Type");
}
}
#ifdef __cplusplus
}
#endif
#endif

48
include/server_addr.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef SERVER_ADDR_H
#define SERVER_ADDR_H
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
YUNXIN_MODULE = 0,
VOICE_MODULE = 1,
VOICE_AI_MODULE = 2,
SERVER_MODULE = 3,
LOG_MODULE = 4,
MARK_POINT_MODULE = 5,
TTS_MODULE = 6,
DC_MODULE = 7,
MAX_MODULE
} SERVER_MODULE_TYPE;
typedef enum
{
DEV_MODE = 0,
TEST_MODE = 1,
PUBLISH_MODE = 2,
MAX_MODE
} SERVER_MODE_TYPE;
typedef enum
{
VOICE_APP_KEY = 0,
VOICE_APP_SECRET = 1,
VOICE_MAX
} VOICE_KEYMAP_TYPE;
const char* SvrModeStr(SERVER_MODE_TYPE mode);
const char* SvrModuleStr(SERVER_MODULE_TYPE module);
void DumpCurServerAddr(const char* pTags);
void ServerManagerInit(void);
SERVER_MODE_TYPE GetCurrentServerMode(void);
void SetCurrentServerMode(SERVER_MODE_TYPE mode);
char* GetCurServerAddr(SERVER_MODULE_TYPE module);
char* GetCurVoiceKeyValue(VOICE_KEYMAP_TYPE keyMap);
#ifdef __cplusplus
}
#endif
#endif

58
include/skins.h Normal file
View File

@ -0,0 +1,58 @@
#ifndef SKINS_H
#define SKINS_H
#ifdef __cplusplus
extern "C" {
#endif
#define MD5_STR_LEN (36) ///<
#define MAX_KEY_NAME (64)
#define MAX_KEY_PATH (256)
#define SKIN_MODE_NAME ("ModuleSkin")
#define RES_MODE_NAME ("ModuleRes")
#define RES_TBL_NAME "res"
#define SKIN_TBL_NAME "skin"
#define SKIN_USER_DB "user_db"
#define CREATE_SKIN_TBL_SQL "CREATE TABLE IF NOT EXISTS %s"SKIN_TBL_NAME" (" \
"ID INTEGER PRIMARY KEY AUTOINCREMENT," \
"keyName TEXT NOT NULL," \
"resType INTEGER NOT NULL," \
"priority INTEGER NOT NULL," \
"resID INTEGER NOT NULL," \
"resReadme TEXT NOT NULL DEFAULT \'\');"
#define CREATE_RES_TBL_SQL "CREATE TABLE IF NOT EXISTS %s"RES_TBL_NAME" (" \
"ID INTEGER PRIMARY KEY AUTOINCREMENT," \
"resVersion TEXT NOT NULL," \
"localPath TEXT NOT NULL," \
"serverURL TEXT NOT NULL," \
"md5Chksum TEXT NOT NULL);"
typedef enum
{
VOICE_RES = 1,
IMAGE_RES,
TEXT_RES,
} SKINS_RES_TYPE;
typedef struct
{
SKINS_RES_TYPE resType;
const char *pResVer;
const char *pKeyName;
const char *pLocalPath;
const char *pMD5Chksum;
} SKIN_RES_INFO, *PSKIN_RES_INFO;
int SkinInit(void);
char* GetSkinsResource(char *pKeyName, int *pResType, int *pVersion, char **pComeFrom);
int SkinUpgrade(char *pUpdFilePath);
void SkinIsVerifyRes(int isVerify);
unsigned int SkinsDefaultSize(void);
PSKIN_RES_INFO SkinsItemById(int iId);
#ifdef __cplusplus
}
#endif
#endif

294
include/skins_res.h Normal file
View File

@ -0,0 +1,294 @@
#ifndef SKINS_RES_H
#define SKINS_RES_H
#include "skins.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef PLATFORM_CPU
#define SKINS_DB_PATH ("./skins.db")
#define DEF_SKINS_ROOT_PATH "/home/hx/MyProjects/release/drivers/skins/"
#else
#define SKINS_DB_PATH ("/mnt/UDISK/skins.db")
#define DEF_SKINS_ROOT_PATH "/usr/share/resource/"
#endif
#define EMU_HTTP_URL_ROOT "http://10.240.84.163/resource/"
#if 0
#define TEXT_WIFIPARING_APPARINGANDCONNECTING ("接收到WIFI配置参数开始连接可能时间比较长请耐心等待")
#define TEXT_BT_WIFIPARING ("进入蓝牙网络配对模式")
#define TEXT_AP_WIFIPARING ("进入AP网络配对模式")
#define TEXT_WIFICONNECTED ("联网成功")
#define TEXT_SYSTEMBOOT ("很高兴遇见你,我是如意")
#define TEXT_NOTRECVINGWIFICONFIG ("没有收到网络配置信息")
#define TEXT_BLE_SUUCCESS_WAIT_CONFIG ("低功耗蓝牙已连接,等待配网")
#define TEXT_AP_WAIT_CONFIG ("当前在AP配网模式等待配网")
#define TEXT_WIFINOTCONNECT ("网络未连接")
#define TEXT_REQSERVER_ERROR ("服务器请求失败,请重新配网")
#define TEXT_BLE_CONNECT ("ble已连接")
#define TEXT_BLE_DISCONNECT ("ble已断开")
#define TEXT_WIFIPARINGSUCCESS ("网络配对成功")
#define TEXT_BT_ON ("开启传统蓝牙")
#define TEXT_BT_OFF ("关闭传统蓝牙")
#define TEXT_ALARM_REMOVE_ALL ("删除全部闹钟成功")
#define TEXT_ALARM_REMOVE ("删除闹钟成功")
#define TEXT_ALARM_ADD ("闹钟设置成功")
#define TEXT_AP_APP_CONNECTED ("APP已通过wifi连接音箱")
#define TEXT_WIFICONNECT_ERR_REPARING ("wifi联网失败请重新配网")
#define TEXT_WIFICONNECT_ERR_PASS ("ssid或密码错误请重新配网")
#define TEXT_WIFIPARING_ERR_SERVERCONNECT ("服务器连接失败,请重新配网")
#define TEXT_NOT_UNSUPPORT ("不支持当前操作")
#define TEXT_BOOT_DONE ("你好,欢迎使用如意音箱")
#define TEXT_WIFIPARING_FIRST_NOTICE ("请使用网易云音乐APP ,进入账号页面 为音箱配网,请下载如意音响APP为音箱配网")
#endif
const SKIN_RES_INFO g_SkinDefaultResTable[] = {
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// voice resources
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef RES_FACTORY_MODE
{VOICE_RES, "0", "v102", DEF_SKINS_ROOT_PATH"voice/Alianwang002.mp3", "2ecc61d16a3ee0f02c4e580f00396d1f"},
#endif
{VOICE_RES, "0", "v103", DEF_SKINS_ROOT_PATH"voice/Alianwang003.mp3", "33c00781480680a9ea5ef6be1f7ac258"},
{VOICE_RES, "0", "v104", DEF_SKINS_ROOT_PATH"voice/Alianwang004.mp3", "d8ee9527dd6635f7251b455fcf177723"},
{VOICE_RES, "0", "v105", DEF_SKINS_ROOT_PATH"voice/Alianwang005.mp3", "87849f3c844a42d765e85631ccfca2eb"},
{VOICE_RES, "0", "v106", DEF_SKINS_ROOT_PATH"voice/Alianwang006.mp3", "46a63182f73e242fff7f202fc621ef17"},
{VOICE_RES, "0", "v107", DEF_SKINS_ROOT_PATH"voice/Alianwang007.mp3", "fc02f25d84abfe066fd4ae8c140fe5f7"},
{VOICE_RES, "0", "v108", DEF_SKINS_ROOT_PATH"voice/Alianwang008.mp3", "da772f7fcec24ebcd85bc3d9fe323f88"},
{VOICE_RES, "0", "v109", DEF_SKINS_ROOT_PATH"voice/Alianwang009.mp3", "22b8163a5956bb877db55d38f1223cb2"},
{VOICE_RES, "0", "v110", DEF_SKINS_ROOT_PATH"voice/Alianwang010.mp3", "5d83539bcb59558dd53352b898512227"},
{VOICE_RES, "0", "v111", DEF_SKINS_ROOT_PATH"voice/Alianwang011.mp3", "58de437b7778885481678cc48bc4b592"},
{VOICE_RES, "0", "v112", DEF_SKINS_ROOT_PATH"voice/Alianwang012.mp3", "0e1d0afc6663a73c5aa5d9de0072b8df"},
{VOICE_RES, "0", "v113", DEF_SKINS_ROOT_PATH"voice/Alianwang013.mp3", "f495927bf6b5c67991685e751f2fca40"},
{VOICE_RES, "0", "v114", DEF_SKINS_ROOT_PATH"voice/Alianwang014.mp3", "06b0f3de13c21c60ab73253ee16f36b3"},
{VOICE_RES, "0", "v202", DEF_SKINS_ROOT_PATH"voice/Ashiyong002.mp3", "e825e5c5b6989afb88d4084ffe1eff01"},
{VOICE_RES, "0", "v203", DEF_SKINS_ROOT_PATH"voice/Ashiyong003.mp3", "d7245a20b4a3597894e6af8a83770044"},
{VOICE_RES, "0", "v204", DEF_SKINS_ROOT_PATH"voice/Ashiyong004.mp3", "d546fe1b69f8ba62c14acd299ae5bc7e"},
{VOICE_RES, "0", "v205", DEF_SKINS_ROOT_PATH"voice/Ashiyong005.mp3", "79df29d63ac4ea40546f0274b7dd3c84"},
{VOICE_RES, "0", "v206", DEF_SKINS_ROOT_PATH"voice/Ashiyong006.mp3", "7f47f1796e125078778556d62bd573e2"},
{VOICE_RES, "0", "v301", DEF_SKINS_ROOT_PATH"voice/S001.mp3", "eee1506b7ed801e5aa6a6ccc18c0c1f1"},
{VOICE_RES, "0", "v302", DEF_SKINS_ROOT_PATH"voice/S002.mp3", "c90dbc04cda7bdb778a9cb196eb208a2"},
{VOICE_RES, "0", "v303", DEF_SKINS_ROOT_PATH"voice/S003.mp3", "89340aa9f735d082d9404bae014d7bae"},
{VOICE_RES, "0", "v304", DEF_SKINS_ROOT_PATH"voice/S004-1.mp3", "2a03648026864291cf0aad7bf6569734"},
{VOICE_RES, "0", "v3041", DEF_SKINS_ROOT_PATH"voice/S004-2.mp3", "33cafc99de51b53afc97156866e82473"},
{VOICE_RES, "0", "v3042", DEF_SKINS_ROOT_PATH"voice/S004-3.mp3", "0a1057342a661597730b521427d6097c"},
{VOICE_RES, "0", "v3043", DEF_SKINS_ROOT_PATH"voice/S004-4.mp3", "c8061b90c50558c155ddc9ffef114e61"},
{VOICE_RES, "0", "v3044", DEF_SKINS_ROOT_PATH"voice/S004-5.mp3", "97f94d1350bc09c9e974525172ad8fc0"},
{VOICE_RES, "0", "v305", DEF_SKINS_ROOT_PATH"voice/S005.mp3", "2e7a489501b76c73e5aa4be4f7e7aa5f"},
{VOICE_RES, "0", "v306", DEF_SKINS_ROOT_PATH"voice/S006.mp3", "437ddb3e99f77696d60c2f28c1b268cb"},
{VOICE_RES, "0", "v307", DEF_SKINS_ROOT_PATH"voice/S007.mp3", "a6c6be6f702b5b47ddebad61d28eb1ad"},
{VOICE_RES, "0", "v308", DEF_SKINS_ROOT_PATH"voice/S008.mp3", "5918f635de28b45f2d32e3eb4b05b9ad"},
{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", "v401", DEF_SKINS_ROOT_PATH"voice/b-h-01.mp3", "68ecfbab58563071b6663a348a39a51b"},
{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"},
{VOICE_RES, "0", "v5012", DEF_SKINS_ROOT_PATH"voice/a-a-02.mp3", "837a2222c961824e98c0d3751a234ae6"},
{VOICE_RES, "0", "v5013", DEF_SKINS_ROOT_PATH"voice/a-a-03.mp3", "0ec34a1f19ee7cea6b139d214e59026d"},
{VOICE_RES, "0", "v502", DEF_SKINS_ROOT_PATH"voice/a-n-01.mp3", "b1eb13ed8c9afaa2989763c3d379b39a"},
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/// picture resources
///////////////////////////////////////////////////////////////////////////////////////////////////////////
{IMAGE_RES, "0", "p001", DEF_SKINS_ROOT_PATH"image/IconChaozuo001.jpg", "0d4aa6351cc71daf2c699e42c1b74cde"},
{IMAGE_RES, "0", "p005", DEF_SKINS_ROOT_PATH"image/IconChaozuo005.jpg", "1ceca68b9e7d49c537376a08c07a2b88"},
{IMAGE_RES, "0", "p101", DEF_SKINS_ROOT_PATH"image/IconLianjie001.jpg", "236dbc343bd1d0c5e651f33900a13c07"},
{IMAGE_RES, "0", "p102", DEF_SKINS_ROOT_PATH"image/IconLianjie002.jpg", "c627364aec00131589fc942c902c65bc"},
{IMAGE_RES, "0", "p103", DEF_SKINS_ROOT_PATH"image/IconLianjie003.jpg", "edb04af03cf7c7e4d29aee43c332235b"},
{IMAGE_RES, "0", "p201", DEF_SKINS_ROOT_PATH"image/IconNaozhong001.jpg", "bd5e7a00b4902ca971684d6ee021fb06"},
{IMAGE_RES, "0", "p302", DEF_SKINS_ROOT_PATH"image/Iconstart002.gif", "90f2b52b1399348debcec2f447dbd383"},
{IMAGE_RES, "0", "p401", DEF_SKINS_ROOT_PATH"image/IconTixing001.jpg", "feff2fbedffc955b491e0349385ef6c3"},
{IMAGE_RES, "0", "p500", DEF_SKINS_ROOT_PATH"image/Iconyinliang000.jpg", "a0c29ad20d51cf86e808c83ee90b6510"},
{IMAGE_RES, "0", "p501", DEF_SKINS_ROOT_PATH"image/Iconyinliang001.jpg", "196ba4082358d3238d0dcb0035764465"},
{IMAGE_RES, "0", "p502", DEF_SKINS_ROOT_PATH"image/Iconyinliang002.jpg", "196ba4082358d3238d0dcb0035764465"},
{IMAGE_RES, "0", "p503", DEF_SKINS_ROOT_PATH"image/Iconyinliang003.jpg", "196ba4082358d3238d0dcb0035764465"},
{IMAGE_RES, "0", "p504", DEF_SKINS_ROOT_PATH"image/Iconyinliang004.jpg", "d3157ec3c194e4cc6dbcbe683fd40d3f"},
{IMAGE_RES, "0", "p505", DEF_SKINS_ROOT_PATH"image/Iconyinliang005.jpg", "3f857b11062aeddaa6061e7cabfde044"},
{IMAGE_RES, "0", "p506", DEF_SKINS_ROOT_PATH"image/Iconyinliang006.jpg", "3f857b11062aeddaa6061e7cabfde044"},
{IMAGE_RES, "0", "p507", DEF_SKINS_ROOT_PATH"image/Iconyinliang007.jpg", "64a461ee34bea341879aa5a08c717705"},
{IMAGE_RES, "0", "p508", DEF_SKINS_ROOT_PATH"image/Iconyinliang008.jpg", "b932b0b1c7766c6a995ce3e63b2b7422"},
{IMAGE_RES, "0", "p509", DEF_SKINS_ROOT_PATH"image/Iconyinliang009.jpg", "dce1278710e1831f02d8dd4fd5d0aac6"},
{IMAGE_RES, "0", "p510", DEF_SKINS_ROOT_PATH"image/Iconyinliang010.jpg", "b9ac1d7469b34d2aabe04d849c4f1112"},
{IMAGE_RES, "0", "p511", DEF_SKINS_ROOT_PATH"image/Iconyinliang011.jpg", "45e001edc7d973b15434334ad7f77771"},
{IMAGE_RES, "0", "p512", DEF_SKINS_ROOT_PATH"image/Iconyinliang012.jpg", "c9c22063c381e5cb775c82b105dce0f1"},
{IMAGE_RES, "0", "p513", DEF_SKINS_ROOT_PATH"image/Iconyinliang013.jpg", "6e06e51e83498185d148070c0643852c"},
{IMAGE_RES, "0", "p514", DEF_SKINS_ROOT_PATH"image/Iconyinliang014.jpg", "6e06e51e83498185d148070c0643852c"},
{IMAGE_RES, "0", "p515", DEF_SKINS_ROOT_PATH"image/Iconyinliang015.jpg", "694a1698c16539805ed4ee238f36586c"},
{IMAGE_RES, "0", "p516", DEF_SKINS_ROOT_PATH"image/Iconyinliang016.jpg", "0e7e847191e429618c6684ae89d30ac6"},
{IMAGE_RES, "0", "p517", DEF_SKINS_ROOT_PATH"image/Iconyinliang017.jpg", "a18f5107ada535d664b2483b02080e70"},
{IMAGE_RES, "0", "p518", DEF_SKINS_ROOT_PATH"image/Iconyinliang018.jpg", "d64992577a379c0faed0078dde767fcc"},
{IMAGE_RES, "0", "p519", DEF_SKINS_ROOT_PATH"image/Iconyinliang019.jpg", "58268a96482df75c97a177371d295bd3"},
{IMAGE_RES, "0", "p520", DEF_SKINS_ROOT_PATH"image/Iconyinliang020.jpg", "81ffbdc7857790696e3a7e353bd86908"},
{IMAGE_RES, "0", "p601", DEF_SKINS_ROOT_PATH"image/Iconlianwang001.gif", "9e18565313b6b1769b7c5979a248dbd6"},
{IMAGE_RES, "0", "p605", DEF_SKINS_ROOT_PATH"image/Iconlianwang005.gif", "ee81f49fe49864d4cbc4f7f9a1ec52c0"},
{IMAGE_RES, "0", "p703", DEF_SKINS_ROOT_PATH"image/IconZhuangtai003.gif","e2bdf79f8c2825c23ffbb0233328df97"},
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// tts resources
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if 0
{{TEXT_RES, 0, "wifiparing_apparingandconnecting", ""}, "", TEXT_WIFIPARING_APPARINGANDCONNECTING, ""},
{{TEXT_RES, 0, "bt_wifiparing", ""}, "", TEXT_BT_WIFIPARING, ""},
{{TEXT_RES, 0, "ap_wifiparing", ""}, "", TEXT_AP_WIFIPARING, ""},
{{TEXT_RES, 0, "wificonnected", ""}, "", TEXT_WIFICONNECTED, ""},
{{TEXT_RES, 0, "systemboot", ""}, "", TEXT_SYSTEMBOOT, ""},
{{TEXT_RES, 0, "notrecvingwificonfig", ""}, "", TEXT_NOTRECVINGWIFICONFIG, ""},
{{TEXT_RES, 0, "ble_suuccess_wait_config", ""}, "", TEXT_BLE_SUUCCESS_WAIT_CONFIG, ""},
{{TEXT_RES, 0, "ap_wait_config", ""}, "", TEXT_AP_WAIT_CONFIG, ""},
{{TEXT_RES, 0, "wifinotconnect", ""}, "", TEXT_WIFINOTCONNECT, ""},
{{TEXT_RES, 0, "reqserver_error", ""}, "", TEXT_REQSERVER_ERROR, ""},
{{TEXT_RES, 0, "ble_connect", ""}, "", TEXT_BLE_CONNECT, ""},
{{TEXT_RES, 0, "ble_disconnect", ""}, "", TEXT_BLE_DISCONNECT, ""},
{{TEXT_RES, 0, "wifiparingsuccess", ""}, "", TEXT_WIFIPARINGSUCCESS, ""},
{{TEXT_RES, 0, "bt_on", ""}, "", TEXT_BT_ON, ""},
{{TEXT_RES, 0, "bt_off", ""}, "", TEXT_BT_OFF, ""},
{{TEXT_RES, 0, "alarm_remove_all", ""}, "", TEXT_ALARM_REMOVE_ALL, ""},
{{TEXT_RES, 0, "alarm_remove", ""}, "", TEXT_ALARM_REMOVE, ""},
{{TEXT_RES, 0, "alarm_add", ""}, "", TEXT_ALARM_ADD, ""},
{{TEXT_RES, 0, "ap_app_connected", ""}, "", TEXT_AP_APP_CONNECTED, ""},
{{TEXT_RES, 0, "wificonnect_err_reparing", ""}, "", TEXT_WIFICONNECT_ERR_REPARING, ""},
{{TEXT_RES, 0, "wificonnect_err_pass", ""}, "", TEXT_WIFICONNECT_ERR_PASS, ""},
{{TEXT_RES, 0, "wifiparing_err_serverconnect", ""}, "", TEXT_WIFIPARING_ERR_SERVERCONNECT, ""},
{{TEXT_RES, 0, "not_unsupport", ""}, "", TEXT_NOT_UNSUPPORT, ""},
{{TEXT_RES, 0, "boot_done", ""}, "", TEXT_BOOT_DONE, ""},
{{TEXT_RES, 0, "wifiparing_first_notice", ""}, "", TEXT_WIFIPARING_FIRST_NOTICE, ""},
#endif
};
static const SKIN_RES_INFO g_emuUpgradeInfo[] = {
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"android.txt", "8dc557037b69c69efd5615cdfc06934a"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"applying-patches.txt", "8d65812b01d64c9df1529509083e189d"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"atomic_ops.txt", "0d6a66d951ed4747aeee1aa7ab99d8d3"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"bad_memory.txt", "e81b536c2095eb53f9209e26b914f426"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"basic_profiling.txt", "1c70596bd41eb49077af5e91e16d2967"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"binfmt_misc.txt", "8936b928d685bdf98f83f1b3e86562a4"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"braille-console.txt", "4263bbce1595bdb3923bcb7885f866f5"},
{VOICE_RES, "1", "v001", EMU_HTTP_URL_ROOT"bt8xxgpio.txt", "3a61d033e71cff3c75c778dad89ac565"},
{VOICE_RES, "1", "v105", EMU_HTTP_URL_ROOT"btmrvl.txt", "f5ce90fb4a0ef97d23914fef37fba39d"},
{VOICE_RES, "1", "v105", EMU_HTTP_URL_ROOT"bus-virt-phys-mapping.txt", "23fedac31d1b6ee5dae644ed86cc2c37"},
{VOICE_RES, "1", "v105", EMU_HTTP_URL_ROOT"cachetlb.txt", "5db6b816869d89822759bca684024430"},
{VOICE_RES, "1", "v105", EMU_HTTP_URL_ROOT"circular-buffers.txt", "3be2b7f00c13b160d5dba390b2ee8a54"},
{VOICE_RES, "1", "v105", EMU_HTTP_URL_ROOT"clk.txt", "e60704c45037f922a73f49fc827b5225"},
{VOICE_RES, "1", "v206", EMU_HTTP_URL_ROOT"coccinelle.txt", "379a83726bbf8f2ffbb12ba454788909"},
{VOICE_RES, "1", "v206", EMU_HTTP_URL_ROOT"cpu-hotplug.txt", "e3676063c62c556a94ebf3b9296db82f"},
{VOICE_RES, "1", "v206", EMU_HTTP_URL_ROOT"cpu-load.txt", "d9d096434110f5c017ab27ea397cee1d"},
{VOICE_RES, "1", "v206", EMU_HTTP_URL_ROOT"cputopology.txt", "4ead2141d532dfaf1057cd2964ced3f4"},
{VOICE_RES, "1", "v206", EMU_HTTP_URL_ROOT"crc32.txt", "644ff3d58c8ab6ca0c5c721dc78e7343"},
{VOICE_RES, "1", "v206", EMU_HTTP_URL_ROOT"dcdbas.txt", "ad88b9a2d9b547a81ec3f28006a897bc"},
{VOICE_RES, "1", "v309", EMU_HTTP_URL_ROOT"debugging-modules.txt", "c3b0d7040e83f85b5593dac628b3ffa5"},
{VOICE_RES, "1", "v309", EMU_HTTP_URL_ROOT"debugging-via-ohci1394.txt", "a58d95e96be1ca24c5946c6636c4e041"},
{VOICE_RES, "1", "v309", EMU_HTTP_URL_ROOT"dell_rbu.txt", "d5324f7ddcfbf19eb00e4c81bbb5cb7f"},
{VOICE_RES, "1", "v309", EMU_HTTP_URL_ROOT"devices.txt", "8aa73c9268a9012eecbbb78fc4e4cc68"},
{VOICE_RES, "1", "v309", EMU_HTTP_URL_ROOT"digsig.txt", "44b680ee0b743d63f9d0d2849e39d982"},
{VOICE_RES, "1", "v309", EMU_HTTP_URL_ROOT"DMA-API-HOWTO.txt", "3225970a70a6a79c5112ff29b8f99ec6"},
{VOICE_RES, "1", "v310", EMU_HTTP_URL_ROOT"DMA-API.txt", "3110d6930bd1c4c692c741f960310810"},
{VOICE_RES, "1", "v310", EMU_HTTP_URL_ROOT"DMA-attributes.txt", "1ccc7f613bde5312a6a7452e8381d518"},
{VOICE_RES, "1", "v311", EMU_HTTP_URL_ROOT"dma-buf-sharing.txt", "303f87732efc9effee0d6ed16e89ee37"},
{VOICE_RES, "1", "v303", EMU_HTTP_URL_ROOT"dmaengine.txt", "80881dc6b0c7c9761be617a8f2e5eee3"},
{VOICE_RES, "1", "v303", EMU_HTTP_URL_ROOT"DMA-ISA-LPC.txt", "a0b20e82cadca3595c95a9b7909a2120"},
{VOICE_RES, "1", "v303", EMU_HTTP_URL_ROOT"dynamic-debug-howto.txt", "d15ef07d9fae98de0e096897da1e06ab"},
{VOICE_RES, "1", "v303", EMU_HTTP_URL_ROOT"edac.txt", "a83b6d68f9e4c2d03ac619f912c13eb9"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"eisa.txt", "cae33ca2a108401d9465a0589503b845"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"email-clients.txt", "a1e6b9470ea752cf97a99ebcb9594aa0"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"feature-removal-schedule.txt", "e45405d2fac3a3bf87b26b3faeaad5de"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"flexible-arrays.txt", "03bfe3a8cb65aecdc96f710a140b8c27"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"futex-requeue-pi.txt", "684984d4f7026c76533ad7f247136ef4"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"gcov.txt", "fb711ca5323092e285f2e0b59a574009"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"gpio.txt", "13417a2589abd22672e8c109e5c57e8e"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"highuid.txt", "1c3e14d700b302d76b1bca29325a4a8e"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"hw_random.txt", "6c78af2ee2fab6ae30aca725c3970da1"},
{VOICE_RES, "1", "v202", EMU_HTTP_URL_ROOT"hwspinlock.txt", "2ac1e75e3ee30099527e344287340b0a"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"initrd.txt", "c889974503df36fc073c891e6d9b8b0a"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"init.txt", "bdbcc42bf6ae739157092a7fa64aaaac"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"Intel-IOMMU.txt", "e693ef88d3d7d42c7a65a23f3975aa97"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"intel_txt.txt", "9dd22fd4de8b9e718fefc96c15b994c8"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"io-mapping.txt", "a7785b478117c65839749521fc020dc3"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"io_ordering.txt", "f7a404c9794d133f9167ff1a7e2953bb"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"iostats.txt", "4248f808a42956c73b79032686ae77bb"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"IPMI.txt", "8b8bc6bf4528e8d82017113c17d58a37"},
{VOICE_RES, "1", "v111", EMU_HTTP_URL_ROOT"IRQ-affinity.txt", "d89c8d406a2618cc19db636ba81ce4ca"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"IRQ-domain.txt", "ec9bde5aa997211d7ded9658cfde4fff"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"irqflags-tracing.txt", "b8ca946951177d2cb8099feb9c4587e2"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"IRQ.txt", "0ef9f8f98b9eac9336c0ffb95cfc1d65"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"isapnp.txt", "ab111f0d42d1e748d9745c09e7ff935b"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"java.txt", "fbe28a3d11651fd214ad1d897700fd4f"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kernel-doc-nano-HOWTO.txt", "28579d296e40e460678d0587991e9d48"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kernel-docs.txt", "afc6fd5cdcc8b49ba794bcf5382ff2c3"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kernel-parameters.txt", "2dc9abd6790fd24c3e841f15d0d24a38"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kmemcheck.txt", "b301c758aed537468e98183bd04dc15d"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kmemleak.txt", "b5108533723c0a616e8723e009244d55"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kobject.txt", "d47cf170cd9ce2aaca082fa322b3c271"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kprobes.txt", "7a4c60ba6c646746ca64a311b24a7919"},
{VOICE_RES, "1", "v110", EMU_HTTP_URL_ROOT"kref.txt", "e6ee109e7185aafc4efe67cad2576352"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"ldm.txt", "3492835c4e3f2340ef0a0d5af464b962"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"local_ops.txt", "809dba9261b3704813557cccaeb3d83d"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"lockdep-design.txt", "b5379d04c39758d7f979d8c6c459285b"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"lockstat.txt", "c672433097ed3823b84bea98cafbb921"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"lockup-watchdogs.txt", "36c72be9bf511bd0e76975f7987f97a2"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"logo.txt", "c12e6a02a126220ed420586143f96d7e"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"magic-number.txt", "2baed34f647a4dab43357718050ded53"},
{VOICE_RES, "1", "v201", EMU_HTTP_URL_ROOT"mca.txt", "1ea3eab396d5433f30952ad1b30ab133"},
{VOICE_RES, "1", "v304", EMU_HTTP_URL_ROOT"md.txt", "6cdd602644e47836f0cb357e910a4db7"},
{VOICE_RES, "1", "v304", EMU_HTTP_URL_ROOT"media-framework.txt", "1f3f9ba9afc6c1323df2c03160b4db4d"},
{VOICE_RES, "1", "v304", EMU_HTTP_URL_ROOT"memory-barriers.txt", "1b2369bd78d18c2f80c23ca3ab2fb8d8"},
{VOICE_RES, "1", "v304", EMU_HTTP_URL_ROOT"memory-hotplug.txt", "e9bc23bc43814ef7fbe2bcd89692c55b"},
{VOICE_RES, "1", "v304", EMU_HTTP_URL_ROOT"memory.txt", "c17ccb89201a46532f3b95fee4adc372"},
{VOICE_RES, "1", "v304", EMU_HTTP_URL_ROOT"mono.txt", "da6d7823007522089fc4bfefc1752b16"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"mutex-design.txt", "278a8bef9b14c136939715738cc0f0e8"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"nommu-mmap.txt", "9f4e01823e63aec8b42bf523389664fc"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"numastat.txt", "bebd74fc4713e1500702be1a90113f74"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"oops-tracing.txt", "87f1184ede24989279c9a1dfa1ccfae1"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"padata.txt", "bd3486df46e488dd75d1e67b2bb52da9"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"parport-lowlevel.txt", "a7d58201239229037269d4fd7ba720ac"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"parport.txt", "fa8d7291a3e7d5c2afe5a2060a0abb50"},
{VOICE_RES, "1", "v108", EMU_HTTP_URL_ROOT"pi-futex.txt", "492ac92f69716bfaa0c40a909c992ade"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"pinctrl.txt", "9b7c710bba0b9aaae7e4f3794a548511"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"pnp.txt", "a7338b790fd6b30b4071fcacbfcedc4e"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"preempt-locking.txt", "5b7ed3fd44bb218e897492667b316a56"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"printk-formats.txt", "8eaefbea3500e15cc155045b3d3ef39c"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"prio_tree.txt", "1b079f5eac72227ecee86a7693ae8f69"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"ramoops.txt", "b50016891d7184720439346f362083e3"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"rbtree.txt", "a35e53c01ecfe9fbc534425504b8f408"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"remoteproc.txt", "d9599a6eda47e17ade41491b1106db22"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"rfkill.txt", "d86dc1dc7f27a25692b40cb739a88a09"},
{VOICE_RES, "1", "v107", EMU_HTTP_URL_ROOT"robust-futex-ABI.txt", "32be0a8a71053b3258c8dc13c8e3f981"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"robust-futexes.txt", "1ac8f369bc00680aa40e8dfd3bc766c3"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"rpmsg.txt", "67b8fcf7e064b15d910e6ef41b944984"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"rtc.txt", "51577c35a6c713e85bc4325dde78f1f9"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"rt-mutex-design.txt", "25703f95e001b8ab0a92ec7e22f85527"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"rt-mutex.txt", "b449bdf78dad3a5ff62eb7a0853c0c99"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"SAK.txt", "bb81ce113927582c1513704f360129fd"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"serial-console.txt", "814e90de90e893f56eb12cc536dc7d42"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"sgi-ioc4.txt", "f4e0584fa5b55907435c3374c6ae6601"},
{VOICE_RES, "1", "v333", EMU_HTTP_URL_ROOT"sgi-visws.txt", "0bb26ebbfc96a898f54126d5762cd3de"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"SM501.txt", "58ce960675582f8414019f33a27e1260"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"sparse.txt", "8bc3d0ada8ca01475d69431cd9cd4ec0"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"spinlocks.txt", "d903caeac016182fd7bb349af658bb1a"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"stable_api_nonsense.txt", "ca2acd6fd94048b5b03b213922d962b5"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"stable_kernel_rules.txt", "3948439142160832a55510a93746b738"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"static-keys.txt", "6d801dd48021a20394a7eaa82f0b758d"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"svga.txt", "ffc4306708801c3489dc575998ecca43"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"sync.txt", "381c9f8905dfc34f66eef3e3e486f0d1"},
{VOICE_RES, "1", "v203", EMU_HTTP_URL_ROOT"sysfs-rules.txt", "84cfa60b3ba436be5acd54034bc15c84"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"sysrq.txt", "f24e71d4fed0257178078b820927791b"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"unaligned-memory-access.txt", "a5a387aeec918a0f528f85bcb76bc8c5"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"unicode.txt", "fd815b4b43d0cf5a85ca44d0db76dde7"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"unshare.txt", "a3ca54a1d655c512654510e56b4c8e53"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"vgaarbiter.txt", "802d04a400dfb5959711fe8088c62f01"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"VGA-softcursor.txt", "88c93a1b83277f3fc3fb07de148fd726"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"video-output.txt", "60ab68e5be73008948e8f1426db0941b"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"volatile-considered-harmful.txt", "8983aa37ffb5d56400e7f54ca9aa88d6"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"workqueue.txt", "6fadee709d10fbbdc4ed587020dbb9b7"},
{VOICE_RES, "1", "v204", EMU_HTTP_URL_ROOT"xz.txt", "4c3cdd3cc9795936719f90c5998e444d"},
{VOICE_RES, "1", "v904", EMU_HTTP_URL_ROOT"zorro.txt", "5afccd5699a870edbaeeb4842171e637"}
};
#ifdef __cplusplus
}
#endif
#endif

507
include/smart_sound.h Normal file
View File

@ -0,0 +1,507 @@
#ifndef SMART_SOUND_H
#define SMART_SOUND_H
#ifdef __cplusplus
extern "C" {
#endif
#define CMD_BT_AVK_OPEN CMD_BT_BREDR_ENABLE
#define CMD_BT_AVK_CLOSE CMD_BT_BREDR_DISABLE
//*****************************************************************
//* Global Configure
//*****************************************************************
#define USED_SHM_TO_DBUS (0) // used shm for dbus transfer data
#ifndef MAX_PATH
#define MAX_PATH (256)
#endif
//*************************************************************
typedef enum {
MODULE_CONTROLLER = 0,
MODULE_ALARM,
MODULE_CALL,
MODULE_VOICEENGINE,
MODULE_PLAYER,
MODULE_CONFIGURE,
MODULE_OTA,
MODULE_WIFI,
MODULE_BT,
MODULE_KPLAYER,
MODULE_KPLAYER_TEST,
MODULE_SPLAYER,
MODULE_SPLAYER_TEST,
MODULE_LIGHT_MCU,
MODULE_BLUEKC,
MODULE_BLUEKC_TEST,
MODULE_MANUFACTURE,
MODULE_BT_DEMO,
MODULE_SKINS,
MODULE_LOG_CTRL,
MODULE_WIRELESSTEST,
MODULE_WIRELESSTEST_DEMO,
MODULE_MANUFACTURE_CONTROLLER,
MODULE_WIFI_DEMO,
MODULE_MAX,
} MODULE_NAME;
typedef enum {
CMD_MISC_PING = 0x0000,
CMD_MISC_OTA,
CMD_MISC_WEATHER,
CMD_MISC_NOWTIME,
CMD_MISC_UPGRADE,
CMD_SYSTEM_STANDBY,
CMD_MISC_QUERY_OTA_STATUS,
CMD_MISC_QUERY_DL_STATUS,
CMD_MISC_CHANGE2TEST,
CMD_MISC_CHANGE2ONLINE,
CMD_SEARCH_PLAYER_REQ,
CMD_SEARCH_PLAYER_RESP,
CMD_PROCESS_START,
CMD_CALL_DIAL = 0x0300,
CMD_CALL_ACCEPI,
CMD_CALL_HANGUP,
CMD_CALL_MESSAGE,
CMD_PLAY_MODECHANGE = 0x0600,
CMD_PLAY_PLAY,
CMD_PLAY_PAUSE,
CMD_PLAY_STOP,
CMD_PLAY_SEEKTO,
CMD_PLAY_SHOWMODE,
CMD_PLAY_NEXT,
CMD_PLAY_PRE,
CMD_PLAY_SEEKTO_PLAY,
CMD_PLAY_SHOWLIST,
CMD_PLAY_UPDATELIST,
CMD_PLAY_PREPARE_NEXT,
CMD_PLAY_ADDTOLIST,
CMD_PLAY_DELETEFROMLIST,
CMD_PLAY_RESETLIST,
CMD_PLAY_VOL_SET,
CMD_PLAY_VOL_RESTORE,
CMD_PLAY_MAX,
CMD_PLAY_AUDIO_STOP = 0x0700,
CMD_PLAY_AUDIO_PLAY,
CMD_PLAY_AUDIO_MAX,
CMD_SE_PLAY = 0x0780,
CMD_SE_PLAYER_STATE_NTF,
CMD_MUSIC_PCM_PLAY = 0X0790,
CMD_MUSIC_PCM_PAUSE = 0X0791,
CMD_MUSIC_PCM_STOP = 0X0792,
CMD_MUSIC_PCM_MAX,
CMD_PLAYER_MAX = 0X07FF,
CMD_PLAY_RET_STATUS = 0x0800,
CMD_CFG_ADD_REQ = 0x0900,
CMD_CFG_ADD_RSP,
CMD_CFG_CHANGE_REQ,
CMD_CFG_CHANGE_RSP,
CMD_CFG_GET_REQ,
CMD_CFG_GET_RSP,
CMD_CFG_UPG_NOTIFY,
CMD_MSC_MSG_CONTROLLER_RECOG_SUCCESS = 0x0a00,
CMD_MSC_MSG_CONTROLLER_RECOG_ERROR,
CMD_MSC_MSG_CONTROLLER_WAKEUP,
CMD_MSC_MSG_CONTROLLER_SESSION_BEGIN,
CMD_MSC_MSG_CONTROLLER_RECOGING,
CMD_CC_MSC_BEGIN_SESSION,
CMD_CC_MSC_END_SESSION,
CMD_CONTROLLER_REQMSG_INITARGS,
CMD_CONTROLLER_RSPMSG_INITARGS,
CMD_CONTROLLER_REQMSG_PLAYERSTATUS,
CMD_CONTROLLER_RSPMSG_PLAYERSTATUS,
CMD_MSC_REQMSG_MIC_CONTROL,
CMD_MSC_RSPMSG_MIC_CONTROL,
CMD_NDUILITE_FESPA_SET_ARG,
CMD_YUNXIN_RECVMSG,
CMD_YUNXIN_SENDMSG,
CMD_YUNXIN_SENDMSG_BYPASS,
CMD_YUNXIN_SENDMSGCB,
CMD_CONTROLLER_MSG_YUNXIN,
CMD_YUNXIN_STATUS,
CMD_YUNXIN_SYSMSG,
CMD_WIFI_CONF = 0x0b00,
CMD_WIFI_CONF_RESP,
CMD_WIFI_AUTO_CONN,
CMD_WIFI_AUTO_CONN_RESP,
CMD_WIFI_AUTO_CONN_OUT,
CMD_WIFI_STATE_REQ,
CMD_WIFI_STATE_RESP,
CMD_WIFI_STATE_NTF,
CMD_WIFI_CHANGE_VALID_AP,
CMD_WIFI_CHANGE_VALID_AP_OUT,
CMD_WIFI_CHANGE_VALID_AP_RESP,
CMD_BT_NAME_GET_REQ,
CMD_BT_NAME_GET_RESP,
CMD_BT_EVT_NTF,
CMD_BT_CREATED,
CMD_BT_RESET,
CMD_BT_BREDR_ENABLE, // 0xb10
CMD_BT_BREDR_DISABLE, // 0xb11
CMD_BT_AVK_SOUND_OPEN,
CMD_BT_AVK_SOUND_CLOSE,
CMD_BT_AVK_CON_EVT,
CMD_BT_AVK_DISC_EVT,
CMD_BT_AVK_CON_DEV,
CMD_BT_AVK_DISC_DEV,
CMD_BT_AVK_PLAY,
CMD_BT_AVK_PAUSE,
CMD_BT_AVK_STOP,
CMD_BT_AVK_PRE,
CMD_BT_AVK_NEXT,
CMD_BT_AVK_VOL_UP,
CMD_BT_AVK_VOL_DOWN,
CMD_BT_AVK_SOUND_START_EVT, // 0xb1f
CMD_BT_AVK_SOUND_STOP_EVT, // 0xb20
CMD_BT_LE_ENABLE, // 0xb21
CMD_BT_LE_DISABLE,
CMD_BT_LE_NEVSPS_DISC,
CMD_BT_AVK_CRTED,
CMD_BT_AVK_DELETED,
CMD_BT_AVK_RC_PLAY,
CMD_BT_AVK_RC_PAUSE,
CMD_WIFI_UNBIND_ACCOUNT,
CMD_BT_VOL_CHANGE,
CMD_BT_BREDR_REBOOT_CLOSE,
CMD_KPLAYER_START = 0x1b00,
CMD_KPLAYER_STOP,
CMD_KPLAYER_NOTIF_DUR,
CMD_KPLAYER_HOST_ACTION,
CMD_KPLAYER_CTR_NTF_BASE = 0x1c00,
CMD_KPLAYER_CTR_CREATED,
CMD_KPLAYER_CTR_DELED,
CMD_KPLAYER_CTR_PLAY,
CMD_KPLAYER_CTR_STOP,
CMD_KPLAYER_CTR_PAUSE,
CMD_KPLAYER_CTR_SEEK,
CMD_KPLAYER_CTR_SET_URL,
CMD_KPLAYER_CTR_SET_VOLUME,
CMD_KPLAYER_CTR_SET_MUTE,
CMD_KPLAYER_CTR_SET_NXT_URL,
CMD_KPLAYER_CTR_SET_NEXT,
CMD_KPLAYER_CTR_SET_PREV,
CMD_SPLAYER_SFIFO_TEST = 0x1d00,
CMD_SPLAYER_START,
CMD_SPLAYER_STOP,
CMD_SPLAYER_HOST_ACTION,
CMD_SPLAYER_CTR_NTF_BASE = 0x1e00,
CMD_SPLAYER_MSG_TYPE_CREATE,
CMD_SPLAYER_MSG_TYPE_DEL,
CMD_SPALYER_MSG_TYPE_START,
CMD_SPLAYER_MSG_TYPE_STOP,
CMD_SPLAYER_MSG_TYPE_SET_VOLUME,
CMD_SPLAYER_MSG_TYPE_STREAMING,
CMD_SPLAYER_MSG_TYPE_DESTRY,
CMD_SPLAYER_MSG_TYPE_DURATION,
CMD_SPLAYER_MSG_TYPE_STREAM_NTF,
CMD_SPLAYER_MSG_TYPE_STREAM_PLAYPAUSE,
CMD_BLUEKC_POOL_TEST = 0x1f00,
CMD_BLUEKC_LOG_DEBUG,
CMD_BLUEKC_LOG_RESTORE,
// 厂测
CMD_TEST_GET_VER_REQ = 0X2000,
CMD_TEST_GET_VER_RESP,
CMD_TEST_GET_MCU_VER_REQ,
CMD_TEST_GET_MCU_VER_RESP,
CMD_TEST_KNOB_REQ,
CMD_TEST_KNOB_RESP,
CMD_TEST_BUTTON_REQ,
CMD_TEST_BUTTON_RESP,
CMD_TEST_GET_VOLUME_REQ,
CMD_TEST_GET_VOLUME_RESP,
CMD_TEST_SET_VOLUME_REQ,
CMD_TEST_SET_VOLUME_RESP,
CMD_TEST_BT_ADDR_REQ,
CMD_TEST_BT_ADDR_RESP,
CMD_TEST_BT_PARRING_REQ,
CMD_TEST_BT_PARRING_RESP,
CMD_TEST_GET_CPLD_REQ,
// RF cmd--->
CMD_TEST_RF_BASE = 0x2100,
CMD_TEST_RF_BT_ENTER,
CMD_TEST_RF_BT_ENTER_RESP,
CMD_TEST_RF_EXIT_TO_NORNAL,
CMD_TEST_RF_EXIT_TO_NORNAL_RESP,
CMD_TEST_RF_BT_TX = 0x2200,
CMD_TEST_RF_BT_TX_RESP,
CMD_TEST_RF_BT_TX_2402_1DH1,
CMD_TEST_RF_BT_TX_2402_1DH1_RESP,
CMD_TEST_RF_BT_TX_2440_1DH1,
CMD_TEST_RF_BT_TX_2440_1DH1_RESP,
CMD_TEST_RF_BT_TX_2480_1DH1,
CMD_TEST_RF_BT_TX_2480_1DH1_RESP,
CMD_TEST_RF_BT_TX_2402_2DH3,
CMD_TEST_RF_BT_TX_2402_2DH3_RESP,
CMD_TEST_RF_BT_TX_2440_2DH3,
CMD_TEST_RF_BT_TX_2440_2DH3_RESP,
CMD_TEST_RF_BT_TX_2480_2DH3,
CMD_TEST_RF_BT_TX_2480_2DH3_RESP,
CMD_TEST_RF_BT_TX_2402_3DH5,
CMD_TEST_RF_BT_TX_2402_3DH5_RESP,
CMD_TEST_RF_BT_TX_2440_3DH5,
CMD_TEST_RF_BT_TX_2440_3DH5_RESP,
CMD_TEST_RF_BT_TX_2480_3DH5,
CMD_TEST_RF_BT_TX_2480_3DH5_RESP,
// varible extend--->
CMD_TEST_RF_BT_TX_VARIABLE = 0x22f0,
CMD_TEST_RF_BT_TX_VARIABLE_RESP,
//<----varible extend
CMD_TEST_RF_BT_RX = 0x2300,
CMD_TEST_RF_BT_RX_RESP,
CMD_TEST_RF_BT_RX_2402_1DH1,
CMD_TEST_RF_BT_RX_2402_1DH1_RESP,
CMD_TEST_RF_BT_RX_2440_1DH1,
CMD_TEST_RF_BT_RX_2440_1DH1_RESP,
CMD_TEST_RF_BT_RX_2480_1DH1,
CMD_TEST_RF_BT_RX_2480_1DH1_RESP,
CMD_TEST_RF_BT_RX_2402_2DH3,
CMD_TEST_RF_BT_RX_2402_2DH3_RESP,
CMD_TEST_RF_BT_RX_2440_2DH3,
CMD_TEST_RF_BT_RX_2440_2DH3_RESP,
CMD_TEST_RF_BT_RX_2480_2DH3,
CMD_TEST_RF_BT_RX_2480_2DH3_RESP,
CMD_TEST_RF_BT_RX_2402_3DH5,
CMD_TEST_RF_BT_RX_2402_3DH5_RESP,
CMD_TEST_RF_BT_RX_2440_3DH5,
CMD_TEST_RF_BT_RX_2440_3DH5_RESP,
CMD_TEST_RF_BT_RX_2480_3DH5,
CMD_TEST_RF_BT_RX_2480_3DH5_RESP,
// varible extend--->
CMD_TEST_RF_BT_RX_VARIABLE = 0x23f0,
CMD_TEST_RF_BT_RX_VARIABLE_RESP,
//<----varible extend
CMD_TEST_RF_BT_EXIT = 0x2400,
CMD_TEST_RF_BT_EXIT_RESP,
CMD_TEST_RF_WIFI_ENTER = 0x2500,
CMD_TEST_RF_WIFI_ENTER_RESP,
CMD_TEST_RF_WIFI_TX = 0x2600,
CMD_TEST_RF_WIFI_TX_RESP,
CMD_TEST_RF_WIFI_TX_CHANNEL1,
CMD_TEST_RF_WIFI_TX_CHANNEL1_RESP,
CMD_TEST_RF_WIFI_TX_CHANNEL7,
CMD_TEST_RF_WIFI_TX_CHANNEL7_RESP,
CMD_TEST_RF_WIFI_TX_CHANNEL13,
CMD_TEST_RF_WIFI_TX_CHANNEL13_RESP,
// varible extend--->
CMD_TEST_RF_WIFI_TX_VARIABLE = 0x26f0,
CMD_TEST_RF_WIFI_TX_VARIABLE_RESP,
//<----varible extend
CMD_TEST_RF_WIFI_RX = 0x2700,
CMD_TEST_RF_WIFI_RX_RESP,
CMD_TEST_RF_WIFI_RX_CHANNEL1,
CMD_TEST_RF_WIFI_RX_CHANNEL1_RESP,
CMD_TEST_RF_WIFI_RX_CHANNEL1_RET,
CMD_TEST_RF_WIFI_RX_CHANNEL1_RET_RESP,
CMD_TEST_RF_WIFI_RX_CHANNEL7,
CMD_TEST_RF_WIFI_RX_CHANNEL7_RESP,
CMD_TEST_RF_WIFI_RX_CHANNEL7_RET,
CMD_TEST_RF_WIFI_RX_CHANNEL7_RET_RESP,
CMD_TEST_RF_WIFI_RX_CHANNEL13,
CMD_TEST_RF_WIFI_RX_CHANNEL13_RESP,
CMD_TEST_RF_WIFI_RX_CHANNEL13_RET,
CMD_TEST_RF_WIFI_RX_CHANNEL13_RET_RESP,
// varible extend--->
CMD_TEST_RF_WIFI_RX_VARIABLE = 0x27f0,
CMD_TEST_RF_WIFI_RX_VARIABLE_RESP,
//<----varible extend
CMD_TEST_RF_WIFI_EXIT = 0x2800,
CMD_TEST_RF_WIFI_EXIT_RESP,
CMD_TEST_MCU_LED_GUIDE = 0X2900,
CMD_TEST_MCU_LED_GUIDE_RSP,
CMD_TEST_MCU_LED_MATRIX,
CMD_TEST_MCU_LED_MATRIX_RSP,
//<-----RF cmd
CMD_TEST_RELEASE_SYSTEM,
CMD_ALARM_SYNC_REQ = 0xF000,
CMD_ALARM_SYNC_RSP,
CMD_ALARM_ADD,
CMD_ALARM_REMOVE,
CMD_ALARM_REMOVEALL,
CMD_REMAIND_SYNC_REQ,
CMD_REMAIND_SYNC_RSP,
CMD_REMAIND_ADD,
CMD_REMAIND_REMOVE,
CMD_REMAIND_REMOVEALL,
CMD_ASSISTANT_STATUS,
CMD_ASSISTANT_RUNNING,
CMD_ASSISTANT_NOTIFY,
CMD_SESSION_ALARM_SYNC,
CMD_WORKDAY_DB_REQ = 0xF100,
CMD_WORKDAY_DB_RSP,
CMD_OTA_NOTIFY = 0xF200,
CMD_OTA_STATUS,
CMD_OTA_RUNNOW,
CMD_LOG_CONFIG = 0xF300,
CMD_DEMO_PERFORM_TEST = 0xff00,
} DBUS_CMD;
typedef enum {
ERR_INPUT_PARAMS = 1,
ERR_NO_ITEMS,
ERR_GET_BUS,
ERR_DBUS_CONNECTION,
ERR_REQUEST_BUS_NAME,
ERR_SET_WATCH_FUNCTION,
ERR_SET_TIMEOUT_FUNCTION,
ERR_BUS_MATCH,
ERR_BUS_SET_MSG_CB,
ERR_DBUS_CREATE_MSG,
ERR_BUS_SEND_MSG,
ERR_DBUS_MSG_TO_LARGE,
ERR_BUS_RCV_MSG,
ERR_ADD_TASK,
ERR_UNSUP_EVP_TYPE,
ERR_CREATE_MQ,
ERR_MQ_SENDMSG,
ERR_CREATE_SHM,
ERR_MAP_SHM,
ERR_MALLOC_MEMORY,
ERR_EVP_INIT_KEY,
ERR_EVP_UPDATE,
ERR_EVP_FINALE,
ERR_EVP_KEY_SIZE,
ERR_OPEN_FILE,
ERR_READ_FILE,
ERR_WRITE_FILE,
ERR_COPY_FILE,
ERR_FILE_NOT_EXISTS,
ERR_GET_FILE_SIZE,
ERR_UNINIT_ITEM,
ERR_FILE_EMPTY,
ERR_SEND_MAIL,
ERR_NETWORK_SEND,
ERR_NETWORK_NOT_CONNECTED,
ERR_UNSUPPORT,
} DBUS_WITH_LIBUV_ERROR;
/**
*
*/
typedef enum {
ERR_NO_INIT_IPL3 = 2000, ///< (0xF101) 未初始化OTA参数
ERR_BAD_IPL3, ///< OTA参数异常
ERR_BAD_FILE_SIZE, ///< 文件大小不正确
ERR_MD5_FILE, ///< 计算文件MD5校验和异常
ERR_MD5_CHECK_SUM, ///< MD5校验和不正确
ERR_OTA_WRITE_BOOT, ///< 写入BOOT分区异常
ERR_OTA_WRITE_ROOTFS, ///< 写入ROOTFS分区异常
ERR_OTA_WRITE_IPL3, ///< 写入IPL3分区异常
ERR_OTA_WRITE_PARAMS, ///< 写入OTA参数异常
ERR_OTA_DOWNLOAD_FILE, ///< 下载文件失败
ERR_VERIFY_PARTITION_MD5, ///< 校验分区MD5异常
ERR_OTA_PRE_STATR, ///< 先前已经启动了一个未完成的OTA任务
ERR_OTA_YET_CUR_VER, ///< 当前版本已经更新
ERR_OTA_NOT_READY, ///< OTA未准备好暂时不能进行OTA升级
} OTA_ERROR;
typedef enum {
ERR_CREATE_CFG_FILE = 1000,
ERR_CREATE_SQLITE3_DB,
ERR_OPEN_SQLITE3_DB,
ERR_SQLITE3_CREATE_TABLE,
ERR_SYNC_DATABASE,
ERR_SQL_QUERY,
ERR_SQL_DELETE,
ERR_UNKNOWN_TYPE,
ERR_PERMISSION_DENIED,
ERR_CFG_NOITEM,
ERR_CFG_ITEM_EXIST,
ERR_CFG_WAIT_RSP,
ERR_CFG_BUSY,
ERR_STR_CONVERT,
ERR_SQL_REG_MODULE,
} CONFIG_MODE_ERRCODE;
typedef enum {
REPEAT_MODE_NONE = 1,
REPEAT_MODE_EVERY_DAY = 2,
REPEAT_MODE_WORKDAY = 3,
REPEAT_MODE_WEEKEND = 4,
REPEAT_MODE_WEEKDAY = 5,
REPEAT_MODE_EVERY_MONTH_DAY = 6,
REPEAT_MODE_EVERY_YEAR_DAY = 7,
REPEAT_MODE_EVERY_TIME = 8,
REPEAT_MODE_MONTH_LAST_DAY = 9,
REPEAT_MODE_HOLIDAY = 10,
} REPEAT_MODE;
#define MAX_CFG_KEY_NAME (256)
#define MAX_CFG_KEY_VALUE (1024)
#define DATA_TIME_STR_LEN (20)
#define GET_FILE_SIZE(path, size) \
do { \
struct stat st; \
memset(&st, 0, sizeof(struct stat)); \
if (stat(path, &st) != 0) { \
size = -1; \
} else { \
size = st.st_size; \
} \
} while (0)
#ifdef __cplusplus
}
#endif
#endif

154
linux32/inc/cjson/cJSON.h Normal file
View File

@ -0,0 +1,154 @@
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef cJSON__h
#define cJSON__h
#include <stddef.h>
#ifdef __cplusplus
extern "C"
{
#endif
/* cJSON Types: */
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6
#define cJSON_IsReference 256
#define cJSON_StringIsConst 512
/* The cJSON structure: */
typedef struct cJSON {
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
typedef struct cJSON_Hooks {
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
extern int cJSON_HasObjectItem(cJSON *object,const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item);
/* Remove/Detatch items from Arrays/Objects. */
extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which);
extern void cJSON_DeleteItemFromArray(cJSON *array,int which);
extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string);
extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string);
/* Update array items. */
extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */
extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem);
extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
/* Duplicate a cJSON item */
extern cJSON *cJSON_Duplicate(cJSON *item,int recurse);
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
need to be released. With recurse!=0, it will duplicate any children connected to the item.
The item->next and ->prev pointers are always zero on return from Duplicate. */
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated);
extern void cJSON_Minify(char *json);
/* Macros for creating things quickly. */
#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val))
/* Macro for iterating over an array */
#define cJSON_ArrayForEach(pos, head) for(pos = (head)->child; pos != NULL; pos = pos->next)
#ifdef __cplusplus
}
#endif
#endif

91
linux32/inc/cjson/s2j.h Normal file
View File

@ -0,0 +1,91 @@
/*
* This file is part of the struct2json Library.
*
* Copyright (c) 2015, Armink, <armink.ztl@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Function: It is an head file for this library. You can see all be called functions.
* Created on: 2015-10-14
*/
#ifndef __S2J_H__
#define __S2J_H__
#include <cJSON.h>
#include <string.h>
#include "s2jdef.h"
#ifdef __cplusplus
extern "C" {
#endif
/* struct2json software version number */
#define S2J_SW_VERSION "1.0.3"
/* Create JSON object */
#define s2j_create_json_obj(json_obj) \
S2J_CREATE_JSON_OBJECT(json_obj)
/* Delete JSON object */
#define s2j_delete_json_obj(json_obj) \
S2J_DELETE_JSON_OBJECT(json_obj)
/* Set basic type element for JSON object */
#define s2j_json_set_basic_element(to_json, from_struct, type, element) \
S2J_JSON_SET_BASIC_ELEMENT(to_json, from_struct, type, element)
/* Set array type element for JSON object */
#define s2j_json_set_array_element(to_json, from_struct, type, element, size) \
S2J_JSON_SET_ARRAY_ELEMENT(to_json, from_struct, type, element, size)
/* Set child structure type element for JSON object */
#define s2j_json_set_struct_element(child_json, to_json, child_struct, from_struct, type, element) \
S2J_JSON_SET_STRUCT_ELEMENT(child_json, to_json, child_struct, from_struct, type, element)
/* Create structure object */
#define s2j_create_struct_obj(struct_obj, type) \
S2J_CREATE_STRUCT_OBJECT(struct_obj, type)
/* Delete structure object */
#define s2j_delete_struct_obj(struct_obj) \
S2J_DELETE_STRUCT_OBJECT(struct_obj)
/* Get basic type element for structure object */
#define s2j_struct_get_basic_element(to_struct, from_json, type, element) \
S2J_STRUCT_GET_BASIC_ELEMENT(to_struct, from_json, type, element)
/* Get array type element for structure object */
#define s2j_struct_get_array_element(to_struct, from_json, type, element) \
S2J_STRUCT_GET_ARRAY_ELEMENT(to_struct, from_json, type, element)
/* Get child structure type element for structure object */
#define s2j_struct_get_struct_element(child_struct, to_struct, child_json, from_json, type, element) \
S2J_STRUCT_GET_STRUCT_ELEMENT(child_struct, to_struct, child_json, from_json, type, element)
/* s2j.c */
extern S2jHook s2jHook;
void s2j_init(S2jHook *hook);
#ifdef __cplusplus
}
#endif
#endif /* __S2J_H__ */

150
linux32/inc/cjson/s2jdef.h Normal file
View File

@ -0,0 +1,150 @@
/*
* This file is part of the struct2json Library.
*
* Copyright (c) 2015, Armink, <armink.ztl@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Function: It is an head file for this library.
* Created on: 2015-10-14
*/
#ifndef __S2JDEF_H__
#define __S2JDEF_H__
#include <cJSON.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} S2jHook, *S2jHook_t;
#define S2J_STRUCT_GET_int_ELEMENT(to_struct, from_json, _element) \
json_temp = cJSON_GetObjectItem(from_json, #_element); \
if (json_temp) (to_struct)->_element = json_temp->valueint;
#define S2J_STRUCT_GET_string_ELEMENT(to_struct, from_json, _element) \
json_temp = cJSON_GetObjectItem(from_json, #_element); \
if (json_temp) strcpy((to_struct)->_element, json_temp->valuestring);
#define S2J_STRUCT_GET_double_ELEMENT(to_struct, from_json, _element) \
json_temp = cJSON_GetObjectItem(from_json, #_element); \
if (json_temp) (to_struct)->_element = json_temp->valuedouble;
#define S2J_STRUCT_ARRAY_GET_int_ELEMENT(to_struct, from_json, _element, index) \
(to_struct)->_element[index] = from_json->valueint;
#define S2J_STRUCT_ARRAY_GET_string_ELEMENT(to_struct, from_json, _element, index) \
strcpy((to_struct)->_element[index], from_json->valuestring);
#define S2J_STRUCT_ARRAY_GET_double_ELEMENT(to_struct, from_json, _element, index) \
(to_struct)->_element[index] = from_json->valuedouble;
#define S2J_STRUCT_ARRAY_GET_ELEMENT(to_struct, from_json, type, _element, index) \
S2J_STRUCT_ARRAY_GET_##type##_ELEMENT(to_struct, from_json, _element, index)
#define S2J_JSON_SET_int_ELEMENT(to_json, from_struct, _element) \
cJSON_AddNumberToObject(to_json, #_element, (from_struct)->_element);
#define S2J_JSON_SET_double_ELEMENT(to_json, from_struct, _element) \
cJSON_AddNumberToObject(to_json, #_element, (from_struct)->_element);
#define S2J_JSON_SET_string_ELEMENT(to_json, from_struct, _element) \
cJSON_AddStringToObject(to_json, #_element, (from_struct)->_element);
#define S2J_JSON_ARRAY_SET_int_ELEMENT(to_json, from_struct, _element, index) \
cJSON_AddItemToArray(to_json, cJSON_CreateNumber((from_struct)->_element[index]));
#define S2J_JSON_ARRAY_SET_double_ELEMENT(to_json, from_struct, _element, index) \
cJSON_AddItemToArray(to_json, cJSON_CreateNumber((from_struct)->_element[index]));
#define S2J_JSON_ARRAY_SET_string_ELEMENT(to_json, from_struct, _element, index) \
cJSON_AddItemToArray(to_json, cJSON_CreateString((from_struct)->_element[index]));
#define S2J_JSON_ARRAY_SET_ELEMENT(to_json, from_struct, type, _element, index) \
S2J_JSON_ARRAY_SET_##type##_ELEMENT(to_json, from_struct, _element, index)
#define S2J_CREATE_JSON_OBJECT(json_obj) \
cJSON *json_obj = cJSON_CreateObject();
#define S2J_DELETE_JSON_OBJECT(json_obj) \
cJSON_Delete(json_obj);
#define S2J_JSON_SET_BASIC_ELEMENT(to_json, from_struct, type, _element) \
S2J_JSON_SET_##type##_ELEMENT(to_json, from_struct, _element)
#define S2J_JSON_SET_ARRAY_ELEMENT(to_json, from_struct, type, _element, size) \
{ \
cJSON *array; \
size_t index = 0; \
array = cJSON_CreateArray(); \
if (array) { \
while (index < size) { \
S2J_JSON_ARRAY_SET_ELEMENT(array, from_struct, type, _element, index++); \
} \
cJSON_AddItemToObject(to_json, #_element, array); \
} \
}
#define S2J_JSON_SET_STRUCT_ELEMENT(child_json, to_json, child_struct, from_struct, type, _element) \
type *child_struct = &((from_struct)->_element); \
cJSON *child_json = cJSON_CreateObject(); \
if (child_json) cJSON_AddItemToObject(to_json, #_element, child_json);
#define S2J_CREATE_STRUCT_OBJECT(struct_obj, type) \
cJSON *json_temp; \
type *struct_obj = s2jHook.malloc_fn(sizeof(type)); \
if (struct_obj) memset(struct_obj, 0, sizeof(type));
#define S2J_DELETE_STRUCT_OBJECT(struct_obj) \
s2jHook.free_fn(struct_obj);
#define S2J_STRUCT_GET_BASIC_ELEMENT(to_struct, from_json, type, _element) \
S2J_STRUCT_GET_##type##_ELEMENT(to_struct, from_json, _element)
#define S2J_STRUCT_GET_ARRAY_ELEMENT(to_struct, from_json, type, _element) \
{ \
cJSON *array, *array_element; \
size_t index = 0, size = 0; \
array = cJSON_GetObjectItem(from_json, #_element); \
if (array) { \
size = cJSON_GetArraySize(array); \
while (index < size) { \
array_element = cJSON_GetArrayItem(array, index); \
if (array_element) S2J_STRUCT_ARRAY_GET_ELEMENT(to_struct, array_element, type, _element, index++); \
} \
} \
}
#define S2J_STRUCT_GET_STRUCT_ELEMENT(child_struct, to_struct, child_json, from_json, type, _element) \
type *child_struct = &((to_struct)->_element); \
cJSON *child_json = cJSON_GetObjectItem(from_json, #_element);
#ifdef __cplusplus
}
#endif
#endif /* __S2JDEF_H__ */

View File

@ -0,0 +1,238 @@
/*
Copyright (c) 2008-2017, Troy D. Hanson http://troydhanson.github.com/uthash/
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* a dynamic array implementation using macros
*/
#ifndef UTARRAY_H
#define UTARRAY_H
#define UTARRAY_VERSION 2.0.2
#include <stddef.h> /* size_t */
#include <string.h> /* memset, etc */
#include <stdlib.h> /* exit */
#ifdef __GNUC__
#define UTARRAY_UNUSED __attribute__((__unused__))
#else
#define UTARRAY_UNUSED
#endif
#ifndef oom
#define oom() exit(-1)
#endif
typedef void (ctor_f)(void *dst, const void *src);
typedef void (dtor_f)(void *elt);
typedef void (init_f)(void *elt);
typedef struct {
size_t sz;
init_f *init;
ctor_f *copy;
dtor_f *dtor;
} UT_icd;
typedef struct {
unsigned i,n;/* i: index of next available slot, n: num slots */
UT_icd icd; /* initializer, copy and destructor functions */
char *d; /* n slots of size icd->sz*/
} UT_array;
#define utarray_init(a,_icd) do { \
memset(a,0,sizeof(UT_array)); \
(a)->icd = *(_icd); \
} while(0)
#define utarray_done(a) do { \
if ((a)->n) { \
if ((a)->icd.dtor) { \
unsigned _ut_i; \
for(_ut_i=0; _ut_i < (a)->i; _ut_i++) { \
(a)->icd.dtor(utarray_eltptr(a,_ut_i)); \
} \
} \
free((a)->d); \
} \
(a)->n=0; \
} while(0)
#define utarray_new(a,_icd) do { \
(a) = (UT_array*)malloc(sizeof(UT_array)); \
if ((a) == NULL) oom(); \
utarray_init(a,_icd); \
} while(0)
#define utarray_free(a) do { \
utarray_done(a); \
free(a); \
} while(0)
#define utarray_reserve(a,by) do { \
if (((a)->i+(by)) > (a)->n) { \
char *utarray_tmp; \
while (((a)->i+(by)) > (a)->n) { (a)->n = ((a)->n ? (2*(a)->n) : 8); } \
utarray_tmp=(char*)realloc((a)->d, (a)->n*(a)->icd.sz); \
if (utarray_tmp == NULL) oom(); \
(a)->d=utarray_tmp; \
} \
} while(0)
#define utarray_push_back(a,p) do { \
utarray_reserve(a,1); \
if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,(a)->i++), p); } \
else { memcpy(_utarray_eltptr(a,(a)->i++), p, (a)->icd.sz); }; \
} while(0)
#define utarray_pop_back(a) do { \
if ((a)->icd.dtor) { (a)->icd.dtor( _utarray_eltptr(a,--((a)->i))); } \
else { (a)->i--; } \
} while(0)
#define utarray_extend_back(a) do { \
utarray_reserve(a,1); \
if ((a)->icd.init) { (a)->icd.init(_utarray_eltptr(a,(a)->i)); } \
else { memset(_utarray_eltptr(a,(a)->i),0,(a)->icd.sz); } \
(a)->i++; \
} while(0)
#define utarray_len(a) ((a)->i)
#define utarray_eltptr(a,j) (((j) < (a)->i) ? _utarray_eltptr(a,j) : NULL)
#define _utarray_eltptr(a,j) ((a)->d + ((a)->icd.sz * (j)))
#define utarray_insert(a,p,j) do { \
if ((j) > (a)->i) utarray_resize(a,j); \
utarray_reserve(a,1); \
if ((j) < (a)->i) { \
memmove( _utarray_eltptr(a,(j)+1), _utarray_eltptr(a,j), \
((a)->i - (j))*((a)->icd.sz)); \
} \
if ((a)->icd.copy) { (a)->icd.copy( _utarray_eltptr(a,j), p); } \
else { memcpy(_utarray_eltptr(a,j), p, (a)->icd.sz); }; \
(a)->i++; \
} while(0)
#define utarray_inserta(a,w,j) do { \
if (utarray_len(w) == 0) break; \
if ((j) > (a)->i) utarray_resize(a,j); \
utarray_reserve(a,utarray_len(w)); \
if ((j) < (a)->i) { \
memmove(_utarray_eltptr(a,(j)+utarray_len(w)), \
_utarray_eltptr(a,j), \
((a)->i - (j))*((a)->icd.sz)); \
} \
if ((a)->icd.copy) { \
unsigned _ut_i; \
for(_ut_i=0;_ut_i<(w)->i;_ut_i++) { \
(a)->icd.copy(_utarray_eltptr(a, (j) + _ut_i), _utarray_eltptr(w, _ut_i)); \
} \
} else { \
memcpy(_utarray_eltptr(a,j), _utarray_eltptr(w,0), \
utarray_len(w)*((a)->icd.sz)); \
} \
(a)->i += utarray_len(w); \
} while(0)
#define utarray_resize(dst,num) do { \
unsigned _ut_i; \
if ((dst)->i > (unsigned)(num)) { \
if ((dst)->icd.dtor) { \
for (_ut_i = (num); _ut_i < (dst)->i; ++_ut_i) { \
(dst)->icd.dtor(_utarray_eltptr(dst, _ut_i)); \
} \
} \
} else if ((dst)->i < (unsigned)(num)) { \
utarray_reserve(dst, (num) - (dst)->i); \
if ((dst)->icd.init) { \
for (_ut_i = (dst)->i; _ut_i < (unsigned)(num); ++_ut_i) { \
(dst)->icd.init(_utarray_eltptr(dst, _ut_i)); \
} \
} else { \
memset(_utarray_eltptr(dst, (dst)->i), 0, (dst)->icd.sz*((num) - (dst)->i)); \
} \
} \
(dst)->i = (num); \
} while(0)
#define utarray_concat(dst,src) do { \
utarray_inserta(dst, src, utarray_len(dst)); \
} while(0)
#define utarray_erase(a,pos,len) do { \
if ((a)->icd.dtor) { \
unsigned _ut_i; \
for (_ut_i = 0; _ut_i < (len); _ut_i++) { \
(a)->icd.dtor(utarray_eltptr(a, (pos) + _ut_i)); \
} \
} \
if ((a)->i > ((pos) + (len))) { \
memmove(_utarray_eltptr(a, pos), _utarray_eltptr(a, (pos) + (len)), \
((a)->i - ((pos) + (len))) * (a)->icd.sz); \
} \
(a)->i -= (len); \
} while(0)
#define utarray_renew(a,u) do { \
if (a) utarray_clear(a); \
else utarray_new(a, u); \
} while(0)
#define utarray_clear(a) do { \
if ((a)->i > 0) { \
if ((a)->icd.dtor) { \
unsigned _ut_i; \
for(_ut_i=0; _ut_i < (a)->i; _ut_i++) { \
(a)->icd.dtor(_utarray_eltptr(a, _ut_i)); \
} \
} \
(a)->i = 0; \
} \
} while(0)
#define utarray_sort(a,cmp) do { \
qsort((a)->d, (a)->i, (a)->icd.sz, cmp); \
} while(0)
#define utarray_find(a,v,cmp) bsearch((v),(a)->d,(a)->i,(a)->icd.sz,cmp)
#define utarray_front(a) (((a)->i) ? (_utarray_eltptr(a,0)) : NULL)
#define utarray_next(a,e) (((e)==NULL) ? utarray_front(a) : ((((a)->i) > (utarray_eltidx(a,e)+1)) ? _utarray_eltptr(a,utarray_eltidx(a,e)+1) : NULL))
#define utarray_prev(a,e) (((e)==NULL) ? utarray_back(a) : ((utarray_eltidx(a,e) > 0) ? _utarray_eltptr(a,utarray_eltidx(a,e)-1) : NULL))
#define utarray_back(a) (((a)->i) ? (_utarray_eltptr(a,(a)->i-1)) : NULL)
#define utarray_eltidx(a,e) (((char*)(e) >= (a)->d) ? (((char*)(e) - (a)->d)/(a)->icd.sz) : -1)
/* last we pre-define a few icd for common utarrays of ints and strings */
static void utarray_str_cpy(void *dst, const void *src) {
char **_src = (char**)src, **_dst = (char**)dst;
*_dst = (*_src == NULL) ? NULL : strdup(*_src);
}
static void utarray_str_dtor(void *elt) {
char **eltc = (char**)elt;
if (*eltc != NULL) free(*eltc);
}
static const UT_icd ut_str_icd UTARRAY_UNUSED = {sizeof(char*),NULL,utarray_str_cpy,utarray_str_dtor};
static const UT_icd ut_int_icd UTARRAY_UNUSED = {sizeof(int),NULL,NULL,NULL};
static const UT_icd ut_ptr_icd UTARRAY_UNUSED = {sizeof(void*),NULL,NULL,NULL};
#endif /* UTARRAY_H */

1107
linux32/inc/uthash/uthash.h Normal file

File diff suppressed because it is too large Load Diff

1073
linux32/inc/uthash/utlist.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,108 @@
/*
Copyright (c) 2008-2017, Troy D. Hanson http://troydhanson.github.com/uthash/
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* a ring-buffer implementation using macros
*/
#ifndef UTRINGBUFFER_H
#define UTRINGBUFFER_H
#define UTRINGBUFFER_VERSION 2.0.2
#include <stdlib.h>
#include <string.h>
#include "utarray.h" // for "UT_icd"
typedef struct {
unsigned i; /* index of next available slot; wraps at n */
unsigned n; /* capacity */
unsigned char f; /* full */
UT_icd icd; /* initializer, copy and destructor functions */
char *d; /* n slots of size icd->sz */
} UT_ringbuffer;
#define utringbuffer_init(a, _n, _icd) do { \
memset(a, 0, sizeof(UT_ringbuffer)); \
(a)->icd = *(_icd); \
(a)->n = (_n); \
if ((a)->n) { (a)->d = (char*)malloc((a)->n * (_icd)->sz); } \
} while(0)
#define utringbuffer_clear(a) do { \
if ((a)->icd.dtor) { \
if ((a)->f) { \
unsigned _ut_i; \
for (_ut_i = 0; _ut_i < (a)->n; ++_ut_i) { \
(a)->icd.dtor(utringbuffer_eltptr(a, _ut_i)); \
} \
} else { \
unsigned _ut_i; \
for (_ut_i = 0; _ut_i < (a)->i; ++_ut_i) { \
(a)->icd.dtor(utringbuffer_eltptr(a, _ut_i)); \
} \
} \
} \
(a)->i = 0; \
(a)->f = 0; \
} while(0)
#define utringbuffer_done(a) do { \
utringbuffer_clear(a); \
free((a)->d); (a)->d = NULL; \
(a)->n = 0; \
} while(0)
#define utringbuffer_new(a,n,_icd) do { \
a = (UT_ringbuffer*)malloc(sizeof(UT_ringbuffer)); \
utringbuffer_init(a, n, _icd); \
} while(0)
#define utringbuffer_free(a) do { \
utringbuffer_done(a); \
free(a); \
} while(0)
#define utringbuffer_push_back(a,p) do { \
if ((a)->icd.dtor && (a)->f) { (a)->icd.dtor(_utringbuffer_internalptr(a,(a)->i)); } \
if ((a)->icd.copy) { (a)->icd.copy( _utringbuffer_internalptr(a,(a)->i), p); } \
else { memcpy(_utringbuffer_internalptr(a,(a)->i), p, (a)->icd.sz); }; \
if (++(a)->i == (a)->n) { (a)->i = 0; (a)->f = 1; } \
} while(0)
#define utringbuffer_len(a) ((a)->f ? (a)->n : (a)->i)
#define utringbuffer_empty(a) ((a)->i == 0 && !(a)->f)
#define utringbuffer_full(a) ((a)->f != 0)
#define _utringbuffer_real_idx(a,j) ((a)->f ? ((j) + (a)->i) % (a)->n : (j))
#define _utringbuffer_internalptr(a,j) ((void*)((a)->d + ((a)->icd.sz * (j))))
#define utringbuffer_eltptr(a,j) ((0 <= (j) && (j) < utringbuffer_len(a)) ? _utringbuffer_internalptr(a,_utringbuffer_real_idx(a,j)) : NULL)
#define _utringbuffer_fake_idx(a,j) ((a)->f ? ((j) + (a)->n - (a)->i) % (a)->n : (j))
#define _utringbuffer_internalidx(a,e) (((char*)(e) >= (a)->d) ? (((char*)(e) - (a)->d)/(a)->icd.sz) : -1)
#define utringbuffer_eltidx(a,e) _utringbuffer_fake_idx(a, _utringbuffer_internalidx(a,e))
#define utringbuffer_front(a) utringbuffer_eltptr(a,0)
#define utringbuffer_next(a,e) ((e)==NULL ? utringbuffer_front(a) : utringbuffer_eltptr(a, utringbuffer_eltidx(a,e)+1))
#define utringbuffer_prev(a,e) ((e)==NULL ? utringbuffer_back(a) : utringbuffer_eltptr(a, utringbuffer_eltidx(a,e)-1))
#define utringbuffer_back(a) (utringbuffer_empty(a) ? NULL : utringbuffer_eltptr(a, utringbuffer_len(a) - 1))
#endif /* UTRINGBUFFER_H */

View File

@ -0,0 +1,398 @@
/*
Copyright (c) 2008-2017, Troy D. Hanson http://troydhanson.github.com/uthash/
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* a dynamic string implementation using macros
*/
#ifndef UTSTRING_H
#define UTSTRING_H
#define UTSTRING_VERSION 2.0.2
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#ifdef __GNUC__
#define UTSTRING_UNUSED __attribute__((__unused__))
#else
#define UTSTRING_UNUSED
#endif
#ifndef oom
#define oom() exit(-1)
#endif
typedef struct {
char *d;
size_t n; /* allocd size */
size_t i; /* index of first unused byte */
} UT_string;
#define utstring_reserve(s,amt) \
do { \
if (((s)->n - (s)->i) < (size_t)(amt)) { \
char *utstring_tmp = (char*)realloc( \
(s)->d, (s)->n + (amt)); \
if (utstring_tmp == NULL) oom(); \
(s)->d = utstring_tmp; \
(s)->n += (amt); \
} \
} while(0)
#define utstring_init(s) \
do { \
(s)->n = 0; (s)->i = 0; (s)->d = NULL; \
utstring_reserve(s,100); \
(s)->d[0] = '\0'; \
} while(0)
#define utstring_done(s) \
do { \
if ((s)->d != NULL) free((s)->d); \
(s)->n = 0; \
} while(0)
#define utstring_free(s) \
do { \
utstring_done(s); \
free(s); \
} while(0)
#define utstring_new(s) \
do { \
s = (UT_string*)calloc(sizeof(UT_string),1); \
if (!s) oom(); \
utstring_init(s); \
} while(0)
#define utstring_renew(s) \
do { \
if (s) { \
utstring_clear(s); \
} else { \
utstring_new(s); \
} \
} while(0)
#define utstring_clear(s) \
do { \
(s)->i = 0; \
(s)->d[0] = '\0'; \
} while(0)
#define utstring_bincpy(s,b,l) \
do { \
utstring_reserve((s),(l)+1); \
if (l) memcpy(&(s)->d[(s)->i], b, l); \
(s)->i += (l); \
(s)->d[(s)->i]='\0'; \
} while(0)
#define utstring_concat(dst,src) \
do { \
utstring_reserve((dst),((src)->i)+1); \
if ((src)->i) memcpy(&(dst)->d[(dst)->i], (src)->d, (src)->i); \
(dst)->i += (src)->i; \
(dst)->d[(dst)->i]='\0'; \
} while(0)
#define utstring_len(s) ((s)->i)
#define utstring_body(s) ((s)->d)
UTSTRING_UNUSED static void utstring_printf_va(UT_string *s, const char *fmt, va_list ap) {
int n;
va_list cp;
for (;;) {
#ifdef _WIN32
cp = ap;
#else
va_copy(cp, ap);
#endif
n = vsnprintf (&s->d[s->i], s->n-s->i, fmt, cp);
va_end(cp);
if ((n > -1) && ((size_t) n < (s->n-s->i))) {
s->i += n;
return;
}
/* Else try again with more space. */
if (n > -1) utstring_reserve(s,n+1); /* exact */
else utstring_reserve(s,(s->n)*2); /* 2x */
}
}
#ifdef __GNUC__
/* support printf format checking (2=the format string, 3=start of varargs) */
static void utstring_printf(UT_string *s, const char *fmt, ...)
__attribute__ (( format( printf, 2, 3) ));
#endif
UTSTRING_UNUSED static void utstring_printf(UT_string *s, const char *fmt, ...) {
va_list ap;
va_start(ap,fmt);
utstring_printf_va(s,fmt,ap);
va_end(ap);
}
/*******************************************************************************
* begin substring search functions *
******************************************************************************/
/* Build KMP table from left to right. */
UTSTRING_UNUSED static void _utstring_BuildTable(
const char *P_Needle,
size_t P_NeedleLen,
long *P_KMP_Table)
{
long i, j;
i = 0;
j = i - 1;
P_KMP_Table[i] = j;
while (i < (long) P_NeedleLen)
{
while ( (j > -1) && (P_Needle[i] != P_Needle[j]) )
{
j = P_KMP_Table[j];
}
i++;
j++;
if (i < (long) P_NeedleLen)
{
if (P_Needle[i] == P_Needle[j])
{
P_KMP_Table[i] = P_KMP_Table[j];
}
else
{
P_KMP_Table[i] = j;
}
}
else
{
P_KMP_Table[i] = j;
}
}
return;
}
/* Build KMP table from right to left. */
UTSTRING_UNUSED static void _utstring_BuildTableR(
const char *P_Needle,
size_t P_NeedleLen,
long *P_KMP_Table)
{
long i, j;
i = P_NeedleLen - 1;
j = i + 1;
P_KMP_Table[i + 1] = j;
while (i >= 0)
{
while ( (j < (long) P_NeedleLen) && (P_Needle[i] != P_Needle[j]) )
{
j = P_KMP_Table[j + 1];
}
i--;
j--;
if (i >= 0)
{
if (P_Needle[i] == P_Needle[j])
{
P_KMP_Table[i + 1] = P_KMP_Table[j + 1];
}
else
{
P_KMP_Table[i + 1] = j;
}
}
else
{
P_KMP_Table[i + 1] = j;
}
}
return;
}
/* Search data from left to right. ( Multiple search mode. ) */
UTSTRING_UNUSED static long _utstring_find(
const char *P_Haystack,
size_t P_HaystackLen,
const char *P_Needle,
size_t P_NeedleLen,
long *P_KMP_Table)
{
long i, j;
long V_FindPosition = -1;
/* Search from left to right. */
i = j = 0;
while ( (j < (int)P_HaystackLen) && (((P_HaystackLen - j) + i) >= P_NeedleLen) )
{
while ( (i > -1) && (P_Needle[i] != P_Haystack[j]) )
{
i = P_KMP_Table[i];
}
i++;
j++;
if (i >= (int)P_NeedleLen)
{
/* Found. */
V_FindPosition = j - i;
break;
}
}
return V_FindPosition;
}
/* Search data from right to left. ( Multiple search mode. ) */
UTSTRING_UNUSED static long _utstring_findR(
const char *P_Haystack,
size_t P_HaystackLen,
const char *P_Needle,
size_t P_NeedleLen,
long *P_KMP_Table)
{
long i, j;
long V_FindPosition = -1;
/* Search from right to left. */
j = (P_HaystackLen - 1);
i = (P_NeedleLen - 1);
while ( (j >= 0) && (j >= i) )
{
while ( (i < (int)P_NeedleLen) && (P_Needle[i] != P_Haystack[j]) )
{
i = P_KMP_Table[i + 1];
}
i--;
j--;
if (i < 0)
{
/* Found. */
V_FindPosition = j + 1;
break;
}
}
return V_FindPosition;
}
/* Search data from left to right. ( One time search mode. ) */
UTSTRING_UNUSED static long utstring_find(
UT_string *s,
long P_StartPosition, /* Start from 0. -1 means last position. */
const char *P_Needle,
size_t P_NeedleLen)
{
long V_StartPosition;
long V_HaystackLen;
long *V_KMP_Table;
long V_FindPosition = -1;
if (P_StartPosition < 0)
{
V_StartPosition = s->i + P_StartPosition;
}
else
{
V_StartPosition = P_StartPosition;
}
V_HaystackLen = s->i - V_StartPosition;
if ( (V_HaystackLen >= (long) P_NeedleLen) && (P_NeedleLen > 0) )
{
V_KMP_Table = (long *)malloc(sizeof(long) * (P_NeedleLen + 1));
if (V_KMP_Table != NULL)
{
_utstring_BuildTable(P_Needle, P_NeedleLen, V_KMP_Table);
V_FindPosition = _utstring_find(s->d + V_StartPosition,
V_HaystackLen,
P_Needle,
P_NeedleLen,
V_KMP_Table);
if (V_FindPosition >= 0)
{
V_FindPosition += V_StartPosition;
}
free(V_KMP_Table);
}
}
return V_FindPosition;
}
/* Search data from right to left. ( One time search mode. ) */
UTSTRING_UNUSED static long utstring_findR(
UT_string *s,
long P_StartPosition, /* Start from 0. -1 means last position. */
const char *P_Needle,
size_t P_NeedleLen)
{
long V_StartPosition;
long V_HaystackLen;
long *V_KMP_Table;
long V_FindPosition = -1;
if (P_StartPosition < 0)
{
V_StartPosition = s->i + P_StartPosition;
}
else
{
V_StartPosition = P_StartPosition;
}
V_HaystackLen = V_StartPosition + 1;
if ( (V_HaystackLen >= (long) P_NeedleLen) && (P_NeedleLen > 0) )
{
V_KMP_Table = (long *)malloc(sizeof(long) * (P_NeedleLen + 1));
if (V_KMP_Table != NULL)
{
_utstring_BuildTableR(P_Needle, P_NeedleLen, V_KMP_Table);
V_FindPosition = _utstring_findR(s->d,
V_HaystackLen,
P_Needle,
P_NeedleLen,
V_KMP_Table);
free(V_KMP_Table);
}
}
return V_FindPosition;
}
/*******************************************************************************
* end substring search functions *
******************************************************************************/
#endif /* UTSTRING_H */

762
linux32/src/cJSON.c Normal file
View File

@ -0,0 +1,762 @@
/*
Copyright (c) 2009 Dave Gamble
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* cJSON */
/* JSON parser in C. */
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <limits.h>
#include <ctype.h>
#include "cJSON.h"
static const char *ep;
const char *cJSON_GetErrorPtr(void) {return ep;}
static int cJSON_strcasecmp(const char *s1,const char *s2)
{
if (!s1) return (s1==s2)?0:1;if (!s2) return 1;
for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0;
return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2);
}
static void *(*cJSON_malloc)(size_t sz) = malloc;
static void (*cJSON_free)(void *ptr) = free;
static char* cJSON_strdup(const char* str)
{
size_t len;
char* copy;
len = strlen(str) + 1;
if (!(copy = (char*)cJSON_malloc(len))) return 0;
memcpy(copy,str,len);
return copy;
}
void cJSON_InitHooks(cJSON_Hooks* hooks)
{
if (!hooks) { /* Reset hooks */
cJSON_malloc = malloc;
cJSON_free = free;
return;
}
cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc;
cJSON_free = (hooks->free_fn)?hooks->free_fn:free;
}
/* Internal constructor. */
static cJSON *cJSON_New_Item(void)
{
cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON));
if (node) memset(node,0,sizeof(cJSON));
return node;
}
/* Delete a cJSON structure. */
void cJSON_Delete(cJSON *c)
{
cJSON *next;
while (c)
{
next=c->next;
if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child);
if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring);
if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string);
cJSON_free(c);
c=next;
}
}
/* Parse the input text to generate a number, and populate the result into item. */
static const char *parse_number(cJSON *item,const char *num)
{
double n=0,sign=1,scale=0;int subscale=0,signsubscale=1;
if (*num=='-') sign=-1,num++; /* Has sign? */
if (*num=='0') num++; /* is zero */
if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */
if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */
if (*num=='e' || *num=='E') /* Exponent? */
{ num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */
while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */
}
n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */
item->valuedouble=n;
item->valueint=(int)n;
item->type=cJSON_Number;
return num;
}
static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; }
typedef struct {char *buffer; int length; int offset; } printbuffer;
static char* ensure(printbuffer *p,int needed)
{
char *newbuffer;int newsize;
if (!p || !p->buffer) return 0;
needed+=p->offset;
if (needed<=p->length) return p->buffer+p->offset;
newsize=pow2gt(needed);
newbuffer=(char*)cJSON_malloc(newsize);
if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;}
if (newbuffer) memcpy(newbuffer,p->buffer,p->length);
cJSON_free(p->buffer);
p->length=newsize;
p->buffer=newbuffer;
return newbuffer+p->offset;
}
static int update(printbuffer *p)
{
char *str;
if (!p || !p->buffer) return 0;
str=p->buffer+p->offset;
return p->offset+strlen(str);
}
/* Render the number nicely from the given item into a string. */
static char *print_number(cJSON *item,printbuffer *p)
{
char *str=0;
double d=item->valuedouble;
if (d==0)
{
if (p) str=ensure(p,2);
else str=(char*)cJSON_malloc(2); /* special case for 0. */
if (str) strcpy(str,"0");
}
else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN)
{
if (p) str=ensure(p,21);
else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */
if (str) sprintf(str,"%d",item->valueint);
}
else
{
if (p) str=ensure(p,64);
else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */
if (str)
{
if (fpclassify(d) != FP_ZERO && !isnormal(d)) sprintf(str,"null");
else if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60) sprintf(str,"%.0f",d);
else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d);
else sprintf(str,"%f",d);
}
}
return str;
}
static unsigned parse_hex4(const char *str)
{
unsigned h=0;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
h=h<<4;str++;
if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0;
return h;
}
/* Parse the input text into an unescaped cstring, and populate item. */
static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
static const char *parse_string(cJSON *item,const char *str)
{
const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2;
if (*str!='\"') {ep=str;return 0;} /* not a string! */
while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */
out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */
if (!out) return 0;
ptr=str+1;ptr2=out;
while (*ptr!='\"' && *ptr)
{
if (*ptr!='\\') *ptr2++=*ptr++;
else
{
ptr++;
switch (*ptr)
{
case 'b': *ptr2++='\b'; break;
case 'f': *ptr2++='\f'; break;
case 'n': *ptr2++='\n'; break;
case 'r': *ptr2++='\r'; break;
case 't': *ptr2++='\t'; break;
case 'u': /* transcode utf16 to utf8. */
uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */
if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */
if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */
{
if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */
uc2=parse_hex4(ptr+3);ptr+=6;
if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */
uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF));
}
len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len;
switch (len) {
case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6;
case 1: *--ptr2 =(uc | firstByteMark[len]);
}
ptr2+=len;
break;
default: *ptr2++=*ptr; break;
}
ptr++;
}
}
*ptr2=0;
if (*ptr=='\"') ptr++;
item->valuestring=out;
item->type=cJSON_String;
return ptr;
}
/* Render the cstring provided to an escaped version that can be printed. */
static char *print_string_ptr(const char *str,printbuffer *p)
{
const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token;
for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0;
if (!flag)
{
len=ptr-str;
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;*ptr2++='\"';
strcpy(ptr2,str);
ptr2[len]='\"';
ptr2[len+1]=0;
return out;
}
if (!str)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (!out) return 0;
strcpy(out,"\"\"");
return out;
}
ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;}
if (p) out=ensure(p,len+3);
else out=(char*)cJSON_malloc(len+3);
if (!out) return 0;
ptr2=out;ptr=str;
*ptr2++='\"';
while (*ptr)
{
if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++;
else
{
*ptr2++='\\';
switch (token=*ptr++)
{
case '\\': *ptr2++='\\'; break;
case '\"': *ptr2++='\"'; break;
case '\b': *ptr2++='b'; break;
case '\f': *ptr2++='f'; break;
case '\n': *ptr2++='n'; break;
case '\r': *ptr2++='r'; break;
case '\t': *ptr2++='t'; break;
default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */
}
}
}
*ptr2++='\"';*ptr2++=0;
return out;
}
/* Invote print_string_ptr (which is useful) on an item. */
static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);}
/* Predeclare these prototypes. */
static const char *parse_value(cJSON *item,const char *value);
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_array(cJSON *item,const char *value);
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p);
static const char *parse_object(cJSON *item,const char *value);
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p);
/* Utility to jump whitespace and cr/lf */
static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;}
/* Parse an object - create a new root, and populate. */
cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated)
{
const char *end=0;
cJSON *c=cJSON_New_Item();
ep=0;
if (!c) return 0; /* memory fail */
end=parse_value(c,skip(value));
if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */
/* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */
if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}}
if (return_parse_end) *return_parse_end=end;
return c;
}
/* Default options for cJSON_Parse */
cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);}
/* Render a cJSON item/entity/structure to text. */
char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);}
char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);}
char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt)
{
printbuffer p;
p.buffer=(char*)cJSON_malloc(prebuffer);
p.length=prebuffer;
p.offset=0;
return print_value(item,0,fmt,&p);
return p.buffer;
}
/* Parser core - when encountering text, process appropriately. */
static const char *parse_value(cJSON *item,const char *value)
{
if (!value) return 0; /* Fail on null. */
if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; }
if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; }
if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; }
if (*value=='\"') { return parse_string(item,value); }
if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); }
if (*value=='[') { return parse_array(item,value); }
if (*value=='{') { return parse_object(item,value); }
ep=value;return 0; /* failure. */
}
/* Render a value to text. */
static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p)
{
char *out=0;
if (!item) return 0;
if (p)
{
switch ((item->type)&255)
{
case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;}
case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;}
case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;}
case cJSON_Number: out=print_number(item,p);break;
case cJSON_String: out=print_string(item,p);break;
case cJSON_Array: out=print_array(item,depth,fmt,p);break;
case cJSON_Object: out=print_object(item,depth,fmt,p);break;
}
}
else
{
switch ((item->type)&255)
{
case cJSON_NULL: out=cJSON_strdup("null"); break;
case cJSON_False: out=cJSON_strdup("false");break;
case cJSON_True: out=cJSON_strdup("true"); break;
case cJSON_Number: out=print_number(item,0);break;
case cJSON_String: out=print_string(item,0);break;
case cJSON_Array: out=print_array(item,depth,fmt,0);break;
case cJSON_Object: out=print_object(item,depth,fmt,0);break;
}
}
return out;
}
/* Build an array from input text. */
static const char *parse_array(cJSON *item,const char *value)
{
cJSON *child;
if (*value!='[') {ep=value;return 0;} /* not an array! */
item->type=cJSON_Array;
value=skip(value+1);
if (*value==']') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0; /* memory fail */
value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_value(child,skip(value+1)));
if (!value) return 0; /* memory fail */
}
if (*value==']') return value+1; /* end of array */
ep=value;return 0; /* malformed. */
}
/* Render an array to text */
static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries;
char *out=0,*ptr,*ret;int len=5;
cJSON *child=item->child;
int numentries=0,i=0,fail=0;
size_t tmplen=0;
/* How many entries in the array? */
while (child) numentries++,child=child->next;
/* Explicitly handle numentries==0 */
if (!numentries)
{
if (p) out=ensure(p,3);
else out=(char*)cJSON_malloc(3);
if (out) strcpy(out,"[]");
return out;
}
if (p)
{
/* Compose the output array. */
i=p->offset;
ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++;
child=item->child;
while (child && !fail)
{
print_value(child,depth+1,fmt,p);
p->offset=update(p);
if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;}
child=child->next;
}
ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate an array to hold the values for each */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
memset(entries,0,numentries*sizeof(char*));
/* Retrieve all the results: */
child=item->child;
while (child && !fail)
{
ret=print_value(child,depth+1,fmt,0);
entries[i++]=ret;
if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1;
child=child->next;
}
/* If we didn't fail, try to malloc the output string */
if (!fail) out=(char*)cJSON_malloc(len);
/* If that fails, we fail. */
if (!out) fail=1;
/* Handle failure. */
if (fail)
{
for (i=0;i<numentries;i++) if (entries[i]) cJSON_free(entries[i]);
cJSON_free(entries);
return 0;
}
/* Compose the output array. */
*out='[';
ptr=out+1;*ptr=0;
for (i=0;i<numentries;i++)
{
tmplen=strlen(entries[i]);memcpy(ptr,entries[i],tmplen);ptr+=tmplen;
if (i!=numentries-1) {*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;}
cJSON_free(entries[i]);
}
cJSON_free(entries);
*ptr++=']';*ptr++=0;
}
return out;
}
/* Build an object from the text. */
static const char *parse_object(cJSON *item,const char *value)
{
cJSON *child;
if (*value!='{') {ep=value;return 0;} /* not an object! */
item->type=cJSON_Object;
value=skip(value+1);
if (*value=='}') return value+1; /* empty array. */
item->child=child=cJSON_New_Item();
if (!item->child) return 0;
value=skip(parse_string(child,skip(value)));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */
if (!value) return 0;
while (*value==',')
{
cJSON *new_item;
if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */
child->next=new_item;new_item->prev=child;child=new_item;
value=skip(parse_string(child,skip(value+1)));
if (!value) return 0;
child->string=child->valuestring;child->valuestring=0;
if (*value!=':') {ep=value;return 0;} /* fail! */
value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */
if (!value) return 0;
}
if (*value=='}') return value+1; /* end of array */
ep=value;return 0; /* malformed. */
}
/* Render an object to text. */
static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p)
{
char **entries=0,**names=0;
char *out=0,*ptr,*ret,*str;int len=7,i=0,j;
cJSON *child=item->child;
int numentries=0,fail=0;
size_t tmplen=0;
/* Count the number of entries. */
while (child) numentries++,child=child->next;
/* Explicitly handle empty object case */
if (!numentries)
{
if (p) out=ensure(p,fmt?depth+4:3);
else out=(char*)cJSON_malloc(fmt?depth+4:3);
if (!out) return 0;
ptr=out;*ptr++='{';
if (fmt) {*ptr++='\n';for (i=0;i<depth-1;i++) *ptr++='\t';}
*ptr++='}';*ptr++=0;
return out;
}
if (p)
{
/* Compose the output: */
i=p->offset;
len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0;
*ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len;
child=item->child;depth++;
while (child)
{
if (fmt)
{
ptr=ensure(p,depth); if (!ptr) return 0;
for (j=0;j<depth;j++) *ptr++='\t';
p->offset+=depth;
}
print_string_ptr(child->string,p);
p->offset=update(p);
len=fmt?2:1;
ptr=ensure(p,len); if (!ptr) return 0;
*ptr++=':';if (fmt) *ptr++='\t';
p->offset+=len;
print_value(child,depth,fmt,p);
p->offset=update(p);
len=(fmt?1:0)+(child->next?1:0);
ptr=ensure(p,len+1); if (!ptr) return 0;
if (child->next) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
p->offset+=len;
child=child->next;
}
ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0;
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr=0;
out=(p->buffer)+i;
}
else
{
/* Allocate space for the names and the objects */
entries=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!entries) return 0;
names=(char**)cJSON_malloc(numentries*sizeof(char*));
if (!names) {cJSON_free(entries);return 0;}
memset(entries,0,sizeof(char*)*numentries);
memset(names,0,sizeof(char*)*numentries);
/* Collect all the results into our arrays: */
child=item->child;depth++;if (fmt) len+=depth;
while (child && !fail)
{
names[i]=str=print_string_ptr(child->string,0);
entries[i++]=ret=print_value(child,depth,fmt,0);
if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1;
child=child->next;
}
/* Try to allocate the output string */
if (!fail) out=(char*)cJSON_malloc(len);
if (!out) fail=1;
/* Handle failure */
if (fail)
{
for (i=0;i<numentries;i++) {if (names[i]) cJSON_free(names[i]);if (entries[i]) cJSON_free(entries[i]);}
cJSON_free(names);cJSON_free(entries);
return 0;
}
/* Compose the output: */
*out='{';ptr=out+1;if (fmt)*ptr++='\n';*ptr=0;
for (i=0;i<numentries;i++)
{
if (fmt) for (j=0;j<depth;j++) *ptr++='\t';
tmplen=strlen(names[i]);memcpy(ptr,names[i],tmplen);ptr+=tmplen;
*ptr++=':';if (fmt) *ptr++='\t';
strcpy(ptr,entries[i]);ptr+=strlen(entries[i]);
if (i!=numentries-1) *ptr++=',';
if (fmt) *ptr++='\n';*ptr=0;
cJSON_free(names[i]);cJSON_free(entries[i]);
}
cJSON_free(names);cJSON_free(entries);
if (fmt) for (i=0;i<depth-1;i++) *ptr++='\t';
*ptr++='}';*ptr++=0;
}
return out;
}
/* Get Array size/item / object item. */
int cJSON_GetArraySize(cJSON *array) {cJSON *c=array->child;int i=0;while(c)i++,c=c->next;return i;}
cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;}
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;}
int cJSON_HasObjectItem(cJSON *object,const char *string) {
cJSON *c=object->child;
while (c )
{
if(cJSON_strcasecmp(c->string,string)==0){
return 1;
}
c=c->next;
}
return 0;
}
/* Utility for array list handling. */
static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;}
/* Utility for handling references. */
static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;}
/* Add item to array/object. */
void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}}
void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);}
void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);}
void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));}
void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));}
cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0;
if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;}
void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));}
cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;}
void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));}
/* Replace array/object items with new ones. */
void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;}
newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;}
void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return;
newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem;
if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);}
void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}}
/* Create basic types: */
cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;}
cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;}
cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;}
cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;}
cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;}
cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;}
cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;}
cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;}
/* Create Arrays: */
cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateNumber(numbers[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && i<count;i++){n=cJSON_CreateString(strings[i]);if(!i)a->child=n;else suffix_object(p,n);p=n;}return a;}
/* Duplication */
cJSON *cJSON_Duplicate(cJSON *item,int recurse)
{
cJSON *newitem,*cptr,*nptr=0,*newchild;
/* Bail on bad ptr */
if (!item) return 0;
/* Create new item */
newitem=cJSON_New_Item();
if (!newitem) return 0;
/* Copy over all vars */
newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble;
if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}}
if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}}
/* If non-recursive, then we're done! */
if (!recurse) return newitem;
/* Walk the ->next chain for the child. */
cptr=item->child;
while (cptr)
{
newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */
if (!newchild) {cJSON_Delete(newitem);return 0;}
if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */
else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */
cptr=cptr->next;
}
return newitem;
}
void cJSON_Minify(char *json)
{
char *into=json;
while (*json)
{
if (*json==' ') json++;
else if (*json=='\t') json++; /* Whitespace characters. */
else if (*json=='\r') json++;
else if (*json=='\n') json++;
else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */
else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */
else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */
else *into++=*json++; /* All other characters. */
}
*into=0; /* and null-terminate. */
}

52
linux32/src/s2j.c Normal file
View File

@ -0,0 +1,52 @@
/*
* This file is part of the struct2json Library.
*
* Copyright (c) 2015, Armink, <armink.ztl@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* 'Software'), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Function: Initialize interface for this library.
* Created on: 2015-10-14
*/
#include <s2j.h>
#include <stdlib.h>
S2jHook s2jHook = {
.malloc_fn = malloc,
.free_fn = free,
};
/**
* struct2json library initialize
* @note It will initialize cJSON library hooks.
*/
void s2j_init(S2jHook *hook) {
/* initialize cJSON library */
cJSON_InitHooks((cJSON_Hooks *)hook);
/* initialize hooks */
if (hook) {
s2jHook.malloc_fn = (hook->malloc_fn) ? hook->malloc_fn : malloc;
s2jHook.free_fn = (hook->free_fn) ? hook->free_fn : free;
} else {
s2jHook.malloc_fn = malloc;
s2jHook.free_fn = free;
}
}

326
log/hexdump.c Normal file
View File

@ -0,0 +1,326 @@
#ifndef __KERNEL__
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <uthash/utstring.h>
#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

1314
log/log.c Normal file

File diff suppressed because it is too large Load Diff