Created
February 21, 2020 19:48
-
-
Save scott-stewart/722c67b59a633337861dd4ed766cf7a7 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
// Example code of using MQTT.js to interact with AWS IoT via a presigned url. | |
// See https://gist.github.com/scott-stewart/2d7dc6a01d5da4326a7ad8b49d467354 for | |
// an exmaple of creating a presigned AWS IoT URL from a Rails controller. | |
// This script makes assumptions about page elements and variables not in the | |
// gist, but hopefully demonstrates the gist of using a presigned url approach, | |
// which can work to interact with AWS IoT WebSocket MQTT connections. | |
var iotClient = null; | |
function runIotClient() { | |
var presignUrlRequest = new XMLHttpRequest(); | |
presignUrlRequest.open("GET", "/iot_presigned_url"); | |
presignUrlRequest.responseType = "json"; | |
presignUrlRequest.send(); | |
presignUrlRequest.onload = function() { | |
iotClient = mqtt.connect(presignUrlRequest.response.url, {}); | |
iotClient.on("connect", function(connack) { | |
iotClient.subscribe( "building/sensors/" + serialNumber + "/commands/+" ) | |
}); | |
iotClient.on("close", function () { | |
if(iotClient){ | |
iotClient.end(); | |
} | |
console.log('connection closed.') | |
}); | |
iotClient.on("error", function(err) { | |
console.log('Error: ' + err.toString()); | |
}); | |
iotClient.on("message", function(topic, payload) { | |
if (topic === 'building/sensors/' + serialNumber + '/commands/reset') { | |
var el = document.querySelector('#tempControl'); | |
el.value = 0 | |
} | |
}); | |
} | |
} | |
function publishIt() { | |
if (iotClient && iotClient.connected) { | |
var topic = "building/sensors/" + serialNumber; | |
var currentReading = getCurrentReading(); | |
var payload = JSON.stringify(currentReading); | |
iotClient.publish(topic, payload); | |
} | |
} | |
setInterval(publishIt, 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment