Guest User

Untitled

a guest
Apr 25th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. //Requires node.js and mqtt library installed.
  2. var mqtt = require('mqtt');
  3.  
  4. const thingsboardHost = "localhost";
  5. // Reads the access token from arguments
  6. const accessToken = process.argv[2];
  7. const minTemperature = 17.5, maxTemperature = 30, minHumidity = 12, maxHumidity = 90;
  8.  
  9. // Initialization of temperature and humidity data with random values
  10. var data = {
  11. temperature: minTemperature + (maxTemperature - minTemperature) * Math.random() ,
  12. humidity: minHumidity + (maxHumidity - minHumidity) * Math.random()
  13. };
  14.  
  15. // Initialization of mqtt client using Thingsboard host and device access token
  16. console.log('Connecting to: %s using access token: %s', thingsboardHost, accessToken);
  17. var client = mqtt.connect('mqtt://'+ thingsboardHost, { username: accessToken });
  18.  
  19. // Triggers when client is successfully connected to the Thingsboard server
  20. client.on('connect', function () {
  21. console.log('Client connected!');
  22. // Uploads firmware version as device attribute using 'v1/devices/me/attributes' MQTT topic
  23. client.publish('v1/devices/me/attributes', JSON.stringify({"firmware_version":"1.0.1"}));
  24. // Schedules telemetry data upload once per second
  25. console.log('Uploading temperature and humidity data once per second...');
  26. setInterval(publishTelemetry, 1000);
  27. });
  28.  
  29. // Uploads telemetry data using 'v1/devices/me/telemetry' MQTT topic
  30. function publishTelemetry() {
  31. data.temperature = genNextValue(data.temperature, minTemperature, maxTemperature);
  32. data.humidity = genNextValue(data.humidity, minHumidity, maxHumidity);
  33. client.publish('v1/devices/me/telemetry', JSON.stringify(data));
  34. }
  35.  
  36. // Generates new random value that is within 3% range from previous value
  37. function genNextValue(prevValue, min, max) {
  38. var value = prevValue + ((max - min) * (Math.random() - 0.5)) * 0.03;
  39. value = Math.max(min, Math.min(max, value));
  40. return Math.round(value * 10) / 10;
  41. }
  42.  
  43. //Catches ctrl+c event
  44. process.on('SIGINT', function () {
  45. console.log();
  46. console.log('Disconnecting...');
  47. client.end();
  48. console.log('Exited!');
  49. process.exit(2);
  50. });
  51.  
  52. //Catches uncaught exceptions
  53. process.on('uncaughtException', function(e) {
  54. console.log('Uncaught Exception...');
  55. console.log(e.stack);
  56. process.exit(99);
  57. });
Add Comment
Please, Sign In to add comment