C# 从Raspberry向Azure Iot中心发送消息

C# 从Raspberry向Azure Iot中心发送消息,c#,azure,win-universal-app,raspberry-pi2,C#,Azure,Win Universal App,Raspberry Pi2,我需要从我的Raspberry中安装的通用应用程序向Azure Iot Hub()发送消息。我不得不使用HTTP协议,因为Raspberry不支持AMQP。 我使用以下代码: public sealed partial class MainPage : Page { private DispatcherTimer _timer = null; private DeviceClient _deviceClient = null; private const string _

我需要从我的Raspberry中安装的通用应用程序向Azure Iot Hub()发送消息。我不得不使用HTTP协议,因为Raspberry不支持AMQP。 我使用以下代码:

public sealed partial class MainPage : Page
{
    private DispatcherTimer _timer = null;
    private DeviceClient _deviceClient = null;
    private const string _deviceConnectionString = "<myConnectionString>";

    public MainPage()
    {
        InitializeComponent();

        _deviceClient = DeviceClient.CreateFromConnectionString(_deviceConnectionString, TransportType.Http1);

        _timer = new DispatcherTimer();
        _timer.Interval = TimeSpan.FromSeconds(5);
        _timer.Tick += _timer_Tick;
        _timer.Start();
    }

    private async void _timer_Tick(object sender, object e)
    {
        string msg = "{deviceId: 'myFirstDevice', timestamp: " + DateTime.Now.Ticks + " }";

        Message eventMessage = new Message(Encoding.UTF8.GetBytes(msg));
        await _deviceClient.SendEventAsync(eventMessage);
    }
}
我已经在我的项目
Microsoft.AspNet.WebApi.Client
中加入了以下文档:没有结果

"dependencies": {
    "Microsoft.AspNet.WebApi.Client": "5.2.3",
    "Microsoft.Azure.Devices.Client": "1.0.0-preview-007",
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
 },
"frameworks": {
    "uap10.0": {}
}

如果我在控制台应用程序中尝试相同的代码,它将按预期工作。@danvy是对的,您需要生成一个SAS令牌,这里是一个签名生成器

发送事件可能有多种方式,如果您使用http,请查看此示例

// Generate a SAS key with the Signature Generator.: 
var sas = "SharedAccessSignature sr=https%3a%2f%2freddogeventhub.servicebus.windows.net%2ftemperature%2fpublishers%2flivingroom%2fmessages&sig=I7n%2bqlIExBRs23V4mcYYfYVYhc6adOlMAeTY9VM9kNg%3d&se=1405562228&skn=SenderDevice";

// Namespace info.
var serviceNamespace = "myeventhub";  
var hubName = "temperature";  
var deviceName = "livingroom";

// Create client.
var httpClient = new HttpClient();  
httpClient.BaseAddress =  
           new Uri(String.Format("https://{0}.servicebus.windows.net/", serviceNamespace));
httpClient.DefaultRequestHeaders  
           .TryAddWithoutValidation("Authorization", sas);

Console.WriteLine("Starting device: {0}", deviceName);

// Keep sending.
while (true)  
{
    var eventData = new
    {
        Temperature = new Random().Next(20, 50)
    };

    var postResult = httpClient.PostAsJsonAsync(
           String.Format("{0}/publishers/{1}/messages", hubName, deviceName), eventData).Result;

    Console.WriteLine("Sent temperature using HttpClient: {0}", 
           eventData.Temperature);
    Console.WriteLine(" > Response: {0}", 
           postResult.StatusCode);
    Console.WriteLine(" > Response Content: {0}", 
           postResult.Content.ReadAsStringAsync().Result);

    Thread.Sleep(new Random().Next(1000, 5000));
}

查看本文以了解更多详细信息

尝试使用本教程设置设备的连接字符串(\u deviceConnectionString)

您可以使用直接从IoT Hub或IoT套件向导创建的仪表板获取的信息手动完成。看起来像这样


_deviceConnectionString=“HostName=YourIoTHubName.azure devices.net;DeviceId=YourDeviceId;SharedAccessKey=YourDeviceSharedAccessKey”

您是否使用CreateDeviceIdentity工具正确生成了DeviceId和设备密钥?
以下是指南:

经过几个小时的搜索,我发现了一个硬件问题。我的Raspberry试图使用未配置的Wi-Fi加密狗发送请求,而对于所有其他请求,则使用网络电缆。移除加密狗成功了。

您的项目具有什么样的功能?只有
互联网(客户端)
您才能尝试手动使用此代码发送事件:您可以使用此工具创建SAS令牌:我正在使用新的Azure IoT Hub()我在这里遵循了Microsoft的入门指南:连接字符串在控制台应用程序中使用相同的代码可以正常工作。你的应用程序是否在你的电脑上运行?我已经添加了解决方案。这是一个硬件问题。按照文章的步骤,复制粘贴的代码和相同的错误<代码>发送请求时出错。内部异常是:
{“来自HRESULT的异常:0x80072F05”}
您可以在GitHub或其他地方与我共享代码吗?我添加了解决方案,这是一个硬件问题。感谢这封信,我发现如果我的pi有多个网络连接可供选择,我会感到困惑。我的Raspberry pi 3现在也面临同样的问题,但问题是我没有使用任何wifi加密狗,但是,内部wifi组件可能会导致类似的问题?如果内部raspberry datime未设置为now,则可能会出现相同的问题!我的在过去!看这里
// Generate a SAS key with the Signature Generator.: 
var sas = "SharedAccessSignature sr=https%3a%2f%2freddogeventhub.servicebus.windows.net%2ftemperature%2fpublishers%2flivingroom%2fmessages&sig=I7n%2bqlIExBRs23V4mcYYfYVYhc6adOlMAeTY9VM9kNg%3d&se=1405562228&skn=SenderDevice";

// Namespace info.
var serviceNamespace = "myeventhub";  
var hubName = "temperature";  
var deviceName = "livingroom";

// Create client.
var httpClient = new HttpClient();  
httpClient.BaseAddress =  
           new Uri(String.Format("https://{0}.servicebus.windows.net/", serviceNamespace));
httpClient.DefaultRequestHeaders  
           .TryAddWithoutValidation("Authorization", sas);

Console.WriteLine("Starting device: {0}", deviceName);

// Keep sending.
while (true)  
{
    var eventData = new
    {
        Temperature = new Random().Next(20, 50)
    };

    var postResult = httpClient.PostAsJsonAsync(
           String.Format("{0}/publishers/{1}/messages", hubName, deviceName), eventData).Result;

    Console.WriteLine("Sent temperature using HttpClient: {0}", 
           eventData.Temperature);
    Console.WriteLine(" > Response: {0}", 
           postResult.StatusCode);
    Console.WriteLine(" > Response Content: {0}", 
           postResult.Content.ReadAsStringAsync().Result);

    Thread.Sleep(new Random().Next(1000, 5000));
}