【IoT】thingsboard3.3.3测试,使用node-mqtt发送消息

  1. thingsboard.yml端口1883

  2. 服务器防火墙开启1883端口

  3. mqtt消息发送,代码来自互联网:脚本地址https://blog.csdn.net/ieflex/article/details/97149225

//Requires node.js and mqtt library installed.
var mqtt = require('mqtt');

const thingsboardHost = "192.168.198.224";
// Reads the access token from arguments
const accessToken = process.argv[2];
const minTemperature = 17.5,
	maxTemperature = 30,
	minHumidity = 12,
	maxHumidity = 90;

// Initialization of temperature and humidity data with random values
var data = {
	temperature: minTemperature + (maxTemperature - minTemperature) * Math.random(),
	humidity: minHumidity + (maxHumidity - minHumidity) * Math.random()
};

// Initialization of mqtt client using Thingsboard host and device access token
console.log('Connecting to: %s using access token: %s', thingsboardHost, accessToken);
var client = mqtt.connect('mqtt://' + thingsboardHost, {
	username: accessToken
});

// Triggers when client is successfully connected to the Thingsboard server
client.on('connect', function() {
	console.log('Client connected!');
	// Uploads firmware version as device attribute using 'v1/devices/me/attributes' MQTT topic
	client.publish('v1/devices/me/attributes', JSON.stringify({
		"firmware_version": "1.0.1"
	}));
	// Schedules telemetry data upload once per second
	console.log('Uploading temperature and humidity data once per second...');
	setInterval(publishTelemetry, 1000);
});

// Uploads telemetry data using 'v1/devices/me/telemetry' MQTT topic
function publishTelemetry() {
	data.temperature = genNextValue(data.temperature, minTemperature, maxTemperature);
	data.humidity = genNextValue(data.humidity, minHumidity, maxHumidity);
	client.publish('v1/devices/me/telemetry', JSON.stringify(data));
}

// Generates new random value that is within 3% range from previous value
function genNextValue(prevValue, min, max) {
	var value = prevValue + ((max - min) * (Math.random() - 0.5)) * 0.03;
	value = Math.max(min, Math.min(max, value));
	return Math.round(value * 10) / 10;
}

//Catches ctrl+c event
process.on('SIGINT', function() {
	console.log();
	console.log('Disconnecting...');
	client.end();
	console.log('Exited!');
	process.exit(2);
});

//Catches uncaught exceptions
process.on('uncaughtException', function(e) {
	console.log('Uncaught Exception...');
	console.log(e.stack);
	process.exit(99);
});

  1. 使用node执行js脚本发送模拟数据,6r983jTRLUpfsmoROnPt为设备令牌

node emulator_pub.js 6r983jTRLUpfsmoROnPt

  1. 使用仪表板查看数据
posted @ 2022-03-04 11:29  咸鱼翻身  阅读(68)  评论(0编辑  收藏  举报