我首先通过 EdgeAgent、EdgeHub 和所有模块孪生重构现有部署,从而通过部署 API 设法做到了这一点。
这是我最终编写的方法的简历:
var modulesContent = new Dictionary<string, IDictionary<string, object>>();
var twinEdgeAgent = await _registryManager.GetTwinAsync(deviceId, "$edgeAgent");
var agentModules = twinEdgeAgent.Properties.Desired[ModulesJsonPropertyName];
agentModules[myModuleId]["status"] = "stopped";
agentModules[myModuleId]["restartPolicy"] = "never";
var desiredProperties = twinEdgeAgent.GetDesiredPropertiesDictionary();
modulesContent.Add("$edgeAgent", edgeHubDesiredProperties);
var twinEdgeHub = await _registryManager.GetTwinAsync(deviceId, "$edgeHub");
var edgeHubDesiredProperties = twinEdgeHub.GetDesiredPropertiesDictionary();
modulesContent.Add("$edgeHub", edgeHubDesiredProperties);
// foreach modules contained in agentModules also add
// the module's twin desired properties in the dictionary (not shown for brevity)
await _registryManager.ApplyConfigurationContentOnDeviceAsync(
deviceId,
new ConfigurationContent { ModulesContent = modulesContent });
internal static class TwinExtensions
{
private const string DesiredPropertiesAttribute = "properties.desired";
public static IDictionary<string, object> GetDesiredPropertiesDictionary(this Twin twin)
{
if (twin == null)
{
throw new ArgumentNullException(nameof(twin));
}
var twinDesiredProperties = twin.Properties.Desired;
twinDesiredProperties.ClearMetadata();
var twinDesiredPropertiesDictionary =
JsonConvert.DeserializeObject<Dictionary<string, object>>(twinDesiredProperties.ToJson());
return new Dictionary<string, object> {{DesiredPropertiesAttribute, twinDesiredPropertiesDictionary}};
}
}
也许有更好/更简单的解决方案,但我们正在使用类似的方法来自动升级模块的运行时映像和其他一些事情,因此我能够在同一代码中重新组合所有这些更改。
如果有办法直接获取部署JSON,那将大大简化,但我没有找到。