首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >azure物联网设备到云消息传递

azure物联网设备到云消息传递
EN

Stack Overflow用户
提问于 2019-08-07 13:49:49
回答 3查看 190关注 0票数 0

我想编写一个将设备消息写入云的控制台应用程序。我已经编写了一个使用IOT集线器和preconfig的Cloud2设备应用程序,所有我的集线器设备ID和工作。

下面是我在visual中使用C#连接2云消息的示例代码。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Diagnostics.Tracing;
using Microsoft.Azure.Devices.Client;

namespace Device2CloudApp
{
    class Program
    {

        // private our own fields for connection to IOT.

        private DeviceClient deviceClient;


        // use the device specific connection string.

        private const string IOT_HUB_CONN_STRING = "HostName=eNstaHub.azure-devices.net;DeviceId=GcobaniNumber1;SharedAccessKey="";
        private const string IOT_HUB_DEVICE = "GcobaniNumber1";
        private const string IOT_HUB_DEVICE_LOCATION = "West US";


        /*
         *  We calling all method inside the constructor for memory allocation. 
         */
       public  Program ()
        {

            SendMessageToIOTHubAsync(deviceClient).Wait();

        }

        private async Task SendMessageToIOTHubAsync(DeviceClient deviceClient)
        {
            try
            {
                var payload = "{" +
                "\"deviceId\":\"" + IOT_HUB_DEVICE + "\", " +
                "\"location\":\"" + IOT_HUB_DEVICE_LOCATION + "\", " +
                "\"localTimestamp\":\"" + DateTime.Now.ToLocalTime() + "\"" +
                "}";

                var msg = new Message(Encoding.UTF8.GetBytes(payload));
                System.Diagnostics.Debug.WriteLine("\t{0} > Sending message:[{1}]", DateTime.Now.ToLocalTime(), payload);
                await deviceClient.SendEventAsync(msg);
            }catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("!!!" + ex.Message);
            }
        }


        static void Main(string[] args)
        {
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING);

            // creating a Constructor here for method declarion.

            Program prg = new Program();
        }
    }
}

在我的控制台上,它没有连接到云-IOT集线器;它抛出一个System.NullreferenceException。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-08-08 01:28:25

它应该按照下面的代码工作。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Diagnostics.Tracing;
using Microsoft.Azure.Devices.Client;

namespace Device2CloudApp
{
    class Program
    {
        // private our own fields for connection to IOT.
        private DeviceClient deviceClient;    

        // use the device specific connection string.

        private const string IOT_HUB_CONN_STRING = "HostName=eNstaHub.azure-devices.net;DeviceId=GcobaniNumber1;SharedAccessKey="";
        private const string IOT_HUB_DEVICE = "GcobaniNumber1";
        private const string IOT_HUB_DEVICE_LOCATION = "West US";


        /*
         *  We calling all method inside the constructor for memory allocation. 
         */
        public  Program ()
        {

            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(IOT_HUB_CONN_STRING);
            SendMessageToIOTHubAsync(deviceClient).Wait();

        }

        private async Task SendMessageToIOTHubAsync(DeviceClient deviceClient)
        {
            try
            {
                var payload = "{" +
                "\"deviceId\":\"" + IOT_HUB_DEVICE + "\", " +
                "\"location\":\"" + IOT_HUB_DEVICE_LOCATION + "\", " +
                "\"localTimestamp\":\"" + DateTime.Now.ToLocalTime() + "\"" +
                "}";

                var msg = new Message(Encoding.UTF8.GetBytes(payload));
                System.Diagnostics.Debug.WriteLine("\t{0} > Sending message:[{1}]", DateTime.Now.ToLocalTime(), payload);
                await deviceClient.SendEventAsync(msg);
            }catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("!!!" + ex.Message);
            }
        }


        static void Main(string[] args)
        {
            // creating a Constructor here for method declarion.

            Program prg = new Program(deviceClient);
        }
    }
}
票数 0
EN

Stack Overflow用户

发布于 2019-08-07 13:54:13

deviceClient方法中有一个本地main,这不是与Azure通信时使用的方法。

删除该实例,然后创建类中的实例。

票数 1
EN

Stack Overflow用户

发布于 2019-08-08 02:56:30

请试试这个.Hope,它很有帮助。

首先声明常量。

代码语言:javascript
复制
    private const string DeviceKey = "your secret key";
    private const string DeviceId = "DeviceName";

然后创建基于SymmetricKey的连接字符串。

代码语言:javascript
复制
     _deviceClient = DeviceClient.Create(IotHubUri, new 
     DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt);

仿真器示例代码:

代码语言:javascript
复制
   using System;
   using System.Text;
   using System.Threading.Tasks;
   using Microsoft.Azure.Devices.Client;
   using Newtonsoft.Json;
   namespace SimulatedDevice
   {
   class Program
    {
    private const string IotHubUri = "YourHubName.azure-devices.net";
    private const string DeviceKey = "Secret Key";
    private const string DeviceId = "DeviceId";
    private const double MinVoltage = 40;
    private const double MinTemperature = 10;
    private const double MinHumidity = 50;
    private static readonly Random Rand = new Random();
    private static DeviceClient _deviceClient;
    private static int _messageId = 1;

    static void Main(string[] args)
    {
        Console.WriteLine("Simulated device\n");
        _deviceClient = DeviceClient.Create(IotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt);
        _deviceClient.ProductInfo = "Simulated_Client";

        SendDeviceToCloudMessagesAsync();
        Console.ReadLine();
    }

    private static async void SendDeviceToCloudMessagesAsync()
    {
        while (true)
        {
            var currentVoltage = MinVoltage + Rand.NextDouble() * 15;
            var currentTemperature = MinTemperature + Rand.NextDouble() * 20;
            var currentHumidity = MinHumidity + Rand.NextDouble() * 25;

            var telemetryDataPoint = new
            {

                deviceId = DeviceId,
                timestamp = DateTime.UtcNow,
                Temperature = currentTemperature,
                Humidity = currentHumidity,
                Voltage = currentVoltage,

            };
            var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
            var message = new Message(Encoding.ASCII.GetBytes(messageString));

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

            await Task.Delay(2000);
          }
         }

      }
     }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57396012

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档