Skip to content

Instantly share code, notes, and snippets.

@Terny22
Last active July 9, 2022 13:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Terny22/987074fc7e43ee75c83973363436c1d0 to your computer and use it in GitHub Desktop.
Save Terny22/987074fc7e43ee75c83973363436c1d0 to your computer and use it in GitHub Desktop.
var mqtt = require('mqtt');
const ACCESS_TOKEN = process.argv[2];
var client = mqtt.connect('mqtt://pe.thingsboard.io',{
username: ACCESS_TOKEN
});
var softwareVersion = 'v1.2.3.456',
temperature = 25;
client.on('connect', function () {
console.log('Client connected!');
client.subscribe('v1/devices/me/rpc/request/+');
client.publish('v1/devices/me/attributes', JSON.stringify({'softwareVersion': softwareVersion}));
console.log('Software version published.');
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 === 'setSoftwareVersion') {
softwareVersion = messageData.params.value;
console.log('New software version was successfylly updated!');
client.publish('v1/devices/me/attributes', JSON.stringify({'softwareVersion': softwareVersion}));
} else {
client.publish('v1/devices/me/rpc/response/' + requestId, message);
}
});
function publishTelemetry() {
emulateTemperatureChanging();
client.publish('v1/devices/me/telemetry', JSON.stringify({'temperature': temperature}));
}
function emulateTemperatureChanging() {
if (temperature >= 25) {
temperature -= Math.random();
} else {
temperature += Math.random();
}
temperature = parseFloat(temperature.toFixed(2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment