我正在使用amqp将消息从我的iot设备发送到Azure IoTHub . 我正在用C#编写程序,我想检查设备是否能够与iot hub Build 连接 . 实现这一目标的最佳方式是什么?是否可以创建回调函数?
我注意到我的一个设备在一个封闭的网络上,即amqp端口被阻止 . 但设备记录它正在向IoT Hub发送消息(没有抛出异常),当我检查Iot Hub时没有收到任何消息 . 这就是我想检查设备是否能够与IoT Hub Build 连接的原因
java sdk有一个eventcallback类但不是C#,或者我错过了什么?
protected static class EventCallback implements IotHubEventCallback { public void execute(IotHubStatusCode status, Object context) { System.out.println("IoT Hub responded to message with status " + status.name()); } }
编辑:这是一个很好的实现吗?
try { client = DeviceClient.CreateFromConnectionString("***", TransportType.Amqp); var task = client.OpenAsync(); task.Wait(30000); // wait for 30 sec if (task.IsCompleted) { Console.WriteLine("Connected"); await client.CloseAsync(); } else { throw new Exception("Time out"); } } catch (Exception e) { Console.WriteLine("Error"); }
1 回答
假设您正在使用Azure IoT SDK,则 Build 连接或出现错误,将引发异常 .
查看GitHub上的Azure IoT SDK示例 . 这是AmqpSample的链接:https://github.com/Azure/azure-iot-sdk-csharp/tree/master/device/samples/DeviceClientAmqpSample
由于SDK是开源的,因此您可以遍历Microsoft.Azure.Devices.Client代码,并查看针对不同的连接失败将抛出的特定异常(IotHubCommunicationException,UnauthorizedException等) .
对于测试,您可以使用设备资源管理器工具管理设备并监控/发送集线器的消息:https://github.com/Azure/azure-iot-sdk-csharp/tree/master/tools/DeviceExplorer