Skip to content

Instantly share code, notes, and snippets.

@jamesbulpin
Created November 23, 2017 22:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesbulpin/ff4174423cb31437977c2aad3015cc2a to your computer and use it in GitHub Desktop.
Save jamesbulpin/ff4174423cb31437977c2aad3015cc2a to your computer and use it in GitHub Desktop.
Azure Function to publish a message to my local MQTT broker via Azure IoT Hub
var Client = require('azure-iothub').Client;
var Message = require('azure-iot-common').Message;
function printResultFor(op) {
return function printResult(context, err, res) {
context.log('printResult for ' + op);
if (err) context.log(op + ' error: ' + err.toString());
if (res) context.log(op + ' status: ' + res.constructor.name);
if (err) {
context.res = {
status: 500,
body: op + ' error: ' + err.toString()
};
}
else {
context.res = {
status: 200,
body: "OK"
};
}
context.done();
};
}
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.', JSON.stringify(req, null, 2));
var topic = null;
var message = null;
if (req.query.topic) {
topic = req.query.topic;
}
if (req.body && req.body.topic) {
topic = req.body.topic;
}
if (req.query.message) {
message = req.query.message;
}
if (req.body && req.body.message) {
message = req.body.message;
}
if (req.query.ping || (req.body && req.body.ping)) {
context.res = {
// status: 200, /* Defaults to 200 */
body: "PING OK"
};
}
else if (topic && message) {
context.res = {
// status: 200, /* Defaults to 200 */
body: "OK"
};
}
else {
context.res = {
status: 400,
body: "Please pass a topic and message on the query string or in the request body"
};
}
if (topic && message) {
var connectionString = 'HostName=<My IoT Hub>.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=<key>';
var targetDevice = 'MyMQTTBroker';
var serviceClient = Client.fromConnectionString(connectionString);
serviceClient.open(function (err) {
if (err) {
context.log('Could not connect: ' + err.message);
context.done();
} else {
context.log('Service client connected');
var m = {
"topic": topic,
"message": message
};
var msg = new Message(JSON.stringify(m));
msg.ack = 'full';
msg.messageId = "My Message ID";
context.log('Sending message: ' + msg.getData());
serviceClient.send(targetDevice, msg, printResultFor('send').bind(null, context));
}
});
}
else {
context.done();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment