Guest User

Untitled

a guest
Aug 7th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. var MQTT = require("async-mqtt");
  2.  
  3. const deviceId = "TheDeviceId";
  4. const iotHubName = "poorlyfundedskynet";
  5. const userName = `${iotHubName}.azure-devices.net/${deviceId}/api-version=2016-11-14`;
  6. const iotHubTopic = `devices/${deviceId}/messages/events/`;
  7. const sas = `SharedAccessSignature sr=${iotHubName}.azure-devices.net%2Fdevices%2F${deviceId}&sig=THeSignaTurE&se=1565174493`;
  8.  
  9. var client = MQTT.connect(`mqtts://${iotHubName}.azure-devices.net:8883`, {
  10. keepalive: 10,
  11. clientId: deviceId,
  12. protocolId: 'MQTT',
  13. clean: false,
  14. protocolVersion: 4,
  15. reconnectPeriod: 1000,
  16. connectTimeout: 30 * 1000,
  17. username: userName,
  18. password: sas,
  19. rejectUnauthorized: false,
  20. });
  21.  
  22. async function doStuff() {
  23.  
  24. console.log("Starting");
  25. try {
  26. await client.publish(iotHubTopic, "It works!");
  27. // This line doesn't run until the server responds to the publish
  28. await client.end();
  29. // This line doesn't run until the client has disconnected without error
  30. console.log("Done");
  31. } catch (e){
  32. // Do something about it!
  33. console.log("Error while sending a message...");
  34. console.log(e.stack);
  35. process.exit();
  36. }
  37. }
  38.  
  39. const ceremony = () => {
  40. return new Promise((resolve, reject) => {
  41. client.on("connect", doStuff);
  42. return resolve();
  43. })
  44. .then((stuff) => {
  45. console.log("Done?", stuff);
  46. })
  47. .catch((err) => {
  48. console.log("Err...", err);
  49. process.exit();
  50. });
  51. }
  52.  
  53. ceremony();
Add Comment
Please, Sign In to add comment