Skip to content

Instantly share code, notes, and snippets.

@jsturtevant
Last active April 7, 2023 16:46
Show Gist options
  • Save jsturtevant/1d383c682d0d2c6422218bac4b7f5c8d to your computer and use it in GitHub Desktop.
Save jsturtevant/1d383c682d0d2c6422218bac4b7f5c8d to your computer and use it in GitHub Desktop.
Azure IoT C2D Azure Function
public class DeviceMessage {
public string DeviceId {get;set;}
public string Message {get;set;}
}
{
"frameworks": {
"net46": {
"dependencies": {
"Microsoft.Azure.Devices": "*"
}
}
}
}
#r "Newtonsoft.Json"
#load "Message.csx"
using System;
using Microsoft.Azure.Devices;
using Newtonsoft.Json;
using System.Text;
using System.Configuration;
public async static Task Run(string myEventHubMessage, TraceWriter log)
{
log.Info($"C# Event Hub trigger function processed a message: {myEventHubMessage}");
var parsedMessage = JsonConvert.DeserializeObject<DeviceMessage>(myEventHubMessage);
log.Info($"device id: {parsedMessage.DeviceId}");
var connnectionString = ConfigurationManager.AppSettings["iotservice"];
var serviceClient = ServiceClient.CreateFromConnectionString(connnectionString);
var commandMessage = new Message(Encoding.ASCII.GetBytes($"Cloud to device message: {parsedMessage.Message} "));
log.Info($"sending message");
await serviceClient.SendAsync(parsedMessage.DeviceId, commandMessage);
}
var iothub = require('azure-iothub');
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
if ((req.body && req.body.name)) {
var connectionString = process.env['iotregistry'];
var registry = iothub.Registry.fromConnectionString(connectionString);
var device = {
deviceId: 'sample-device-' + Date.now()
};
console.log('\n**creating device \'' + device.deviceId + '\'');
registry.create(device, function (){
console.log(' device info: ' + JSON.stringify(deviceInfo));
});
res = {
// status: 200, /* Defaults to 200 */
body: {"hello": req.body.name}
};
}
else {
res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done(null, res);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment