cjson_wrapper operator[](size_t index) const { return cjson_wrapper(cJSON_GetArrayItem(json_, index)); }
static stat_query_section_t *StatQuery_GetArraySection( stat_query_section_t *parent, int idx ) { return (stat_query_section_t *)cJSON_GetArrayItem( (cJSON *)parent, idx ); }
static const char *StatQuery_GetArrayString( stat_query_section_t *parent, int idx ) { cJSON *object = cJSON_GetArrayItem( (cJSON *)parent, idx ); return StatQuery_JsonToString( object ); }
int32_t PLUGNAME(_process_json)(char *forwarder,char *sender,int32_t valid,struct plugin_info *plugin,uint64_t tag,char *retbuf,int32_t maxlen,char *origjsonstr,cJSON *origjson,int32_t initflag,char *tokenstr) { char endpoint[128],tagstr[512],*resultstr,*retstr = 0,*methodstr,*jsonstr,*destplugin,*submethod; cJSON *retjson,*json,*tokenobj; uint32_t nonce; struct applicant_info apply; retbuf[0] = 0; if ( tokenstr == 0 ) tokenstr = ""; if ( is_cJSON_Array(origjson) != 0 && cJSON_GetArraySize(origjson) == 2 ) json = cJSON_GetArrayItem(origjson,0), jsonstr = cJSON_Print(json), _stripwhite(jsonstr,' '); else json = origjson, jsonstr = origjsonstr; if ( Debuglevel > 2 ) printf("<<<<<<<<<<<< INSIDE relays PLUGIN! process %s [(%s).(%s)]\n",plugin->name,jsonstr,tokenstr); if ( initflag > 0 ) { // configure settings RELAYS.readyflag = 1; plugin->allowremote = 1; strcpy(retbuf,"{\"result\":\"initflag > 0\"}"); } else { if ( plugin_result(retbuf,json,tag) > 0 ) return((int32_t)strlen(retbuf)); resultstr = cJSON_str(cJSON_GetObjectItem(json,"result")); methodstr = cJSON_str(cJSON_GetObjectItem(json,"method")); destplugin = cJSON_str(cJSON_GetObjectItem(json,"destplugin")); submethod = cJSON_str(cJSON_GetObjectItem(json,"submethod")); if ( methodstr == 0 || methodstr[0] == 0 ) { printf("(%s) has not method\n",jsonstr); return(0); } //fprintf(stderr,"RELAYS methodstr.(%s) (%s)\n",methodstr,jsonstr); if ( resultstr != 0 && strcmp(resultstr,"registered") == 0 ) { plugin->registered = 1; strcpy(retbuf,"{\"result\":\"activated\"}"); } #ifdef INSIDE_MGW else if ( strcmp(methodstr,"msigaddr") == 0 ) { char *devMGW_command(char *jsonstr,cJSON *json); if ( SUPERNET.gatewayid >= 0 ) retstr = devMGW_command(jsonstr,json); } #endif else { strcpy(retbuf,"{\"result\":\"relay command under construction\"}"); if ( strcmp(methodstr,"list") == 0 ) retstr = relays_jsonstr(jsonstr,json); else if ( strcmp(methodstr,"telepathy") == 0 ) { sprintf(retbuf,"%s",jsonstr); } else if ( strcmp(methodstr,"busdata") == 0 ) { retstr = busdata_sync(&nonce,jsonstr,cJSON_str(cJSON_GetObjectItem(json,"broadcast")),0); // {"plugin":"relay","method":"busdata","destplugin":"relay","submethod":"join","broadcast":"join","endpoint":""} } else if ( strcmp(methodstr,"allservices") == 0 ) { if ( (retjson= serviceprovider_json()) != 0 ) { retstr = cJSON_Print(retjson), _stripwhite(retstr,' '); free_json(retjson); //printf("got.(%s)\n",retstr); } else printf("null serviceprovider_json()\n"); } else if ( strcmp(methodstr,"protocol") == 0 || strcmp(methodstr,"allprotocols") == 0 ) { if ( strcmp(methodstr,"protocol") == 0 && valid > 0 ) protocols_register(sender,jstr(json,"protocol"),jstr(json,"endpoint"),jint(json,"disconnect")); if ( (retjson= protocols_json(jstr(json,"protocol"))) != 0 ) { retstr = cJSON_Print(retjson), _stripwhite(retstr,' '); free_json(retjson); } else printf("null protocols_json()\n"); } else if ( strcmp(methodstr,"join") == 0 ) { if ( SUPERNET.noncing == 0 ) { copy_cJSON(tagstr,cJSON_GetObjectItem(json,"tag")); copy_cJSON(endpoint,cJSON_GetObjectItem(json,"endpoint")); SUPERNET.noncing = 1; if ( SUPERNET.iamrelay != 0 ) { portable_thread_create((void *)calc_nonces,clonestr(endpoint)); sprintf(retbuf,"{\"result\":\"noncing\",\"endpoint\":\"%s\"}",endpoint); } //fprintf(stderr,"join or nonce.(%s)\n",retbuf); } } else if ( strcmp(methodstr,"nonce") == 0 ) { char endpoint[512],sender[64],destpoint[512],relaypoint[512],globalpoint[512],noncestr[512]; memset(&apply,0,sizeof(apply)); copy_cJSON(destpoint,cJSON_GetObjectItem(json,"destpoint")); copy_cJSON(endpoint,cJSON_GetObjectItem(json,"lbendpoint")); copy_cJSON(relaypoint,cJSON_GetObjectItem(json,"relaypoint")); copy_cJSON(globalpoint,cJSON_GetObjectItem(json,"globalpoint")); copy_cJSON(sender,cJSON_GetObjectItem(json,"NXT")); if ( SUPERNET.noncing != 0 && strcmp(SUPERNET.lbendpoint,destpoint) == 0 ) { if ( endpoint[0] != 0 && tokenstr[0] != 0 && (tokenobj= cJSON_Parse(tokenstr)) != 0 ) { strcpy(apply.lbendpoint,endpoint); strcpy(apply.relayendpoint,relaypoint); strcpy(apply.globalendpoint,globalpoint); apply.senderbits = calc_nxt64bits(sender); copy_cJSON(noncestr,cJSON_GetObjectItem(tokenobj,"nonce")); if ( noncestr[0] != 0 ) apply.nonce = (uint32_t)calc_nxt64bits(noncestr); //printf("tokenobj.(%s) -> nonce.%u\n",tokenstr,apply.nonce); free_json(tokenobj); recv_nonces(&apply); } } } } } return(plugin_copyretstr(retbuf,maxlen,retstr)); }
void MM_ReadJails(const char *fileData) { cJSON * root = cJSON_Parse(fileData); int len = root ? cJSON_GetArraySize(root) : 0; for (int i = 0; i < len; i++) { cJSON *item = cJSON_GetArrayItem(root, i); if (!item) { G_LogPrintf(__FUNCTION__"(): item %i is NULL, skipping.\n", i); continue; } cJSON *origin = cJSON_GetObjectItem(item, "origin"); if (!origin) { G_LogPrintf(__FUNCTION__"(): item %i has NULL origin, skipping.\n", i); continue; } if (cJSON_GetArraySize(origin) != 3) { G_LogPrintf(__FUNCTION__"(): item %i has corrupted origin, skipping.\n", i); continue; } float origin_v[3] = { 0 }; qboolean _continue = qfalse; for (int j = 0; j < 3; j++) { cJSON *origin_m = cJSON_GetArrayItem(origin, j); if (origin_m->type == cJSON_Number) origin_v[j] = cJSON_GetArrayItem(origin, j)->valuedouble; else { G_LogPrintf(__FUNCTION__"(): item %i has corrupted origin axis, skipping.\n", i); _continue = qtrue; } } if (_continue) continue; cJSON *angles = cJSON_GetObjectItem(item, "angles"); if (!angles) { G_LogPrintf(__FUNCTION__"(): item %i has NULL angles, skipping.\n", i); continue; } if (cJSON_GetArraySize(angles) != 3) { G_LogPrintf(__FUNCTION__"(): item %i has corrupted angles, skipping.\n", i); continue; } float angles_v[3] = { 0 }; for (int j = 0; j < 3; j++) { cJSON *angles_m = cJSON_GetArrayItem(angles, j); if (angles_m->type == cJSON_Number) angles_v[j] = cJSON_GetArrayItem(angles, j)->valuedouble; else { G_LogPrintf(__FUNCTION__"(): item %i has corrupted angles axis, skipping.\n", i); _continue = qtrue; } } if (_continue) continue; jails_add(origin_v, angles_v); } cJSON_Delete(root); }
static int _load_config() { cJSON *config = NULL; cJSON *data = NULL; cJSON *elm = NULL; cJSON *startTime = NULL; cJSON *command = NULL; int cnt = 0; int index = 0; int hour,min,second; int ret = OK; if (NULL != task) { free(task); task = NULL; } config = _get_JSON_from_file(CONFIG_FILE_PATH); if (NULL == config) { LOG_ERR("get config errer"); ret = ERROR; goto leave; } /* attendtion free */ PRINTF("data = %s", cJSON_Print(config)); data = cJSON_GetObjectItem(config, "data"); cnt = cJSON_GetArraySize(data); task = (TASK_ENTRY *)malloc(sizeof(TASK_ENTRY)*cnt); if (NULL == task) { LOG_ERR("malloc error!"); ret = ERROR; goto leave; } for(index = 0; index < cnt; index++) { elm = cJSON_GetArrayItem(data, index); startTime = cJSON_GetObjectItem(elm, "startTime"); if( startTime != NULL && startTime->type == cJSON_String ) { sscanf(startTime->valuestring, "%d:%d:%d", &hour, &min, &second); task[index].startTime = hour * 60 * 60 + min * 60 + second; } command = cJSON_GetObjectItem(elm, "command"); if( command != NULL && command->type == cJSON_String ) { if(strlen(command->valuestring) < MAX_COMMAND_LENGTH) { strcpy(task[index].command, command->valuestring); } else { LOG_ERR("command %s size %d error!", command->valuestring, strlen(command->valuestring)); _log_to_file(ERROR_LOG_FILE_PATH, "command %s size %d error!", command->valuestring, strlen(command->valuestring)); } } } _quick_sort(0, cnt - 1, task); task_index = 0; task_MAX = cnt; #ifdef LOG_DEBUG for(index = 0; index < cnt; index++) { PRINTF("%02d:%02d:%02d %s", task[index].startTime/3600, (task[index].startTime % 3600)/60, task[index].startTime%60, task[index].command); } #endif leave: if(config) cJSON_Delete(config); return ret; }
int32_t PLUGNAME(_process_json)(char *forwarder,char *sender,int32_t valid,struct plugin_info *plugin,uint64_t tag,char *retbuf,int32_t maxlen,char *jsonstr,cJSON *json,int32_t initflag,char *tokenstr) { char *resultstr,*methodstr,zerobuf[1],*coinstr,*str = 0; cJSON *array,*item; int32_t i,n,j = 0; struct coin777 *coin; struct destbuf tmp; retbuf[0] = 0; if ( initflag > 0 ) { if ( json != 0 ) { COINS.argjson = cJSON_Duplicate(json,1); COINS.slicei = get_API_int(cJSON_GetObjectItem(json,"slice"),0); if ( (array= cJSON_GetObjectItem(json,"coins")) != 0 && (n= cJSON_GetArraySize(array)) > 0 ) { for (i=j=0; i<n; i++) { item = cJSON_GetArrayItem(array,i); coinstr = cJSON_str(cJSON_GetObjectItem(item,"name")); if ( coinstr != 0 && coinstr[0] != 0 && (coin= coin777_find(coinstr,0)) == 0 ) { printf("CALL coin777_create.(%s) (%s)\n",coinstr,cJSON_Print(item)); coin777_create(coinstr,item); } } } } else strcpy(retbuf,"{\"result\":\"no JSON for init\"}"); COINS.readyflag = 1; plugin->allowremote = 1; //plugin->sleepmillis = 1; } else { if ( plugin_result(retbuf,json,tag) > 0 ) return((int32_t)strlen(retbuf)); resultstr = cJSON_str(cJSON_GetObjectItem(json,"result")); methodstr = cJSON_str(cJSON_GetObjectItem(json,"method")); coinstr = cJSON_str(cJSON_GetObjectItem(json,"coin")); if ( methodstr == 0 || methodstr[0] == 0 ) { printf("(%s) has not method\n",jsonstr); return(0); } //printf("COINS.(%s) for (%s) (%s)\n",methodstr,coinstr!=0?coinstr:"",jsonstr); if ( resultstr != 0 && strcmp(resultstr,"registered") == 0 ) { plugin->registered = 1; strcpy(retbuf,"{\"result\":\"activated\"}"); } else { zerobuf[0] = 0; str = 0; //printf("INSIDE COINS.(%s) methods.%ld\n",jsonstr,sizeof(coins_methods)/sizeof(*coins_methods)); copy_cJSON(&tmp,cJSON_GetObjectItem(json,"NXT")), safecopy(sender,tmp.buf,32); if ( coinstr == 0 ) coinstr = zerobuf; else coin = coin777_find(coinstr,1); #ifdef INSIDE_MGW if ( strcmp(methodstr,"acctpubkeys") == 0 ) { if ( SUPERNET.gatewayid >= 0 ) { if ( coinstr[0] == 0 ) strcpy(retbuf,"{\"result\":\"need to specify coin\"}"); else if ( (coin= coin777_find(coinstr,1)) != 0 ) { int32_t MGW_publish_acctpubkeys(char *coinstr,char *str); char *get_msig_pubkeys(char *coinstr,char *serverport,char *userpass); if ( (str= get_msig_pubkeys(coin->name,coin->serverport,coin->userpass)) != 0 ) { MGW_publish_acctpubkeys(coin->name,str); strcpy(retbuf,"{\"result\":\"published and processed acctpubkeys\"}"); free(str), str= 0; } else sprintf(retbuf,"{\"error\":\"no get_msig_pubkeys result\",\"method\":\"%s\"}",methodstr); } else sprintf(retbuf,"{\"error\":\"no coin777\",\"method\":\"%s\"}",methodstr); } else sprintf(retbuf,"{\"error\":\"gateway only method\",\"method\":\"%s\"}",methodstr); } else if ( strcmp(methodstr,"gotmsigaddr") == 0 ) { if ( SUPERNET.gatewayid < 0 ) printf("GOTMSIG.(%s)\n",jsonstr); } else #endif sprintf(retbuf,"{\"error\":\"unsupported method\",\"method\":\"%s\"}",methodstr); } } //printf("<<<<<<<<<<<< INSIDE PLUGIN.(%s) initflag.%d process %s slice.%d\n",SUPERNET.myNXTaddr,initflag,plugin->name,COINS.slicei); return(plugin_copyretstr(retbuf,maxlen,str)); }
/* * This function provides a way of opening and parsing out *an include file named "Client.json" in each plugin *directory for the benefit of the webbrowser */ int getPluginWebIncludes (struct evbuffer* target, const char* pluginDirName) { if (!target || !pluginDirName) { doLog (ERROR, LOG_COMP, _("Invalid use of getPluginWebIncludes().")); return -1; } #ifndef WEB_PLUGIN_DIR doLog (ERROR, LOG_COMP, _("WEB_PLUGIN_DIR not provided at compile time.")); return -1; #endif char pluginIncludePath[256]; snprintf (pluginIncludePath, 256, "%s/%s/Client.json", WEB_PLUGIN_PATH, pluginDirName); FILE* includeFile = fopen (pluginIncludePath, "rb"); if (includeFile) { /* Get file size first */ fseek (includeFile, 0L, SEEK_END); size_t sz = ftell (includeFile); fseek (includeFile, 0L, SEEK_SET); char* includeFileContent = malloc (sizeof( char ) * sz); if (!includeFileContent) { doLog (ERROR, LOG_COMP, _("Unable to allocate memory to accommodate include file for parsing.")); fclose (includeFile); return -1; } fread (includeFileContent, sizeof( char ) * sz, 1, includeFile); cJSON* includeFileParsed = cJSON_Parse (includeFileContent); if (!includeFileParsed) { doLog (ERROR, LOG_COMP, _("Unable to parse JSON from include file.")); fclose (includeFile); free (includeFileContent); return -1; } /* Done with string after parsing */ free (includeFileContent); /* Make comment in HTML */ evbuffer_add_printf (target, "\t\t<!-- Includes for %.50s -->\n", pluginDirName); /* PARSE! */ int i; cJSON* jsArr = cJSON_GetObjectItem (includeFileParsed, "js"); if (jsArr && jsArr->type == cJSON_Array) for (i = 0; i < cJSON_GetArraySize (jsArr); ++i) { cJSON* jsItem = cJSON_GetArrayItem (jsArr, i); if (jsItem && jsItem->type == cJSON_String) evbuffer_add_printf ( target, "\t\t<script type=\"text/javascript\" src=\"../plugins/%.50s/%.50s\"></script>\n", pluginDirName, jsItem->valuestring); } cJSON* cssArr = cJSON_GetObjectItem (includeFileParsed, "css"); if (cssArr && cssArr->type == cJSON_Array) for (i = 0; i < cJSON_GetArraySize (cssArr); ++i) { cJSON* cssItem = cJSON_GetArrayItem (cssArr, i); if (cssItem && cssItem->type == cJSON_String) evbuffer_add_printf ( target, "\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"../plugins/%.50s/%.50s\" />\n", pluginDirName, cssItem->valuestring); } /* Line break */ evbuffer_add_printf (target, "\n"); /* Free JSON */ cJSON_Delete (includeFileParsed); } else { doLog (WARNING, LOG_COMP, _("Unable to open %s. No includes added."), pluginIncludePath); return -1; } return fclose (includeFile); }
void LeaderboardStorage::Tick(double TimePassed) { if( m_pWebRequestObject ) m_pWebRequestObject->Tick(); m_TimeSinceLastRequestSent += (float)TimePassed; if( m_TimeSinceLastRequestSent > m_MaxTimeToWaitToWebResponse ) { m_pWebRequestObject->Reset(); } if( m_pWebRequestObject->DidSomethingGoWrong() ) return; if( m_RequestedBoardID >= 0 && m_pWebRequestObject->IsBusy() == false && m_pWebRequestObject->GetResult() == 0 ) GetScoreBlock(); // invalidate all blocks older than 3 minutes. if( true ) { for( int i=0; i<NumLeaderboardStorageBlocksCached; i++ ) { if( m_Blocks[i].m_InUse ) { double age = MyTime_GetSystemTime() - m_Blocks[i].m_TimeRetrieved; if( age > 3*60 ) m_Blocks[i].m_InUse = false; } } } // if we received anything from the web, parse it and store it. if( m_pWebRequestObject->IsBusy() == false ) { char* result = m_pWebRequestObject->GetResult(); if( result ) { cJSON* root = cJSON_Parse( result ); if( root ) { cJSON* obj; obj = cJSON_GetObjectItem( root, "NumEntries" ); if( obj ) { g_pGame->m_pLeaderboardStorage->m_TotalPlayers[m_RequestedBoardID] = obj->valueint; } // read in "UserOffset", only returned if we are looking for a user. obj = cJSON_GetObjectItem( root, "UserOffset" ); if( obj ) { m_UserIndices[m_RequestedBoardID] = obj->valueint - 1; } int blockoffset = m_RequestedOffset; obj = cJSON_GetObjectItem( root, "BlockOffset" ); if( obj ) { blockoffset = obj->valueint; } int boardid = m_RequestedBoardID; // find a block of names and scores to store this info into. int blocktouse = FindDuplicateBlockOrReturnNew( blockoffset, boardid ); m_Blocks[blocktouse].m_InUse = true; m_Blocks[blocktouse].m_Offset = blockoffset; m_Blocks[blocktouse].m_BoardID = boardid; m_Blocks[blocktouse].m_TimeRetrieved = MyTime_GetSystemTime(); m_Blocks[blocktouse].m_NumEntriesInBlock = 0; cJSON* NameArray = cJSON_GetObjectItem( root, "UserNames" ); if( NameArray ) { m_Blocks[blocktouse].m_NumEntriesInBlock = cJSON_GetArraySize( NameArray ); for( int i=0; i<m_Blocks[blocktouse].m_NumEntriesInBlock; i++ ) { LeaderboardBlockEntry* pPlayer = &m_Blocks[blocktouse].m_Entries[i]; cJSON* temp; temp = cJSON_GetArrayItem( NameArray, i ); if( temp ) strcpy_s( pPlayer->m_Username, 15+1, temp->valuestring ); // if we find our own name, then store it's index. if( _stricmp( temp->valuestring, g_pGame->m_pProfileManager->m_CurrentProfile->m_Username ) == 0 ) m_UserIndices[m_RequestedBoardID] = blockoffset + i; } // if we got names, we should get Scores. cJSON* ScoreArray = cJSON_GetObjectItem( root, "Scores" ); if( ScoreArray ) { int numitems = cJSON_GetArraySize( ScoreArray ); for( int i=0; i<numitems; i++ ) { LeaderboardBlockEntry* pPlayer = &m_Blocks[blocktouse].m_Entries[i]; cJSON* temp; temp = cJSON_GetArrayItem( ScoreArray, i ); if( temp ) pPlayer->m_Score = temp->valueint; } } } cJSON_Delete( root ); } m_RequestedOffset = -1; m_RequestedBoardID = -1; m_pWebRequestObject->ClearResult(); } } }
PCSFileList *BaiduPCS_ListRemoteDir(BaiduPCS *api, const char *path) { //{{{ PCSFileList *list = NULL; PCSFile *file = NULL; HttpClient *client = api->client; char *url_buffer = api->util_buffer0; const char *token = api->token; const char *error = NULL; const char *response = NULL; char *path_encode = NULL; cJSON *json = NULL; cJSON *array = NULL; cJSON *item = NULL; int i = 0; int length = 0; BaiduPCS_ResetError(api); list = PCSFileList_New(); path_encode = curl_easy_escape(client->curl, path, 0); sprintf(url_buffer, "https://pcs.baidu.com/rest/2.0/pcs/file?" "access_token=%s" "&method=list" "&path=%s", token, path_encode); curl_free(path_encode); #ifdef DEBUG fprintf(stderr, "request %s\n", url_buffer); #endif HttpClient_Init(client); HttpClient_Get(client, url_buffer); MAKE_JSON(); item = cJSON_GetObjectItem(json, "list"); if (item == NULL || item->type != cJSON_Array) { BaiduPCS_ThrowError(api, "can't find json.list"); goto free; } array = item; length = cJSON_GetArraySize(array); for (i = 0; i < length; i ++) { item = cJSON_GetArrayItem(array, i); if (item == NULL || item->type != cJSON_Object) { BaiduPCS_ThrowError(api, "json.list.item is not object"); goto free; } file = PCSFile_New(); PCSFileList_Prepend(list, file); _BaiduPCS_Json2File(api, file, item); if (BaiduPCS_GetError(api) != NULL) { } } free: if (json != NULL) { cJSON_Delete(json); } return list; }
void App42UserResponse::init() { if(_result != 200) { Util::app42Trace("App42User failed result is %d", _result); buildErrorMessage(); return; } // parse the body cJSON *ptrBody = cJSON_Parse(_body.c_str()); cJSON* ptrApp42 = Util::getJSONChild("app42", ptrBody); cJSON* ptrResponse = Util::getJSONChild("response", ptrApp42); cJSON* ptrUsers = Util::getJSONChild("users", ptrResponse); if (ptrUsers) { cJSON* ptrUser = Util::getJSONChild("user", ptrUsers); if (ptrUser) { cJSON* child = ptrUser; if(child->type == cJSON_Array) { child = child->child; } while(child != NULL && child->type == cJSON_Object) { App42User app42User; app42User.userName = Util::getJSONString("userName", child); app42User.email = Util::getJSONString("email", child); app42User.isAccountLocked = Util::getJSONInt("accountLocked", child); app42User.sessionId = Util::getJSONInt("sessionId", child); cJSON* ptrUserProfile = Util::getJSONChild("profile", child); if (ptrUserProfile) { app42User.profile = buildUserProfile(ptrUserProfile); } cJSON* ptrUserRoles = Util::getJSONChild("role", child); if (ptrUserRoles) { cJSON* childRole = ptrUserRoles; if (childRole->type == cJSON_Array) { int size = cJSON_GetArraySize(childRole); for (int i=0; i<size; i++) { cJSON *item = cJSON_GetArrayItem(childRole, i); app42User.roleList.push_back(item->valuestring); } } } users.push_back(app42User); child = child->next; } } } else { setTotalRecords(); } cJSON_Delete(ptrBody); }
PCSFile *BaiduPCS_NewRemoteFile(BaiduPCS *api, const char *path) { //{{{ PCSFile *file = NULL; HttpClient *client = api->client; char *url_buffer = api->util_buffer0; const char *token = api->token; const char *error = NULL; const char *response = NULL; char *path_encode = NULL; cJSON *json = NULL; cJSON *array = NULL; cJSON *item = NULL; BaiduPCS_ResetError(api); file = PCSFile_New(); path_encode = curl_easy_escape(client->curl, path, 0); sprintf(url_buffer, "https://pcs.baidu.com/rest/2.0/pcs/file?" "access_token=%s" "&method=meta" "&path=%s", token, path_encode); curl_free(path_encode); path_encode = NULL; #ifdef DEBUG fprintf(stderr, "request %s\n", url_buffer); #endif HttpClient_Init(client); HttpClient_Get(client, url_buffer); MAKE_JSON(); item = cJSON_GetObjectItem(json, "list"); if (item == NULL || item->type != cJSON_Array) { BaiduPCS_ThrowError(api, "can't find json.list"); goto free; } array = item; if (cJSON_GetArraySize(array) == 0) { BaiduPCS_ThrowError(api, "json.list is blank"); goto free; } item = cJSON_GetArrayItem(array, 0); if (item == NULL || item->type != cJSON_Object) { BaiduPCS_ThrowError(api, "json.list.item is not object"); goto free; } _BaiduPCS_Json2File(api, file, item); free: if (json != NULL) { cJSON_Delete(json); } if (api->error[0] != '\0') { if (file != NULL) { PCSFile_Free(file); } return NULL; } return file; }
// i ==>index cJSON *JSONNode::getArrayItem(cJSON *head, int index) { if(index >= getArraySize(head)) return NULL; return cJSON_GetArrayItem(head, index); }
OicSecPstat_t * JSONToPstatBin(const char * jsonStr, const bool isIncResName) { if(NULL == jsonStr) { return NULL; } OCStackResult ret = OC_STACK_ERROR; OicSecPstat_t *pstat = NULL; cJSON *jsonPstat = NULL; cJSON *jsonObj = NULL; unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {}; uint32_t outLen = 0; B64Result b64Ret = B64_OK; cJSON *jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, INFO); if(isIncResName) { jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME); } else { jsonPstat = jsonRoot; } VERIFY_NON_NULL(TAG, jsonPstat, INFO); pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t)); VERIFY_NON_NULL(TAG, pstat, INFO); jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR); pstat->isOp = jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pstat->deviceID.id)), ERROR); memcpy(pstat->deviceID.id, base64Buff, outLen); jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); pstat->commitHash = jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); pstat->cm = (OicSecDpm_t)jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); pstat->om = (OicSecDpom_t)jsonObj->valueint; jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME); VERIFY_NON_NULL(TAG, jsonObj, ERROR); if (cJSON_Array == jsonObj->type) { pstat->smLen = cJSON_GetArraySize(jsonObj); size_t idxx = 0; VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR); pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t)); VERIFY_NON_NULL(TAG, pstat->sm, ERROR); do { cJSON *jsonSm = cJSON_GetArrayItem(jsonObj, idxx); VERIFY_NON_NULL(TAG, jsonSm, ERROR); pstat->sm[idxx] = (OicSecDpom_t)jsonSm->valueint; }while ( ++idxx < pstat->smLen); } ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { OC_LOG (ERROR, TAG, "JSONToPstatBin failed"); DeletePstatBinData(pstat); pstat = NULL; } return pstat; }
double jdoublei(cJSON *json,int32_t i) { if ( json != 0 ) return(get_API_float(cJSON_GetArrayItem(json,i))); else return(0.); }
void _setConfigurations(cJSON *root, s_config *config, char *http_packet) { cJSON *valueSetObj= cJSON_CreateObject(); cJSON *attribute; cJSON *key; cJSON *item; int array_size; int i; char cmd[MAX_BUF]; char result[MAX_BUF]; char ErrMesg[B_5_BUF]; cJSON *transaction_id = cJSON_GetObjectItem(root, "transaction_id"); char *conf_version; char *radio_index; char *profile_index; char *status; int flag =0; if(!transaction_id) { debug(LOG_ERR, "Can not find transaction_id parameter: %s", cJSON_GetErrorPtr()); create_http_json(valueSetObj, NULL, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{transaction_id}", config->sn, http_packet); return; } cJSON *valueSet = cJSON_GetObjectItem(root, "valueSet"); if(!valueSet) { debug(LOG_ERR, "Get valueSet faild[%s]", cJSON_GetErrorPtr()); create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{valueSet}", config->sn, http_packet); return; } /* if((key = cJSON_GetObjectItem(valueSet, "conf_version")) == NULL || (conf_version = key->valuestring) == NULL) { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{conf_version}", config->sn, http_packet); return; } */ ErrMesg[0]=0; //setDeviceInfo// { if((attribute = cJSON_GetObjectItem(valueSet, "setDeviceInfo")) != NULL) { if((key = cJSON_GetObjectItem(attribute, "apname")) != NULL && key->valuestring != NULL) { /*snprintf(cmd, MAX_BUF, "config apname %s\n", key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_apname(key->valuestring, result, sizeof(result)/sizeof(result[0])); } } } //setRadioInfo// { if((attribute = cJSON_GetObjectItem(valueSet, "setRadioInfo")) != NULL) { array_size = cJSON_GetArraySize(attribute); debug(LOG_DEBUG, "Array size of paras is %d",array_size); for(i=0; i< array_size; i++) { item = cJSON_GetArrayItem(attribute, i); //debug(LOG_DEBUG, "%s\n",item->valuestring); if((key = cJSON_GetObjectItem(item, "radio_index")) == NULL || (radio_index = radio_keywords[parse_radio_keywords(key->valuestring)].value) == NULL) { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{radio_index}", config->sn, http_packet); return; } /* if((key = cJSON_GetObjectItem(item, "radio")) != NULL && key->valuestring != NULL) { snprintf(cmd, MAX_BUF, "config interface wlan %s radio %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); //debug(LOG_INFO, "result is %d", strlen(result)); } */ if((key = cJSON_GetObjectItem(item, "mode")) != NULL && key->valuestring != NULL) { /*snprintf(cmd, MAX_BUF, "config interface wlan %s mode %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_mode(atoi(radio_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "power")) != NULL && key->valuestring != NULL) { /* snprintf(cmd, MAX_BUF, "config interface wlan %s power %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_power(atoi(radio_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "channel")) != NULL && key->valuestring != NULL) { /* snprintf(cmd, MAX_BUF, "config interface wlan %s channel %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_channel(atoi(radio_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "channelwidth")) != NULL && key->valuestring != NULL) { /* snprintf(cmd, MAX_BUF, "config interface wlan %s channelwidth %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_channelwidth(atoi(radio_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "max-wireless-clients")) != NULL && key->valuestring != NULL) { /* snprintf(cmd, MAX_BUF, "config interface wlan %s max-wireless-clients %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_max_assoc(atoi(radio_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "client-isolation")) != NULL && key->valuestring != NULL) { /* snprintf(cmd, MAX_BUF, "config interface wlan %s client-isolation %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); */ set_ap_isolate(atoi(radio_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } /* if((key = cJSON_GetObjectItem(item, "rate")) != NULL && key->valuestring != NULL) { snprintf(cmd, MAX_BUF, "config interface wlan %s rate %s\n", cJSON_GetObjectItem(item, "radio_index")->valuestring, key->valuestring); if(set_config(cmd, result)) strcpy(ErrMesg, result); } */ } } } //setSSIDInfo// { if((attribute = cJSON_GetObjectItem(valueSet, "setSSIDInfo")) != NULL) { array_size = cJSON_GetArraySize(attribute); debug(LOG_DEBUG, "Array size of paras is %d",array_size); for(i=0; i< array_size; i++) { item = cJSON_GetArrayItem(attribute, i); if((key = cJSON_GetObjectItem(item, "radio_index")) == NULL || (radio_index = radio_keywords[parse_radio_keywords(key->valuestring)].value) == NULL) { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{radio_index}", config->sn, http_packet); return; } if((key = cJSON_GetObjectItem(item, "profile_index")) == NULL || (profile_index = key->valuestring) == NULL) { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{profile_index}", config->sn, http_packet); return; } if((key = cJSON_GetObjectItem(item, "status")) == NULL || (status = key->valuestring) == NULL) { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "3", "Missing parameter:{status}", config->sn, http_packet); return; } if(atoi(profile_index)>0) { char vifs[128]; char viname[32]; sprintf(viname, "wl%d.%d", atoi(radio_index), atoi(profile_index)); read_vifs(atoi(radio_index), vifs, sizeof(vifs)/sizeof(vifs[0])); if(strstr(vifs, viname) && atoi(status)==0) { del_virtual_interface(atoi(radio_index), atoi(profile_index)); } else if(!strstr(vifs, viname) && atoi(status)==1) { add_virtual_interface(atoi(radio_index), atoi(profile_index)); } else if((!strstr(vifs, viname) && atoi(status)==0) || atoi(profile_index)>3) { continue; } } if((key = cJSON_GetObjectItem(item, "hide-network-name")) != NULL && key->valuestring != NULL) { set_status(atoi(radio_index), atoi(profile_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "ssid")) != NULL && key->valuestring != NULL) { set_ssid(atoi(radio_index), atoi(profile_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "authentication")) != NULL && key->valuestring != NULL) { set_security_mode(atoi(radio_index), atoi(profile_index), authentication_keywords[parse_authentication_keywords(key->valuestring)].value, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "encryption")) != NULL && key->valuestring != NULL) { set_crypto(atoi(radio_index), atoi(profile_index), encryption_keywords[parse_encryption_keywords(key->valuestring)].value, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } if((key = cJSON_GetObjectItem(item, "presharedkey")) != NULL && key->valuestring != NULL) { set_wpa_psk(atoi(radio_index), atoi(profile_index), key->valuestring, result, sizeof(result)/sizeof(result[0])); strcpy(ErrMesg, result); } flag =1; } } } { //apply_setting(); /* int result; pthread_t tid_init_service = 0; config->upgrade_lock = 1; debug(LOG_INFO, "create a new thread (thread_init_service)"); result = pthread_create(&tid_init_service, NULL, (void *)thread_init_service, NULL); if (result != 0) { debug(LOG_ERR, "FATAL: Failed to create a new thread (init_service) - exiting"); exit(1); }*/ system("nvram commit"); } if(strlen(ErrMesg)) { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "failed", "1000", ErrMesg, config->sn, http_packet); } else { create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, SETCONFIGURATIONS, "success", "0", NULL, config->sn, http_packet); } if(flag) { safe_encrypt_http_send(config->httpfd, http_packet, strlen(http_packet), 0); shutdown(config->httpfd, SHUT_RDWR); system("reboot"); } }
cJSON *jitem(cJSON *array,int32_t i) { if ( array != 0 && is_cJSON_Array(array) != 0 && cJSON_GetArraySize(array) > i ) return(cJSON_GetArrayItem(array,i)); return(0); }
void _getMonitor(cJSON *root, s_config *config, char *http_packet) { char tmp_value[32]; int flag = 0; cJSON *valueSetObj= cJSON_CreateObject(); cJSON *package; cJSON *list; cJSON *transaction_id = cJSON_GetObjectItem(root, "transaction_id"); if(!transaction_id) { debug(LOG_ERR, "Can not find transaction_id parameter: %s", cJSON_GetErrorPtr()); create_http_json(valueSetObj, 0, RESPONSE, GETMONITOR, "failed", "3", "Missing parameter:{transaction_id}", config->sn, http_packet); return; } cJSON *valueSet = cJSON_GetObjectItem(root, "valueSet"); if(!valueSet) { debug(LOG_ERR, "Can not find valueset parameter: %s", cJSON_GetErrorPtr()); create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, GETMONITOR, "failed", "3", "Missing parameter:{valueSet}", config->sn, http_packet); return; } cJSON *monitors = cJSON_GetObjectItem(valueSet, "monitors"); if(!monitors) { debug(LOG_ERR, "Can not find monitor parameter: %s", cJSON_GetErrorPtr()); create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, GETMONITOR, "failed", "3", "Missing parameter:{monitors}", config->sn, http_packet); return; } int array_size = cJSON_GetArraySize(monitors); debug(LOG_DEBUG, "Array size of monitor is %d",array_size); int i = 0; cJSON *item; for(i=0; i< array_size; i++) { item = cJSON_GetArrayItem(monitors, i); debug(LOG_DEBUG, "%s\n",item->valuestring); if(strcmp(item->valuestring , "wireless_traffic") == 0) { flag = 1; int wifi_index = 0; char interface_name[INTERFACELEN]; char ssid[SSIDLEN]; char assoc_num[4]; cJSON_AddItemToObject(valueSetObj, "wireless_traffic", list = cJSON_CreateArray()); while(read_ssid(wifi_index++, ssid, sizeof(ssid)/sizeof(ssid[0]))) { cJSON_AddItemToArray(list, package = cJSON_CreateObject()); sprintf(tmp_value, "%d", wifi_index-1); cJSON_AddStringToObject(package,"radio_index",tmp_value); snprintf(interface_name, INTERFACELEN, "eth%d", wifi_index); read_counter(tmp_value, interface_name, "Rxbytes", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Rxbytes", tmp_value); read_counter(tmp_value, interface_name, "Txbytes", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Txbytes", tmp_value); read_counter(tmp_value, interface_name, "Rxpkt", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Rxpkt", tmp_value); read_counter(tmp_value, interface_name, "Txpkt", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Txpkt", tmp_value); read_assoc_client_count(interface_name, assoc_num, sizeof(assoc_num)/sizeof(assoc_num[0])); cJSON_AddStringToObject(package,"NumberOfAssociatedClients", assoc_num); } } else if(strcmp(item->valuestring , "wired_traffic") == 0) { flag = 1; cJSON_AddItemToObject(valueSetObj, "wired_traffic", package = cJSON_CreateObject()); read_counter(tmp_value, "vlan2", "Rxbytes", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Rxbytes", tmp_value); read_counter(tmp_value, "vlan2", "Txbytes", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Txbytes", tmp_value); read_counter(tmp_value, "vlan2", "Rxpkt", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Rxpkt", tmp_value); read_counter(tmp_value, "vlan2", "Txpkt", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"Txpkt", tmp_value); /* read_counter(tmp_value, "vlan2", "rx_errors", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"rx_errors", tmp_value); read_counter(tmp_value, "vlan2", "tx_errors", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"tx_errors", tmp_value); read_counter(tmp_value, "vlan2", "rx_discards", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"rx_discards", tmp_value); read_counter(tmp_value, "vlan2", "tx_discards", sizeof(tmp_value)/sizeof(tmp_value[0])); cJSON_AddStringToObject(package,"tx_discards", tmp_value); */ } } flag?create_http_json(valueSetObj, transaction_id->valuestring, RESPONSE, GETMONITOR, "success", "0", NULL, NULL, http_packet):create_http_json(valueSetObj, atoi(transaction_id->valuestring), RESPONSE, GETMONITOR, "failed", "4", "Unsupported value", config->sn, http_packet); }
void TileSet::Init(cJSON* tileset) { _defaultTU=new TileUnit; bool b[4]={false,false,false,false};//non-blocking border _defaultTU->Init(b,false,false,false); m_firstGid=cJSON_GetObjectItem(tileset,"firstgid")->valueint; _filename=cJSON_GetObjectItem(tileset,"image")->valuestring; _imageHeight=cJSON_GetObjectItem(tileset,"imageheight")->valueint; _imageWidth=cJSON_GetObjectItem(tileset,"imagewidth")->valueint; _name=cJSON_GetObjectItem(tileset,"name")->valuestring; _tileheight=cJSON_GetObjectItem(tileset,"tileheight")->valueint; _tilewidth=cJSON_GetObjectItem(tileset,"tilewidth")->valueint; _image=Iw2DCreateImageResource(_name); _tilesPerRow=_imageWidth/_tilewidth; _tileSize= CIwSVec2(_tilewidth, _tileheight); cJSON * properties=cJSON_GetObjectItem(tileset,"tileproperties"); if(properties!=NULL) { int propSize=0; if(properties->child) propSize=cJSON_GetArraySize(properties); for(int i=0;i!=propSize;i++) { cJSON *tile=cJSON_GetArrayItem(properties,i); int index=atoi(tile->string); bool b[4]={false,false,false,false};//non-blocking border bool isDoor=false; bool isEndPoint=false; bool isNPC=false; int NPCindex=0; int properSize=cJSON_GetArraySize(tile); for(int j=0;j!=properSize;j++) { cJSON * proper=cJSON_GetArrayItem(tile,j); if(CharCMP(proper->string, "Border",sizeof("Border"))) { char* border=cJSON_GetArrayItem(tile,0)->valuestring; for(int i=0;i!=4;i++) if(border[i*2]=='0') b[i]=true;//blocking border } else if(CharCMP(proper->string, "Door",sizeof("Door"))) { isDoor=true; } else if(CharCMP(proper->string, "EndPoint",sizeof("EndPoint"))) { isEndPoint=true; } else if(CharCMP(proper->string, "NPC",sizeof("NPC"))) { isNPC=true; NPCindex=proper->valueint; } } TileUnit tu; if(isNPC) tu.Init(b,isDoor,isEndPoint,isNPC,NPCindex); else tu.Init(b,isDoor,isEndPoint,isNPC); m_TileUnitsKey.append(index); m_TileUnits.append(tu); } } }
AlprResults AlprImpl::fromJson(std::string json) { AlprResults allResults; cJSON* root = cJSON_Parse(json.c_str()); int version = cJSON_GetObjectItem(root, "version")->valueint; allResults.epoch_time = (int64_t) cJSON_GetObjectItem(root, "epoch_time")->valuedouble; allResults.img_width = cJSON_GetObjectItem(root, "img_width")->valueint; allResults.img_height = cJSON_GetObjectItem(root, "img_height")->valueint; allResults.total_processing_time_ms = cJSON_GetObjectItem(root, "processing_time_ms")->valueint; cJSON* rois = cJSON_GetObjectItem(root,"regions_of_interest"); int numRois = cJSON_GetArraySize(rois); for (int c = 0; c < numRois; c++) { cJSON* roi = cJSON_GetArrayItem(rois, c); int x = cJSON_GetObjectItem(roi, "x")->valueint; int y = cJSON_GetObjectItem(roi, "y")->valueint; int width = cJSON_GetObjectItem(roi, "width")->valueint; int height = cJSON_GetObjectItem(roi, "height")->valueint; AlprRegionOfInterest alprRegion(x,y,width,height); allResults.regionsOfInterest.push_back(alprRegion); } cJSON* resultsArray = cJSON_GetObjectItem(root,"results"); int resultsSize = cJSON_GetArraySize(resultsArray); for (int i = 0; i < resultsSize; i++) { cJSON* item = cJSON_GetArrayItem(resultsArray, i); AlprPlateResult plate; //plate.bestPlate = cJSON_GetObjectItem(item, "plate")->valuestring; plate.processing_time_ms = cJSON_GetObjectItem(item, "processing_time_ms")->valuedouble; plate.plate_index = cJSON_GetObjectItem(item, "plate_index")->valueint; plate.region = std::string(cJSON_GetObjectItem(item, "region")->valuestring); plate.regionConfidence = cJSON_GetObjectItem(item, "region_confidence")->valueint; plate.requested_topn = cJSON_GetObjectItem(item, "requested_topn")->valueint; cJSON* coordinates = cJSON_GetObjectItem(item,"coordinates"); for (int c = 0; c < 4; c++) { cJSON* coordinate = cJSON_GetArrayItem(coordinates, c); AlprCoordinate alprcoord; alprcoord.x = cJSON_GetObjectItem(coordinate, "x")->valueint; alprcoord.y = cJSON_GetObjectItem(coordinate, "y")->valueint; plate.plate_points[c] = alprcoord; } cJSON* candidates = cJSON_GetObjectItem(item,"candidates"); int numCandidates = cJSON_GetArraySize(candidates); for (int c = 0; c < numCandidates; c++) { cJSON* candidate = cJSON_GetArrayItem(candidates, c); AlprPlate plateCandidate; plateCandidate.characters = std::string(cJSON_GetObjectItem(candidate, "plate")->valuestring); plateCandidate.overall_confidence = cJSON_GetObjectItem(candidate, "confidence")->valuedouble; plateCandidate.matches_template = (cJSON_GetObjectItem(candidate, "matches_template")->valueint) != 0; plate.topNPlates.push_back(plateCandidate); if (c == 0) { plate.bestPlate = plateCandidate; } } allResults.plates.push_back(plate); } cJSON_Delete(root); return allResults; }
int main() { char* para_str = NULL; char* s_begin = NULL; char para[30] = {0}; char* tmp_ptr = para; printf("Content-type: text/html\n\n"); // CGI返回头 if (!getenv("QUERY_STRING")) { printResult(ST_QueryString); return -1; } // 获取传入的所有参数 para_str = getenv("QUERY_STRING"); if (!(s_begin = strstr(para_str, "second=")) || !strstr(para_str, "callback=") || !strstr(para_str, "encodemethod=") || !strstr(para_str, "sign=")) { printResult(ST_TooFewPara); return -1; } // TODO: 判断每个参数的合法性 s_begin = strstr(s_begin, "="); s_begin++; if (*s_begin == '\0' || *s_begin == '&') { printResult(ST_ParaSecond); return -1; } while ((*tmp_ptr++ = *s_begin++) != '\0') { if (*s_begin == '&') { break; } } //========================================================================= // 调用getZBNode.cgi,并获取返回结果 int socket_fd; int len; struct sockaddr_in remote_addr; char buf[BUF_SIZE] = {0}; char* recv_data = NULL; int recv_data_size = 0; memset(&remote_addr, 0, sizeof(remote_addr)); remote_addr.sin_family = AF_INET; remote_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); remote_addr.sin_port = htons(80); if ((socket_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { close(socket_fd); printResult(ST_SockCreate); return -1; } if (connect(socket_fd, (struct sockaddr*)&remote_addr, sizeof(struct sockaddr)) < 0) { close(socket_fd); printResult(ST_SockConnect); return -1; } send(socket_fd, GetZBNode, strlen(GetZBNode), 0); while ((len = recv(socket_fd, buf, BUF_SIZE, 0)) > 0) { recv_data = (char*)realloc(recv_data, sizeof(char)*(recv_data_size + len + 1)); memcpy(recv_data + recv_data_size, buf, len); recv_data_size += len; *(recv_data + recv_data_size) = '\0'; } close(socket_fd); if (!recv_data) { printResult(ST_GetInfo); return -1; } //========================================================================= cJSON* json_recv; cJSON* json_array; cJSON* json_node; cJSON* json_tmp; char* begin = strchr(recv_data, '{'); char* end = strrchr(recv_data, '}'); if (!begin || !end) { free(recv_data); printResult(ST_JsonParse); return -1; } int json_len = end - begin + 1; char* json_str = (char*)calloc(sizeof(char), json_len + 1); // 增加一个字节保存'\0' strncpy(json_str, begin, json_len); free(recv_data); recv_data = NULL; json_recv = cJSON_Parse(json_str); if (!json_recv) { free(json_str); cJSON_Delete(json_recv); printResult(ST_JsonParse); return -1; } free(json_str); json_str = NULL; json_array = cJSON_GetObjectItem(json_recv, "response_params"); if (!json_array) { cJSON_Delete(json_recv); printResult(ST_InvalidResPara); return -1; } int array_size = cJSON_GetArraySize(json_array); if (array_size == 0) { cJSON_Delete(json_recv); printResult(ST_ArraySize); return -1; } char* ieee = NULL; char request[BUF_SIZE] = {0}; int i = 0; for (i = 0; i < array_size; ++i) { // 对于其中某个设备操作失败直接忽略 json_tmp = cJSON_GetArrayItem(json_array, i); if (!json_tmp) { continue; } json_node = cJSON_GetObjectItem(json_tmp, "node"); if (!json_node) { continue; } json_tmp = cJSON_GetObjectItem(json_node, "node_type"); if (!json_tmp) { continue; } if (atoi(cJSON_PrintUnformatted(json_tmp)) == ZB_EndDevice) { continue; } json_tmp = cJSON_GetObjectItem(json_node, "ieee"); if (!json_tmp) { continue; } ieee = cJSON_PrintRawString(json_tmp); sprintf(request, "GET /cgi-bin/rest/network/setPermitJoinOn.cgi?" "ieee=%s&%s HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n", ieee, para_str); free(ieee); if ((socket_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { close(socket_fd); continue; } if (connect(socket_fd, (struct sockaddr*)&remote_addr, sizeof(struct sockaddr)) < 0) { close(socket_fd); continue; } send(socket_fd, request, strlen(request), 0); close(socket_fd); } cJSON_Delete(json_recv); printResult(ST_Success); char cmd[BUF_SIZE] = {0}; sprintf(cmd, "/gl/bin/led-zigbee %s > /dev/null 2>&1 &", para); system("killall -9 led-zigbee"); system(cmd); return 0; }
void Screen_Base::ImportMenuLayout(const char* layout) { if( layout == 0 ) return; cJSON* menuitemarray = cJSON_Parse( layout ); assert( menuitemarray ); if( menuitemarray ) { int numitems = cJSON_GetArraySize( menuitemarray ); assert( numitems <= MAX_MENUITEMS ); for( int i=0; i<numitems; i++ ) { cJSON* menuitem = cJSON_GetArrayItem( menuitemarray, i ); cJSON* objname = cJSON_GetObjectItem( menuitem, "Name" ); int itemindex = -1; for( itemindex = 0; itemindex < MAX_MENUITEMS; itemindex++ ) { if( strcmp( objname->valuestring, m_pMenuItems[itemindex]->m_Name ) == 0 ) break; } if( itemindex < MAX_MENUITEMS ) { float x = 0; float y = 0; float w = 0; float h = 0; float iw = -1; float ih = -1; MenuItem* pMenuItem = m_pMenuItems[itemindex]; cJSONExt_GetFloat( menuitem, "X", &x ); cJSONExt_GetFloat( menuitem, "Y", &y ); cJSONExt_GetFloat( menuitem, "Scale", &pMenuItem->m_Scale.x ); cJSONExt_GetFloat( menuitem, "Scale", &pMenuItem->m_Scale.y ); cJSONExt_GetFloat( menuitem, "Scale", &pMenuItem->m_Scale.z ); cJSONExt_GetFloat( menuitem, "SX", &pMenuItem->m_Size.x ); cJSONExt_GetFloat( menuitem, "SY", &pMenuItem->m_Size.y ); cJSONExt_GetFloat( menuitem, "W", &w ); cJSONExt_GetFloat( menuitem, "H", &h ); cJSONExt_GetFloat( menuitem, "IW", &iw ); cJSONExt_GetFloat( menuitem, "IH", &ih ); cJSONExt_GetFloat( menuitem, "OffX", &pMenuItem->m_PositionOffset.x ); cJSONExt_GetFloat( menuitem, "OffY", &pMenuItem->m_PositionOffset.y ); pMenuItem->SetPositionAndSize( x, y, w, h, iw, ih ); switch( pMenuItem->m_MenuItemType ) { case MIT_Sprite: { MenuSprite* pMenuSprite = GetMenuSprite( itemindex ); cJSONExt_GetFloat( menuitem, "BGShadowX", &pMenuSprite->m_DropShadowOffsetBG_X ); cJSONExt_GetFloat( menuitem, "BGShadowY", &pMenuSprite->m_DropShadowOffsetBG_Y ); } break; case MIT_Text: // MenuText_SaveLoad { MenuText* pMenuText = GetMenuText( itemindex ); cJSONExt_GetFloat( menuitem, "FontHeight", &pMenuText->m_FontHeight ); cJSONExt_GetFloat( menuitem, "TextShadowX", &pMenuText->m_DropShadowOffsetX ); cJSONExt_GetFloat( menuitem, "TextShadowY", &pMenuText->m_DropShadowOffsetY ); cJSONExt_GetUnsignedChar( menuitem, "Justify", &pMenuText->m_Justification ); } break; case MIT_Button: { MenuButton* pMenuButton = GetMenuButton( itemindex ); cJSONExt_GetFloat( menuitem, "FontHeight", &pMenuButton->m_FontHeight ); cJSONExt_GetFloat( menuitem, "BGShadowX", &pMenuButton->m_DropShadowOffsetBG_X ); cJSONExt_GetFloat( menuitem, "BGShadowY", &pMenuButton->m_DropShadowOffsetBG_Y ); cJSONExt_GetFloat( menuitem, "TextShadowX", &pMenuButton->m_DropShadowOffsetText_X ); cJSONExt_GetFloat( menuitem, "TextShadowY", &pMenuButton->m_DropShadowOffsetText_Y ); } break; case MIT_Base: case MIT_InputBox: case MIT_ScrollingText: case MIT_ScrollBox: case MIT_CheckBox: case MIT_NumMenuItemTypes: break; } } } cJSON_Delete( menuitemarray ); } }
int upgradeapp::device_update_data(char * result, int length){ if(length <= 0){ log_out(log_warn, "device_update_data:receive data length is %d\n", length); } cJSON * json = cJSON_Parse(result); if(!json){ log_out(log_error, "device_update_data:invalid json %s\n", result); return -1; } cJSON * jscode = cJSON_GetObjectItem(json, "code"); cJSON * jsmessage = cJSON_GetObjectItem(json, "message"); cJSON * jsdata = cJSON_GetObjectItem(json, "data"); if(!jscode || jscode->type != cJSON_Number || !jsmessage || jsmessage->type != cJSON_String || !jsdata){ cJSON_Delete(json); log_out(log_error, "device_update_data::invalid json %s\n", result); return -1; } if(jscode->valueint != 0){ log_out(log_error, "device_update_data::code %d\n", jscode->valueint); cJSON_Delete(json); return -1; } cJSON * jslst = cJSON_GetObjectItem(jsdata, "upgrade"); if(!jslst){ log_out(log_warn, "device_update_data::no devices\n"); cJSON_Delete(json); return -1; } int count = cJSON_GetArraySize(jslst); log_out(log_debug, "device_update_data::device count %d\n", count); for(int k = 0; k < count; k++){ cJSON * jsdev = cJSON_GetArrayItem(jslst, k); cJSON * jsid = cJSON_GetObjectItem(jsdev, "device_id"); uint dev = jsid->valueuint; cJSON * jsver = cJSON_GetObjectItem(jsdev, "version"); cJSON * jsforce = cJSON_GetObjectItem(jsdev, "force"); cJSON * jsurl = cJSON_GetObjectItem(jsdev, "url"); cJSON * jsver_id = cJSON_GetObjectItem(jsdev, "version_id"); cJSON * jscheck = cJSON_GetObjectItem(jsdev, "check"); cJSON * jstype = cJSON_GetObjectItem(jscheck, "type"); cJSON * jsvalue = cJSON_GetObjectItem(jscheck, "value"); cJSON * jssize = cJSON_GetObjectItem(jscheck, "size"); if(!jsforce || jsforce->type != cJSON_Number || !jsver || jsver->type != cJSON_String || !jsurl || jsurl->type != cJSON_String || !jsid || jsid->type != cJSON_Number || !jsver_id || jsver_id->type != cJSON_Number || !jscheck || !jstype || jstype->type != cJSON_String || !jsvalue || jsvalue->type != cJSON_String || !jssize || jssize->type != cJSON_Number){ log_out(log_error, "start_update_req::invalid json %s\n", jsdev->valuestring); continue; } std::map<uint, dev_state>::iterator it = m_devmap.find(dev); if(it != m_devmap.end()){ it->second.version_id = jsver_id->valueuint; if(jsforce->valueuint == e_force && it->second.line_state == em_online){ char identify[512] = {0}; sprintf(identify, "{\"device_id\":%u,\"url\":\"%s\",\"check\":{\"type\":\"%s\",\"value\":\"%s\",\"size\":%d}}", it->first, jsurl->valuestring, jstype->valuestring, jsvalue->valuestring, jssize->valueint); post_req(it->second.con, start_update_req, identify); it->second.upgrade_state = e_upgrading; log_out(log_warn, "device_update_data:: mgrserver: %s\n", identify); char buf[512] = {0}; sprintf(buf, "msg={\"platform\":\"device\",\"data\":[{\"device_id\":%u,\"version_id\":%u,\"status\":%d}]}", it->first, it->second.version_id, e_upgrading); log_out(log_debug, "device_update_data:post status %s\n", buf); char result[128 * 128] = {0}; if(post(m_api_upgrade_status, buf, strlen(buf), result, sizeof(result)) < 0){ log_out(log_error, "device_update_data:post status fail\n"); } } } else{ log_out(log_warn, "device_update_data:: invalid device(%u)\n", dev); } } cJSON_Delete(json); return 0; }
uint64_t j64bitsi(cJSON *json,int32_t i) { return(get_API_nxt64bits(cJSON_GetArrayItem(json,i))); }
OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr) { if (NULL == jsonStr) { return NULL; } OCStackResult ret = OC_STACK_ERROR; OicSecDoxm_t *doxm = NULL; cJSON *jsonDoxm = NULL; cJSON *jsonObj = NULL; size_t jsonObjLen = 0; unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {}; uint32_t outLen = 0; B64Result b64Ret = B64_OK; cJSON *jsonRoot = cJSON_Parse(jsonStr); VERIFY_NON_NULL(TAG, jsonRoot, ERROR); jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME); VERIFY_NON_NULL(TAG, jsonDoxm, ERROR); doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t)); VERIFY_NON_NULL(TAG, doxm, ERROR); //OxmType -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME); if ((jsonObj) && (cJSON_Array == jsonObj->type)) { doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR); doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *)); VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR); for (size_t i = 0; i < doxm->oxmTypeLen ; i++) { cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR); jsonObjLen = strlen(jsonOxmTy->valuestring) + 1; doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen); VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR); strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen); } } //Oxm -- not Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME); if (jsonObj && cJSON_Array == jsonObj->type) { doxm->oxmLen = (size_t)cJSON_GetArraySize(jsonObj); VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR); doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t)); VERIFY_NON_NULL(TAG, doxm->oxm, ERROR); for (size_t i = 0; i < doxm->oxmLen ; i++) { cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i); VERIFY_NON_NULL(TAG, jsonOxm, ERROR); doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint; } } //OxmSel -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint; } else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->oxmSel = gDoxm->oxmSel; } //sct -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR); doxm->sct = (OicSecCredType_t)jsonObj->valueint; } else // PUT/POST JSON may not have sct so set it to the gDoxm->sct { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->sct = gDoxm->sct; } //Owned -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->owned = jsonObj->valueint; } else // PUT/POST JSON may not have owned so set it to the gDomx->owned { VERIFY_NON_NULL(TAG, gDoxm, ERROR); doxm->owned = gDoxm->owned; } //DeviceId -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR); if(cJSON_String == jsonObj->type) { //Check for empty string, in case DeviceId field has not been set yet if (jsonObj->valuestring[0]) { outLen = 0; b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)), ERROR); memcpy(doxm->deviceID.id, base64Buff, outLen); } } } else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id { VERIFY_NON_NULL(TAG, gDoxm, ERROR); memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id)); } //DPC -- Mandatory jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME); if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR); doxm->dpc = jsonObj->valueint; } else // PUT/POST JSON may not have owned so set it to the gDomx->dpc { if(NULL != gDoxm) { doxm->dpc = gDoxm->dpc; } else { doxm->dpc = false; // default is false } } //Owner -- will be empty when device status is unowned. jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME); if(true == doxm->owned) { VERIFY_NON_NULL(TAG, jsonObj, ERROR); } if(jsonObj) { VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR); outLen = 0; b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff, sizeof(base64Buff), &outLen); VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR); memcpy(doxm->owner.id, base64Buff, outLen); } ret = OC_STACK_OK; exit: cJSON_Delete(jsonRoot); if (OC_STACK_OK != ret) { DeleteDoxmBinData(doxm); doxm = NULL; } return doxm; }
char *jstri(cJSON *json,int32_t i) { return(cJSON_str(cJSON_GetArrayItem(json,i))); }
static double StatQuery_GetArrayNumber( stat_query_section_t *parent, int idx ) { cJSON *object = cJSON_GetArrayItem( (cJSON *)parent, idx ); return StatQuery_JsonToNumber( object ); }
uint32_t juinti(cJSON *json,int32_t i) { if ( json == 0 ) return(0); return(get_API_uint(cJSON_GetArrayItem(json,i),0)); }
void* KaiXinAPI_MessageCenter_JsonParse(char *text) { cJSON *json; cJSON *tmp; tResponseMessageCenter* Response = new tResponseMessageCenter; memset(Response, 0 , sizeof(tResponseMessageCenter)); json=cJSON_Parse(text); tmp = cJSON_GetObjectItem(json,"ret"); if (tmp) { Response->ret = tmp->valueint; } if(Response->ret == 1) { tmp = cJSON_GetObjectItem(json, "uid"); if(tmp) { Response->uid = tmp->valueint; } tmp = cJSON_GetObjectItem(json, "n"); if(tmp) { Response->nCount = tmp->valueint; } tmp = cJSON_GetObjectItem(json, "notices"); if(tmp) { int nSize = 0, i = 0; nSize = cJSON_GetArraySize(tmp); Response->nSize = nSize; if( nSize != 0 ) { Response->pNotices = NULL; Response->pNotices = (MessageCenter_notices*) malloc(sizeof( MessageCenter_notices ) * nSize); memset(Response->pNotices, 0 , sizeof(MessageCenter_notices) * nSize ); } while( i < nSize ) { cJSON *Item = NULL, *pTemp = NULL; Item = cJSON_GetArrayItem(tmp,i); pTemp = cJSON_GetObjectItem(Item, "mtype"); if(pTemp) { Response->pNotices[i].Type = pTemp->valueint; } pTemp = cJSON_GetObjectItem(Item, "n"); if(pTemp) { Response->pNotices[i].Num = pTemp->valueint; } i++; } } } else { } cJSON_Delete(json); return Response; }
int upgradeapp::device_update_data(char * result, int length){ if(length <= 0){ log_out(log_warn, "device_update_data:receive data length is %d\n", length); return -1; } cJSON * json = cJSON_Parse(result); if(!json){ log_out(log_error, "device_update_data:invalid json %s\n", result); cJSON_Delete(json); return -1; } cJSON * jscode = cJSON_GetObjectItem(json, "code"); cJSON * jsmessage = cJSON_GetObjectItem(json, "message"); cJSON * jsdata = cJSON_GetObjectItem(json, "data"); if(!jscode || jscode->type != cJSON_Number || !jsmessage || jsmessage->type != cJSON_String || !jsdata){ log_out(log_error, "device_update_data::invalid json %s\n", result); cJSON_Delete(json); return -1; } if(jscode->valueint != 0){ log_out(log_error, "device_update_data:: error code %d\n", jscode->valueint); cJSON_Delete(json); return -1; } int count = cJSON_GetArraySize(jsdata); log_out(log_debug, "device_update_data::device count %d\n", count); for(int k = 0; k < count; k++){ cJSON * jsdev = cJSON_GetArrayItem(jsdata, k); cJSON * jsstatus = cJSON_GetObjectItem(jsdev, "status"); if(!jsstatus || jsstatus->type != cJSON_Number){ continue; } if(jsstatus->valueint){ continue; } cJSON * jssn = cJSON_GetObjectItem(jsdev, "ulusn"); cJSON * jsver = cJSON_GetObjectItem(jsdev, "target_ver"); cJSON * jsforce = cJSON_GetObjectItem(jsdev, "force"); cJSON * jsurl = cJSON_GetObjectItem(jsdev, "url"); cJSON * jsmiss_id = cJSON_GetObjectItem(jsdev, "mission_id"); cJSON * jstype = cJSON_GetObjectItem(jsdev, "check_type"); cJSON * jsvalue = cJSON_GetObjectItem(jsdev, "check_value"); cJSON * jssize = cJSON_GetObjectItem(jsdev, "size"); if(!jsforce || jsforce->type != cJSON_Number || !jsver || jsver->type != cJSON_String || !jssn || jssn->type != cJSON_String || !jsurl || jsurl->type != cJSON_String || !jsmiss_id || jsmiss_id->type != cJSON_Number || !jstype || jstype->type != cJSON_String || !jsvalue || jsvalue->type != cJSON_String || !jssize || jssize->type != cJSON_Number){ continue; } std::map<strkey_t, dev_state>::iterator it = m_devmap.find(jssn->valuestring); if(it != m_devmap.end()){ it->second.mission_id = jsmiss_id->valueint; if(jsforce->valueuint == e_force && it->second.line_state == em_online && (jsver->valuestring != it->second.version) && it->second.upgrade_state != e_upgrading){ char identify[512] = {0}; sprintf(identify, "{\"sn\":\"%s\",\"url\":\"%s\",\"check\":{\"type\":\"%s\",\"value\":\"%s\",\"size\":%d}}", it->first.c_str(), jsurl->valuestring, jstype->valuestring, jsvalue->valuestring, jssize->valueint); post_req(it->second.con, start_update_req, identify); it->second.upgrade_state = e_upgrading; log_out(log_debug, "device_update_data::post data to mgrserver: %s\n", identify); char buf[512] = {0}; sprintf(buf, "{\"platform\":\"device\",\"sn\":\"%s\",\"version\":\"%s\",\"mission_id\":%d,\"status\":%d,\"time\":%d}", it->first.c_str(), it->second.version.c_str(), it->second.mission_id, e_upgrading, (int)time(NULL)); char result[128 * 128] = {0}; if(post(gs_svr_data.m_api_upgrade_status, buf, strlen(buf), result, sizeof(result)) < 0){ // log_out(log_error, "device_update_data:post status fail\n"); // return -1; } log_out(log_debug, "device_update_data:post status %s\n", buf); } else{ log_out(log_warn, "device_update_data:: device(%s) offline or optional(%u) or upgrading or same version\n", jssn->valuestring, jsforce->valueuint); } } else{ log_out(log_warn, "device_update_data:: invalid device(%s)\n", jssn->valuestring); } } cJSON_Delete(json); return 0; }