Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.