Last active
August 7, 2018 10:51
-
-
Save snobu/a524a85ca5936d591ff5e3cd6a2585ca to your computer and use it in GitHub Desktop.
mqtt.js-iothub
This file contains hidden or 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("async-mqtt"); | |
| const deviceId = "TheDeviceId"; | |
| const iotHubName = "poorlyfundedskynet"; | |
| const userName = `${iotHubName}.azure-devices.net/${deviceId}/api-version=2016-11-14`; | |
| const iotHubTopic = `devices/${deviceId}/messages/events/`; | |
| const sas = `SharedAccessSignature sr=${iotHubName}.azure-devices.net%2Fdevices%2F${deviceId}&sig=THeSignaTurE&se=1565174493`; | |
| var client = MQTT.connect(`mqtts://${iotHubName}.azure-devices.net:8883`, { | |
| keepalive: 10, | |
| clientId: deviceId, | |
| protocolId: 'MQTT', | |
| clean: false, | |
| protocolVersion: 4, | |
| reconnectPeriod: 1000, | |
| connectTimeout: 30 * 1000, | |
| username: userName, | |
| password: sas, | |
| rejectUnauthorized: false, | |
| }); | |
| async function doStuff() { | |
| console.log("Starting"); | |
| try { | |
| await client.publish(iotHubTopic, "It works!"); | |
| // This line doesn't run until the server responds to the publish | |
| await client.end(); | |
| // This line doesn't run until the client has disconnected without error | |
| console.log("Done"); | |
| } catch (e){ | |
| // Do something about it! | |
| console.log("Error while sending a message..."); | |
| console.log(e.stack); | |
| process.exit(); | |
| } | |
| } | |
| const ceremony = () => { | |
| return new Promise((resolve, reject) => { | |
| client.on("connect", doStuff); | |
| return resolve(); | |
| }) | |
| .then((stuff) => { | |
| console.log("Done?", stuff); | |
| }) | |
| .catch((err) => { | |
| console.log("Err...", err); | |
| process.exit(); | |
| }); | |
| } | |
| ceremony(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment