1
votes

I want to make UWP app for receivering messages from Azure IoT hub. I found example code for Console receiver App, but it doesn't work with UWP, because UWP do not support this refference

using Microsoft.ServiceBus.Messaging;

Can someone post code for UWP app for receivering messages from Azure IoT hub?

6
I ran into the exact same issueDave Voyles

6 Answers

1
votes

You can try AzureSBLite, you can install this from NuGet package manager.

https://github.com/ppatierno/azuresblite

Sample Code for receiving:

string ConnectionString = "<EventHub-Compatible-EndPoint>;SharedAccessKeyName=iothubowner;SharedAccessKey<Key>
    static string eventHubEntity = "<EventHub-Compatible-Name>";
    string partitionId = "0";
    DateTime startingDateTimeUtc;
    EventHubConsumerGroup group;
    EventHubClient client;
    MessagingFactory factory;
    EventHubReceiver receiver;

public async Task ReceiveDataFromCloud()
    {
        startingDateTimeUtc = DateTime.UtcNow;
        ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder(ConnectionString);
        builder.TransportType = ppatierno.AzureSBLite.Messaging.TransportType.Amqp;

        factory = MessagingFactory.CreateFromConnectionString(ConnectionString);

        client = factory.CreateEventHubClient(eventHubEntity);
        group = client.GetDefaultConsumerGroup();
        receiver = group.CreateReceiver(partitionId.ToString(), startingDateTimeUtc);//startingDateTimeUtc
        while (true)
        {
            EventData data = receiver.Receive();

            if (data != null)
            {
                var receiveddata = Encoding.UTF8.GetString(data.GetBytes());

                Debug.WriteLine("{0} {1} {2}", data.SequenceNumber, data.EnqueuedTimeUtc.ToLocalTime(), Encoding.UTF8.GetString(data.GetBytes()));

            }
            else
            {
                break;
            }

            await Task.Delay(2000);

        }

        receiver.Close();
        client.Close();
        factory.Close();

    }

You can get EventHub-Compatible-Endpoint and EventHub-Compatible Name from IoTHub settings-> Messaging section. In that under Device to cloud settings.

0
votes

I am also facing same issue.I couldn't receive message Azure IOT hub.Because AMQP is not supporting in UWP. I have tried below sample.But i dont have luck to receive message. https://github.com/Azure/azure-iot-sdks/tree/master/csharp/device/samples/UWPSample

Please let me know,If you have received message in UWP. Is it plan to support AMQP in UWP?When will give this update?

0
votes

Receiving messages sent by the cloud to the device is supported in the official SDK using the HTTP endpoint. See:

https://github.com/Azure/azure-iot-sdks/tree/master/csharp/device/samples/UWPSample

Receiving messages sent by the device to the cloud is trickier because it's an AMQP endpoint but can be done using AMQPNetLite:

https://paolopatierno.wordpress.com/2015/10/31/azure-iot-hub-commands-and-feedback-using-amqp-net-lite/

0
votes

This is Best way to receive messages from iot. there are two way to do this C2D and D2C... cloud to device and device to cloud. It depends on your requirement. Code is full tested by me:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        //txtblkMessages.Text = "test";
        Start();
    }

    private static int MESSAGE_COUNT = 1;

    private const string DeviceConnectionString = "HostName=[your hostname];DeviceId=[your DeviceId];SharedAccessKey=[your shared key]";
    public async Task Start()
    {
        try
        {
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString, TransportType.Amqp);
            //await SendEvent(deviceClient);
            await ReceiveCommands(deviceClient);
        }
        catch (Exception ex)
        {
            Debug.WriteLine("Error in sample: {0}", ex.Message);
        }
    }

    async Task SendEvent(DeviceClient deviceClient)
    {
        string dataBuffer;
        //for (int count = 0; count < MESSAGE_COUNT; count++)
        //{
        dataBuffer = "Hello Iot";
        Message eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
        await deviceClient.SendEventAsync(eventMessage);
        // }
    }

    async Task ReceiveCommands(DeviceClient deviceClient)
    {
        Message receivedMessage;
        string messageData;
        while (true)
        {
            receivedMessage = await deviceClient.ReceiveAsync();
            if (receivedMessage != null)
            {
                messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                txtblkMessages.Text = messageData + "\n" + txtblkMessages.Text;
                await deviceClient.CompleteAsync(receivedMessage);
            }
            //  Note: In this sample, the polling interval is set to 
            //  10 seconds to enable you to see messages as they are sent.
            //  To enable an IoT solution to scale, you should extend this //  interval. For example, to scale to 1 million devices, set 
            //  the polling interval to 25 minutes.
            //  For further information, see
            //  https://azure.microsoft.com/documentation/articles/iot-hub-devguide/#messaging
            await Task.Delay(TimeSpan.FromSeconds(1));
        }
    }
}
0
votes

Please check source code of the UWP application I created:

https://github.com/Daniel-Krzyczkowski/WindowsIoTCore/blob/master/AzureTruckIoT/AzureTruckIoT.SensorsApp/Cloud/CloudDataService.cs

CloudDataService class contains two methods and uses IoT Hub SDK:

  • SendDataToTheCloud
  • ReceiveDataFromTheCloud

This is an example how to send and receive messages with UWP app and IoT Hub.