我需要从我的Raspberry中安装的Universal App向Azure Iot Hub(https://azure.microsoft.com/it-it/services/iot-hub/)发送消息 . 我've to use HTTP protocol because Raspberry doesn' t支持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);
}
}
SendEventAsync
给了我:
Exception thrown: 'Microsoft.Azure.Devices.Client.Exceptions.IotHubCommunicationException' in mscorlib.ni.dll
Message: {"An error occurred while sending the request."}
我已经包含在我的项目 Microsoft.AspNet.WebApi.Client
中,如下所示:https://github.com/Azure/azure-iot-sdks/issues/65没有结果 .
"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": {}
}
If I try the SAME code in a Console application it works as expected.
4 回答
@danvy是对的,你需要生成一个SAS令牌,这里是一个签名生成器https://github.com/sandrinodimattia/RedDog/releases
可能有多种方式发送事件,您正在使用http,请查看此示例
查看此文章了解更多详情http://fabriccontroller.net/iot-with-azure-service-bus-event-hubs-authenticating-and-sending-from-any-type-of-device-net-and-js-samples/
尝试使用本教程为您的设备设置连接字符串(_deviceConnectionString)
https://github.com/Azure/azure-iot-sdks/blob/master/tools/DeviceExplorer/doc/how_to_use_device_explorer.md
您可以直接使用从IoT Hub获取的信息或从IoT Suite向导创建的仪表板手动完成 . 它看起来像这样
_deviceConnectionString =“HostName = YourIoTHubName.azure-devices.net; DeviceId = YourDeviceId; SharedAccessKey = YourDeviceSharedAccessKey”;
您是否使用CreateDeviceIdentity工具正确生成了DeviceId和设备密钥?这是指南:https://blogs.windows.com/buildingapps/2015/12/09/windows-iot-core-and-azure-iot-hub-putting-the-i-in-iot/
经过几个小时的搜索,我发现了硬件问题 . 我的Raspberry试图使用未配置的Wi-Fi加密狗发送请求,而所有其他请求都使用网络电缆 . 卸下加密狗就可以了 .