MQTT上报电压值

不想你离开。 提交于 2019-12-10 23:33:23

添加标准功能

在这里插入图片描述

上报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;
}

实验结果

可以看到打印出的电压值和设备运行状态
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!