谷歌Android things物联网硬件接入阿里云IoT物联网套件云端实战
NXP Pico i.MX7D 完整I/O接口文档
DHT12支持I2C,淘宝有售
ZE08支持UART,淘宝有售
设备接线
产品属性定义
属性名 | 标识符 | 数据类型 | 描述 |
---|---|---|---|
温度 | temperature | float | DHT12传感器采集 |
湿度 | humidity | float | DHT12传感器采集 |
甲醛浓度 | ch2o | double | ZE08传感器采集 |
a) 使用Android Studio创建Android things工程,添加网络权限
<uses-permission android:name="android.permission.INTERNET" />
b) gradle引入eclipse.paho.mqtt
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.0'
c) DHT12Thermometer通过I2C读取DHT12数据
private void readDataFromI2C() {
try {
byte[] data = new byte[5];
i2cDevice.readRegBuffer(0x00, data, data.length);
// check data
if ((data[0] + data[1] + data[2] + data[3]) % 256 != data[4]) {
humidity = temperature = 0;
return;
}
// humidity data
humidity = Double.valueOf(String.valueOf(data[0]) + "." + String.valueOf(data[1]));
Log.d(TAG, "humidity: " + humidity);
// temperature data
if (data[3] < 128) {
temperature = Double.valueOf(String.valueOf(data[2]) + "." + String.valueOf(data[3]));
} else {
temperature = Double.valueOf("-" + String.valueOf(data[2]) + "." + String.valueOf(data[3] - 128));
}
Log.d(TAG, "temperature: " + temperature);
} catch (IOException e) {
Log.e(TAG, "readDataFromI2C error " + e.getMessage(), e);
}
}
d) Ze08CH2O通过UART获取ZE08数据
try {
// data buffer
byte[] buffer = new byte[9];
while (uartDevice.read(buffer, buffer.length) > 0) {
if (checkSum(buffer)) {
ppbCh2o = buffer[4] * 256 + buffer[5];
ch2o = ppbCh2o / 66.64 * 0.08;
} else {
ch2o = ppbCh2o = 0;
}
Log.d(TAG, "ch2o: " + ch2o);
}
} catch (IOException e) {
Log.e(TAG, "Ze08CH2O read data error " + e.getMessage(), e);
}
e) 创建阿里云IoT连接,上报数据
/*
payload格式
{
"id": 123243,
"params": {
"temperature": 25.6,
"humidity": 60.3,
"ch2o": 0.048
},
"method": "thing.event.property.post"
}
*/
MqttMessage message = new MqttMessage(payload.getBytes("utf-8"));
message.setQos(1);
String pubTopic = "/sys/" + productKey + "/" + deviceName + "/thing/event/property/post";
mqttClient.publish(pubTopic, message);