问题
I need to send a message from the IoT Hub to the DevKit Device. Based on https://docs.microsoft.com/en-au/azure/iot-hub/iot-hub-devguide-c2d-guidance I want to send a Direct Method as I need to manage a bank of relays.
I have an IoT DevKit and have successfully configured it and are able to send device to IoT Hub messages but am looking for a sample to do this the other way. I currently can only find samples that set the device twin properties, not send direct methods. On the server-side I believe I would use Microsoft.Azure.Devices.ServiceClient to SendAsync a message to the device (happy to be corrected is incorrect).
On the device I think (???) I need to use SetDeviceMethodCallback but I have no idea how to initialise it and receive messages. Ideally, the sample would also include how to send an acknowledgement that the message was received and actioned.
Any help would be appreciated even if just to let me know I am on the right track here. Thanks in advance.
回答1:
Here is some sample that I used before with the IoT DevKit (=Mxchip) on the device side:
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);
On the services side (where you do the method invocation) here is some C# example
ServiceClient _iothubServiceClient = ServiceClient.CreateFromConnectionString(config["iothubowner_cs"]);
var result = await _iothubServiceClient.InvokeDeviceMethodAsync(deviceid, "start");
var status = result.Status;
来源:https://stackoverflow.com/questions/58500266/sending-cloud-to-device-messages-using-iot-devkit-and-azure-iot-hub-device-cod