以下是上报数据到华为云Iot的代码片段,配合串口控制灯光,改变灯的状态(ON/OFF),并将状态上报至华为云。
/** 上报属性线程 **/
static void *sync_dev_properties(void *arg){
struct Device *cur_dev = NULL;
char *light_name[4] = {"厨房灯","卧室灯","客厅灯","卫生间灯"};
int i;
/* 组织上报灯光状态的初始json数据 */
cJSON *lights = cJSON_CreateObject();
cJSON *update_key = NULL;
char *update_value = NULL;
for(i=0;i<4;i++){
cJSON_AddItemToObject(lights,light_name[i], cJSON_CreateString(statostr(read_dev_status(light_name[i]))));
}
/* 每3秒向服务器上报数据 */
ST_IOTA_SERVICE_DATA_INFO lights_service = {
.event_time = NULL,
.service_id = "家居灯光",
.properties = cJSON_Print(lights)
};
while(1){
if(IOTA_PropertiesReport(&lights_service,1,0,NULL) != 0 ){
fprintf(stderr,"[mqtt_ctl.c] IOTA_PropertiesReport():occurred error.\n");
}
printf("read_status:%d\n", read_dev_status(light_name[1]));
printf("statostr:%s\n", statostr(read_dev_status(light_name[1])));
sleep(3);
fprintf(stderr,"[mqtt_ctl.c] json data\n%s%s\n", lights_service.service_id,cJSON_Print(lights));
for(i=0;i<4;i++) {
update_key = cJSON_GetObjectItem(lights, light_name[i]);
update_value = statostr(read_dev_status(light_name[i]));
cJSON_SetValuestring(update_key, update_value);
}
lights_service.properties = cJSON_Print(lights);
}
}