修改后的全部代码:
https://blog.csdn.net/cainiaofu/article/details/114262377?spm=1001.2014.3001.5501
1、编写AP3216C三合一环境光传感器驱动,生成设备节点
我的设备节点是:/dev/AP3216C
2、源码的修改
注:源码位于src/mqtt/example/mqtt_example.c,在此基础上进行修改。
int example_publish(void *handle)
{
int res = 0;
unsigned short temp = 0;
unsigned short humid = 0;
/*需要发布的主题 thing/event/property/post:
表示设备属性上报(eg:上传温湿度数据,以及开关等状态回复,用来确定设备是否可以正常使用),权限是发布*/
const char *fmt = "/sys/%s/%s/thing/event/property/post";
char *topic = NULL;
int topic_len = 0;
char *payload = NULL;
int fd = 0;
int len = 0;unsigned short adc_val = 0;
const char *adc = "/dev/AP3216C";
unsigned short databuf[3];
payload = HAL_Malloc(200);
memset(payload, 0, 200);
if((fd = open(adc, O_RDWR))>0)
{ usleep(100000); /*这是读取开发板三合传感器的关键。如果不加这个休眠,读出的值是0.
推测是因为三合传感器的初始化需要时间,如果马上读取,三合传感器的值还没有显示到设备节点。所以读出的是0*/
if((read(fd,databuf, sizeof(databuf)))==0)
{ //分别取出三合传感器的值
humid= databuf[0];
temp = databuf[1];
adc_val = databuf[2];
}
}
close(fd);
//为了调试
sprintf(payload,"{\"params\":{\"CurrentTemperature\":%d,\"RelativeHumidity\":%d,\"LightLuxValue\":%d},\"method\":\"thing.event.property.post\"}",temp, humid, adc_val);
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);
//将三合传感器的值发送给服务器上指定的topic
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);
return 0;
}
3、效果演示:
https://www.bilibili.com/video/BV1RX4y1G7ZF/