从xamarin .netstandard中的Azure IotHub接收消息

时间:2020-03-30 03:11:52

标签: azure xamarin xamarin.forms azure-iot-hub .net-standard-2.0

我正在使用Visual Studio 2019在.netStandard 2.0中开发xamarin应用程序,我从iothub接收数据时遇到问题,我能够将xamarin应用程序的数据发送到iot hub,但无法从azure iothub接收数据。

解放

  1. Microsoft.Azure.Device(1.20.0)
  2. Microsoft.Azure.Device.Client(1.24.0)

    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.http1);
        await SendEvent(deviceClient);
        await ReceiveCommands(deviceClient);
     }
    catch (Exception ex)
     {
        Debug.WriteLine("Error in sample: {0}", ex.Message);
     }
    }
    async Task SendEvent(DeviceClient deviceClient)
    {
    string dataBuffer;        
    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);
        }
    
        await Task.Delay(TimeSpan.FromSeconds(1));
    }
    }
    

0 个答案:

没有答案