使用 IoT DevKit 和 Azure IoT Hub 发送云到设备消息 - 设备代码



我需要从 IoT 中心向 DevKit 设备发送消息。基于 https://learn.microsoft.com/en-au/azure/iot-hub/iot-hub-devguide-c2d-guidance 我想发送一个直接方法,因为我需要管理一组中继。

我有一个 IoT DevKit,已成功配置它,并且能够将设备发送到 IoT 中心消息,但我正在寻找一个示例来以另一种方式执行此操作。我目前只能找到设置设备孪生属性的示例,而不能发送直接方法。在服务器端,我相信我会使用 Microsoft.Azure.Devices.ServiceClient 向设备发送异步消息(很高兴被纠正是不正确的)。

在我认为的设备上(???)我需要使用 SetDeviceMethodCallback,但我不知道如何初始化它并接收消息。理想情况下,该示例还包括如何发送消息已接收并已操作的确认。

任何帮助将不胜感激,即使只是为了让我知道我在这里走在正确的轨道上。提前谢谢。

以下是我之前在设备端使用 IoT DevKit (=Mxchip) 的一些示例:

static int  DeviceMethodCallback(const char *methodName, const unsigned char *payload, int size, unsigned char **response, int *response_size)
{
LogInfo("Try to invoke method %s", methodName);
const char *responseMessage = ""Successfully invoke device method"";
int result = 200;
if (strcmp(methodName, "start") == 0)
{
DoSomething();
}
else if (strcmp(methodName, "stop") == 0)
{
DoSomethingElse();
}
else
{
LogInfo("No method %s found", methodName);
responseMessage = ""No method found"";
result = 404;
}
*response_size = strlen(responseMessage) + 1;
*response = (unsigned char *)strdup(responseMessage);
return result;
}
DevKitMQTTClient_SetDeviceMethodCallback(DeviceMethodCallback);

在服务端(执行方法调用的位置),下面是一些 C# 示例

ServiceClient _iothubServiceClient = ServiceClient.CreateFromConnectionString(config["iothubowner_cs"]);
var result = await _iothubServiceClient.InvokeDeviceMethodAsync(deviceid, "start");
var status = result.Status;