Last active
July 26, 2023 11:20
-
-
Save Terny22/2b380427d1a9af823dac03d14f3379ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mqtt = require('mqtt'); | |
const ACCESS_TOKEN = process.argv[2]; | |
var client = mqtt.connect('mqtt://demo.thingsboard.io',{ | |
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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code. But after running this to Thingsboard, the Telemetry value remain constant at 25. How to make it randomly changeable as it is mentioned in the code - changing value in every 60 secs.