2016-12-01 129 views
0

首先简要背景 -天青如何处理DeviceClient.CompleteAsync(消息)

我想出来的教程中HERE。我已经缩小了应用程序的范围,使用Azure IOT集线器在互联网上切换红色或绿色的椭圆。所以这个想法是从我的Windows Phone上的UWP(或桌面,因为这是UWP无关紧要)改变椭圆。

我正在使用本教程中使用的设备浏览器向应用发送消息/命令以切换椭圆的颜色。在命令设备资源管理器完成显示反馈状态如下 -

Message Feedback status: "Success", Description: "Success"

我的猜测是在完成后的每个命令的应用正在发送使用

await DeviceClient.CompleteAsync(Message)

状态,但如何为Device Explorer收到它?抓取网页后我找不到答案,也没有关于此事的任何文档。

要重新使用下面的XAML

<Page 
    x:Class="YourAppName.MainPage" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d"> 

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
     <StackPanel HorizontalAlignment="Center" 
        VerticalAlignment="Center"> 
      <Ellipse x:Name="LED" 
        Fill="LightGray" 
        Stroke="White" 
        Width="100" 
        Height="100" 
        Margin="10"/> 
     </StackPanel> 
     <Button x:Name="onBtn" 
       Content="On/Off" 
       HorizontalAlignment="Left" 
       Margin="140,498,0,0" 
       VerticalAlignment="Top"/> 
     <TextBox x:Name="feedbackTxt" 
       HorizontalAlignment="Left" 
       Margin="15,148,0,0" 
       TextWrapping="Wrap" 
       Text="Status" 
       VerticalAlignment="Top" 
       Width="331"/> 
    </Grid> 
</Page> 

问题创造一个UWP应用程序,然后添加以下代码在MainPage.xaml.cs中

using System; 
using System.Diagnostics; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Windows.UI.Xaml.Media; 
using Microsoft.Azure.Devices; 
using Microsoft.Azure.Devices.Client; 
using Newtonsoft.Json; 
using Message = Microsoft.Azure.Devices.Client.Message; 


namespace YourAppName 
{ 
    public sealed partial class MainPage 
    { 

     private readonly SolidColorBrush _redBrush = new SolidColorBrush(Windows.UI.Colors.Red); 
     private readonly SolidColorBrush _grayBrush = new SolidColorBrush(Windows.UI.Colors.LightGray); 
     private readonly SolidColorBrush _greenBrush = new SolidColorBrush(Windows.UI.Colors.Green); 

     public MainPage() 
     { 
      InitializeComponent(); 

      DeviceClient = DeviceClient.Create(IotHubUri, 
      new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey)); 
      Loaded += async (sender, args) => 
      { 
       // send device connected message 
       await SendDeviceToCloudMessagesAsync(); 

       // receive remote light control events 
       await ReceiveCloudToDeviceMessageAsync(); 
      }; 
     } 

     #region Azure IoT Hub Settings 

     private DeviceClient DeviceClient { get; set; } 

     private string IotHubUri { get; } = "Your HOST Name"; 

     private string DeviceKey { get; } = "Your Device Key"; 

     private static string DeviceId => "Your Device ID"; 

     #endregion 

     public async Task SendDeviceToCloudMessagesAsync() 
     { 
      try 
      { 
       var telemetryDataPoint = new 
       { 
        deviceId = DeviceId, 
        message = "Hello" 
       }; 
       var messageString = JsonConvert.SerializeObject(telemetryDataPoint); 
       var message = new Message(Encoding.ASCII.GetBytes(messageString)); 

       await DeviceClient.SendEventAsync(message); 
       Debug.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); 


      } 
      catch (Exception ex) 
      { 
       Debug.WriteLine(ex.Message); 
      } 
     } 

     public async Task ReceiveCloudToDeviceMessageAsync() 
     { 

      Debug.WriteLine("\nReceiving cloud to device messages from service"); 

      while (true) 
      { 
       var receivedMessage = await DeviceClient.ReceiveAsync(); 
       if (receivedMessage == null) continue; 

       var msg = Encoding.ASCII.GetString(receivedMessage.GetBytes()); 


       if (msg == "on") 
       { 
        LED.Fill = _greenBrush; 
        await DeviceClient.CompleteAsync(receivedMessage); 
        feedbackTxt.Text = msg; 
       } 

       if (msg == "off") 
       { 
        LED.Fill = _redBrush; 
        await DeviceClient.CompleteAsync(receivedMessage); 
        feedbackTxt.Text = msg; 
       } 

      } 

     } 

    } 
} 

打开project.json文件,并替换为以下 -

{ 
    "dependencies": { 
    "Microsoft.Azure.Devices": "1.1.0", 
    "Microsoft.Azure.Devices.Client": "1.0.22", 
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2", 
    "Newtonsoft.Json": "9.0.1" 
    }, 
    "frameworks": { 
    "uap10.0": {} 
    }, 
    "runtimes": { 
    "win10-arm": {}, 
    "win10-arm-aot": {}, 
    "win10-x86": {}, 
    "win10-x86-aot": {}, 
    "win10-x64": {}, 
    "win10-x64-aot": {} 
    } 
} 

最后右键单击pr oject并加入到Windows IOT Extension

参考使用您的凭据替换占位符,你将能够做到这 -

打开 Turn ON

关闭

Turn Off

如何是设备浏览器接收突出显示的Message Feedback status

是 - 我想确认我已发送的命令执行成功

enter image description here

我的使用情况(可以说把灯打开),然后才显示一条消息,告知其完成的用户。

帮助任何人?

在回答Junas

enter image description here

没有真的发生......可能是我得到的using语句错了吗?

回答

0

的官方文档演示如何发送的云到设备的消息接收消息:https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d

我在这里编制的例子:

private static ServiceClient; 
private static string connectionString = "{iot hub connection string}"; 

public static void Main() 
{ 
    Console.WriteLine("Send Cloud-to-Device message\n"); 
    serviceClient = ServiceClient.CreateFromConnectionString(connectionString); 

    ReceiveFeedbackAsync(); 

    Console.WriteLine("Press any key to send a C2D message."); 
    Console.ReadLine(); 
    SendCloudToDeviceMessageAsync().Wait(); 
    Console.ReadLine(); 
} 

private async static Task SendCloudToDeviceMessageAsync() 
{ 
    var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message.")); 
    commandMessage.Ack = DeliveryAcknowledgement.Full; 
    await serviceClient.SendAsync("myFirstDevice", commandMessage); 
} 

private async static void ReceiveFeedbackAsync() 
{ 
    var feedbackReceiver = serviceClient.GetFeedbackReceiver(); 

    Console.WriteLine("\nReceiving c2d feedback from service"); 
    while (true) 
    { 
     var feedbackBatch = await feedbackReceiver.ReceiveAsync(); 
     if (feedbackBatch == null) continue; 

     Console.ForegroundColor = ConsoleColor.Yellow; 
     Console.WriteLine("Received feedback: {0}", string.Join(", ", feedbackBatch.Records.Select(f => f.StatusCode))); 
     Console.ResetColor(); 

     await feedbackReceiver.CompleteAsync(feedbackBatch); 
    } 
} 

总之,你必须:

  1. 创建ServiceClient(并将它缓存)
  2. 开始接收反馈意见与反馈接收器的背景
  3. 发送的消息,并设置确认为完全请求反馈
+0

真棒,让我给它一去,我会回来给你.. – envyM6

+0

我不能得到它的工作。你可以在某处上传解决方案吗?不要忘记删除您的凭据 – envyM6

+0

其实我只是从官方文档中拿出这个,现在我没有时间去设置它:( – juunas