Search code examples
azure-iot-central

How do I implement the 'const patch = {...}' in the code below equivalent in C#


I am trying to implement this same method in C# but can't find an equivalent for the javascript const patch = {..}

I also don't really understand what is going on here - why does the patch have a property 'rundiagnostics' which seems to be the method name, and why are the twin reported properties being updated.

I am wanting to process a long running command and reflect the result in the commands response. It is not entirely clear how IoT Central handles the long running commands so any additional explanation would be welcome. Maybe a sequence diagram or two (??).

Link to docs here

client.onDeviceMethod('rundiagnostics', commandHandler);

// ...

const commandHandler = async (request, response) => {
  switch (request.methodName) {
  case 'rundiagnostics': {
    console.log('Starting long-running diagnostics run ' + request.payload);
    await sendCommandResponse(request, response, 202, 'Diagnostics run started');

    // Long-running operation here
    // ...

    const patch = {
      rundiagnostics: {
        value: 'Diagnostics run complete at ' + new Date().toLocaleString()
      }
    };

    deviceTwin.properties.reported.update(patch, function (err) {
      if (err) throw err;
      console.log('Properties have been reported for component');
    });
    break;
  }
  default:
    await sendCommandResponse(request, response, 404, 'unknown method');
    break;
  }
};

Solution

  • I also don't really understand what is going on here - why does the patch have a property 'rundiagnostics' which seems to be the method name, and why are the twin reported properties being updated.

    IoT Hub (that IoT Central uses) has no support for long-running tasks natively. They way that it's implemented is by using a Direct Method to contact the device. The device needs to respond within 300 seconds (this is an IoT Hub limit, IoT Central might limit it even more, I don't remember). To get around this limitation for long running tasks, IoT Central allows the device to respond with 202 accepted instead. The reported property update is done with the same name as the method so that IoT Central understands that it's related to the Direct Method that was called. So in essence the reported property update signals IoT Central that the work is done.

    As for the patch, you could go with a string, but the C# DeviceClient does not support a string in deviceClient.UpdateReportedPropertiesAsync(). The RegistryManager in the other answer does, but that's not what you need on the device side. You need to turn the string into a TwinCollection, or just use an object:

    var patch = new
    {
        rundiagnostics = new
        {
            value = $"Diagnostics run complete at {DateTime.Now}"
        }
    };
    
    var twinCollection= new TwinCollection(JObject.FromObject(patch), null);