添加標準功能
上報fmt
const char *fmt="/sys/%s/%s/thing/event/property/post";
在example_publish( )中獲取電壓值並上報
int example_publish(void *handle)
{
int res = 0;
const char *fmt = "/sys/%s/%s/thing/event/property/post";//"/%s/%s/user/get";
char *topic = NULL;
int topic_len = 0;
char *payload = NULL;
int fd, ret;
double vref = 3.36;
double voltage, get_value;
char *data=NULL;
data = HAL_Malloc(20);
memset(data,0,20);
payload = HAL_Malloc(200);
memset(payload, 0, 200);
fd = open(AI8_DATA_PATH, O_RDONLY);
if(fd < 0) {
perror("open AI8_DATA_PATH error");
return -1;
}
ret = read(fd, data, sizeof(data));
if(ret < 0) {
perror("read data error");
return -1;
}
close(fd);
/* collect data and calculate the voltage */
get_value = atof(data);
voltage = vref * (get_value / 4096);
sprintf(payload,"{\"params\":{\"CurrentVoltage\":%0.1f},\"method\":\"thing.event.property.post\"}",voltage);//這裏的CurrentVoltage就是之前添加標準功能的key
topic_len = strlen(fmt) + strlen(DEMO_PRODUCT_KEY) + strlen(DEMO_DEVICE_NAME) + 1;
topic = HAL_Malloc(topic_len);
if (topic == NULL) {
EXAMPLE_TRACE("memory not enough");
return -1;
}
memset(topic, 0, topic_len);
HAL_Snprintf(topic, topic_len, fmt, DEMO_PRODUCT_KEY, DEMO_DEVICE_NAME);
res = IOT_MQTT_Publish_Simple(0, topic, IOTX_MQTT_QOS0, payload, strlen(payload));
if (res < 0) {
EXAMPLE_TRACE("publish failed, res = %d", res);
HAL_Free(topic);
return -1;
}
HAL_Free(topic);
HAL_Free(payload);
HAL_Free(data);
return 0;
}
實驗結果
可以看到打印出的電壓值和設備運行狀態