书接上篇博文
ThingsBoard使用笔记(2)模拟传感器发送MQTT并显示监控图表
1.模拟硬件监控设备给定时给服务端发送数据
- 使用mqtt-temperature.js,发送监控数据到服务器,并接受服务器控制,注意修改IP
var mqtt = require('mqtt');
const ACCESS_TOKEN = process.argv[2];
var client = mqtt.connect('mqtt://localhost',{
username: ACCESS_TOKEN
});
var controlValue,
realValue = 25;
client.on('connect', function () {
console.log('connected');
client.subscribe('v1/devices/me/rpc/request/+');
console.log('Uploading temperature data once per second...');
setInterval(publishTelemetry, 1000);
});
client.on('message', function (topic, message) {
console.log('request.topic: ' + topic);
console.log('request.body: ' + message.toString());
var requestId = topic.slice('v1/devices/me/rpc/request/'.length),
messageData = JSON.parse(message.toString());
if (messageData.method === 'getValue') {
if(controlValue === undefined) {
client.publish('v1/devices/me/rpc/response/' + requestId, JSON.stringify(realValue));
} else {
client.publish('v1/devices/me/rpc/response/' + requestId, JSON.stringify(controlValue));
}
} else if (messageData.method === 'setValue') {
controlValue = messageData.params;
console.log('Going to set new control value: ' + controlValue);
} else {
client.publish('v1/devices/me/rpc/response/' + requestId, message);
}
});
function publishTelemetry() {
emulateTemperatureChanging();
client.publish('v1/devices/me/telemetry', JSON.stringify({temperature: realValue}));
}
function emulateTemperatureChanging() {
if(controlValue !== undefined) {
if(controlValue >= realValue) {
realValue += (Math.random() + (Math.abs(controlValue - realValue)/30));
} else {
realValue -= (Math.random() + (Math.abs(controlValue - realValue)/30));
}
}
}
- 执行监控数据发送
# CKbirnV1FPOebt0WfUNs 是设备令牌
node mqtt-temperature.js CKbirnV1FPOebt0WfUNs
2.查看监控图表,能看到一条直线
3.创建温度控制部件
- 创建控制部件
- 选择目标设备
- 保存后效果
- 点击控制温度