Home > Software engineering >  Sending messages to IoT hub from Azure Time Trigger Function as device
Sending messages to IoT hub from Azure Time Trigger Function as device

Time:09-14

At the moment Im simulating device where every 30 seconds I send telemetry data to IoT hub. Here is simple code:

s_deviceClient = DeviceClient.Create(s_iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(s_myDeviceId, s_deviceKey), TransportType.Mqtt);

using var cts = new CancellationTokenSource();
var messages = SendDeviceToCloudMessagesAsync(cts.Token);
await s_deviceClient.CloseAsync(cts.Token);
await messages;
cts.Cancel();

And function to send message:

string combinedString = fileStrings[0]   fileStrings[1];
var telemetryDataString = converter.SerializeObject(combinedString);

using var message = new Message(Encoding.UTF8.GetBytes(telemetryDataString))
    {
     ContentEncoding = "utf-8",
     ContentType = "application/json",
    };

await s_deviceClient.SendEventAsync(message);
await Task.Delay(interval);

Everything works fine and I created .exe file that was running without problems. But computer where code is running tends to shut-off from time to time which is problematic. So I tried to move this to Azure Time Trigger Function. While in logs everything looks ok, messages aren't actually posted to IoT hub. I tried to find solution but have not been able to find anything. Is it possible to send messages as device with azure function?

CodePudding user response:

You seem to be closing your DeviceClient before you start using it to send messages. Try the following:

public async Task Do()
{
    // Using statement will dispose your client after you're done with it.
    // No need to close it manually.
    using(var client = DeviceClient.Create(s_iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(s_myDeviceId, s_deviceKey), TransportType.Mqtt))
    {
        // Send messages, await for completion.
        await SendDeviceToCloudMessagesAsync(client);
    }
}

private async Task SendDeviceToCloudMessagesAsync(DeviceClient client)
{
    string combinedString = fileStrings[0]   fileStrings[1];
    var telemetryDataString = converter.SerializeObject(combinedString);

    using var message = new Message(Encoding.UTF8.GetBytes(telemetryDataString))
    {
        ContentEncoding = "utf-8",
        ContentType = "application/json",
    };

    await client.SendEventAsync(message);
    await Task.Delay(interval);
}
  • Related