Hello @Alex Fang,
devices connected to the IoT Hub support both device-to-cloud communication and cloud-to-device communication.
Each device supports:
- Desired/Reported properties
- Direct methods
- Cloud messages
This can be done using any of the available SDKs or via MQTT only directly.
You say you use a Form to change sensors. So your flow should be something like this:
WinForm|Web form -> backend code -> IoT Hub -> Device -> code reacting on C2D message and switch the sensor on or off
In this case, I demonstrate a Direct Method which is perfect when the device is connected to the IoT Hub while manipulated. If you are not sure when the device is connected, check out how to set a desired property on the device.
First, you write some logic on the device to react to incoming Direct Methods:
...
deviceClient.SetMethodHandlerAsync("Switch", HandleMethodSwitch, deviceClient).ConfigureAwait(false);
...
private static Task<MethodResponse> HandleMethodSwitch(MethodRequest methodRequest, object userContext)
{
Console.WriteLine($"method {methodRequest.Name} handled with body {methodRequest.DataAsJson}");
// TODO: switch your sensors based on the body
return Task.FromResult(new MethodResponse(new byte[0], 200));
}
Here, I used C# code to first register a method that will be triggered when the case-sensitive 'Switch' direct method is executed. It's up to you to write the code for the sensors.
Once this code is deployed, write the logic behind the Form.
Here, we use the IoT Hub Service SDK to execute the call (based on this example):
var methodInvocation = new CloudToDeviceMethod("Switch")
{
ResponseTimeout = TimeSpan.FromSeconds(30)
};
methodInvocation.SetPayloadJson("sensor1:off");
var response = await serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);
Console.WriteLine($"Response: {response.Status}; {response.GetPayloadAsJson()}");
Here, a 'Switch' method is constructed and the payload 'sensor1:off' is added.
You can design your own payload.
The method is invoked for your device with a certain ID and the response is shown if the call does not timeout within thirty seconds.
It is recommended to either make the current sensor states visible in the reported properties or using an extra desired method that exposes the state of all sensors.
If the response helped, do "Accept Answer". If it doesn't work, please let us know the progress. All community members with similar issues will benefit by doing so. Your contribution is highly appreciated.