0
votes

I have a device which is sending the binary data packet to the server. I want to migrate that to Azure IoT hub. I want to stick with binary data itself and parse binary data in the Azure function.

I have written the device simulator in .NET using Azure SDK and written the Azure function which gets triggered when message received on IoT Hub.

Code at the Device simulator:

double currentTemperature = 23.0;
byte[] temp= BitConverter.GetBytes(currentTemperature);
double currentHumidity = 24.0;
byte[] humidity= BitConverter.GetBytes(currentHumidity);

List<byte> bytes = new List<byte>();
bytes.AddRange(temp);
bytes.AddRange(humidity);

DeviceClient s_deviceClient; // Created device client here.
var message = new Microsoft.Azure.Devices.Client.Message(bytes.ToArray());
await s_deviceClient.SendEventAsync(message);

In Azure function - If I convert

public static void Run(string myIoTHubMessage, ILogger log)
{
    byte[] dataArray = Encoding.ASCII.GetBytes(myIoTHubMessage);
}

Here I have tried different types of encoding to covert myIoTHubMessage to byte array, but it did not worked.

2
Does it show any error? Can you print the log?Yatin Gaikwad

2 Answers

0
votes

Instead of using string as your input binding attribute, use EventData. See my code here for a complete example.

[FunctionName("IotHubMessageProcessor")]
public static void Run([IoTHubTrigger("messages/events", Connection = "iothubevents_cs", ConsumerGroup = "receiverfunction")]EventData message, ILogger log)

You can then read the body (raw content) as a stream from the message object.

When you use string, the IoTHub binding internally tries to interpret the message body as a UTF-8 encoded string - which obviously fails in your case.

0
votes

try the following:

using System;

public static void Run(byte[] myIoTHubMessage, IDictionary<string, object> properties, IDictionary<string, object> systemproperties, TraceWriter log)
{
    log.Info($"Temperature = {BitConverter.ToDouble(myIoTHubMessage, 0)}");
    log.Info($"Humidity = {BitConverter.ToDouble(myIoTHubMessage, 8)}");

    log.Info($"\nSystemProperties:\n\t{string.Join("\n\t", systemproperties.Select(i => $"{i.Key}={i.Value}"))}");

    log.Info($"\nProperties:\n\t{string.Join("\n\t", properties.Select(i => $"{i.Key}={i.Value}"))}");
}