static async Task UpdateDeploymentEnvironmentVariablesAsync(TestResultReportingClient apiClient, CancellationTokenSource cts) { RegistryManager registryManager = null; try { registryManager = RegistryManager.CreateFromConnectionString(Settings.Current.IoTHubConnectionString.OrDefault()); JObject deploymentJson = await GetEdgeAgentDeploymentManifestJsonAsync(registryManager, Settings.Current.DeviceId); DateTime testStartAt = DateTime.UtcNow; long count = 1; var envVars = new Dictionary <string, string>(); while (!cts.IsCancellationRequested && DateTime.UtcNow - testStartAt < Settings.Current.TestDuration) { KeyValuePair <string, string> newEnvVar = AddEnvironmentValue(deploymentJson, Settings.Current.TargetModuleId.OrDefault(), count); ConfigurationContent configContent = JsonConvert.DeserializeObject <ConfigurationContent>(deploymentJson.ToString()); await registryManager.ApplyConfigurationContentOnDeviceAsync(Settings.Current.DeviceId, configContent); envVars.Add(newEnvVar.Key, newEnvVar.Value); var testResult = new DeploymentTestResult(Settings.Current.TrackingId, Settings.Current.ModuleId + ".send", envVars, DateTime.UtcNow); await ModuleUtil.ReportTestResultAsync(apiClient, Logger, testResult); Logger.LogInformation($"Successfully report to TRC for new deployment: tracking id={Settings.Current.TrackingId}, new environment variable={newEnvVar.Key}:{newEnvVar.Value}, EnvVars Count={envVars.Count}."); await Task.Delay(Settings.Current.DeploymentUpdatePeriod, cts.Token); count++; } } finally { registryManager?.Dispose(); } }
public static async Task <string> AddModuleOnDeviceAsync(string moduleName, string deviceName, string pipelineName, JObject properties, JObject moduleContent) { pipelineName = pipelineName.ToLower().Replace(" ", string.Empty); var contentStr = string.Empty; switch (pipelineName) { case "workplacesafety": contentStr = BuildContentForAddWorkplaceSafety(moduleName, properties, moduleContent, moduleImageUri); break; default: break; } if (string.IsNullOrEmpty(contentStr)) { return(null); } var content = JsonConvert.DeserializeObject <ConfigurationContent>(contentStr); RegistryManager manager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); await manager.ApplyConfigurationContentOnDeviceAsync(deviceName, content); return(contentStr); }
async Task UpdateDesiredProperties(RegistryManager registryManager, string edgeDeviceId) { var desiredProperties = new { schemaVersion = "1.0", routes = new Dictionary <string, string> { ["route1"] = "from /* INTO $upstream", ["route2"] = "from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", ["route4"] = "from /modules/module3 INTO BrokeredEndpoint(\"/modules/module5/inputs/input1\")", ["route5"] = "from /modules/module5 INTO BrokeredEndpoint(\"/modules/module6/inputs/input1\")", }, storeAndForwardConfiguration = new { timeToLiveSecs = 20 } }; var cc = new ConfigurationContent { ModulesContent = new Dictionary <string, IDictionary <string, object> > { ["$edgeHub"] = new Dictionary <string, object> { ["properties.desired"] = desiredProperties }, ["$edgeAgent"] = new Dictionary <string, object> { ["properties.desired"] = new object() } } }; await registryManager.ApplyConfigurationContentOnDeviceAsync(edgeDeviceId, cc); }
/* Deploy specified Manifest to the specified deviceId */ public async Task <Boolean> Deploy(string deviceid, string modulesTemplate) { /* * AddConfigurationContentOnDeviceAsync (modulesTemplate) */ try { deviceid = deviceid ?? throw new ArgumentNullException(nameof(deviceid)); Device targetDevice = await _registryManager.GetDeviceAsync(deviceid); //Check if the Device exists targetDevice = targetDevice ?? throw new ArgumentNullException(nameof(targetDevice)); //Get all the Modules //Convert baseTemplate to Dictionary<String,Object> //Read the entire modulesTemplate IDictionary <string, object> modulesContentObj = JsonConvert.DeserializeObject <IDictionary <string, object> >(modulesTemplate); //What we essentially have is Dict<"ModulesContent",Object> //Transform ModulesContentObject into Dictionary<String,Object> string modulesObjStr = JsonConvert.SerializeObject(modulesContentObj["modulesContent"]); IDictionary <string, object> modulesContentObj2 = JsonConvert.DeserializeObject <IDictionary <string, object> >(modulesObjStr); //Now build the ConfigurationContent IDictionary<String,IDictionary<String,Object>> IDictionary <string, IDictionary <string, object> > ModulesContent = new Dictionary <string, IDictionary <string, object> >(); IDictionary <string, IDictionary <string, object> > modulesContentConfigContent = new Dictionary <string, IDictionary <string, object> >(); foreach (var item in modulesContentObj2) { //Get the Key //This will be the module names, $edgeAgent, $edgeHub - System Modules & Custom Modules string key = item.Key; //The Value is an object - properties.desired //Grab this from string desiredPropertiesStr = JsonConvert.SerializeObject(modulesContentObj2[key]); //Break it further to level 3 IDictionary<string,object> IDictionary <string, object> modulesContentObj3 = JsonConvert.DeserializeObject <IDictionary <string, object> >(desiredPropertiesStr); modulesContentConfigContent.Add(key, modulesContentObj3); } ConfigurationContent modConfigContent = new ConfigurationContent(); modConfigContent.ModulesContent = modulesContentConfigContent; Console.WriteLine($"Applying to Device {deviceid} configuration {JsonConvert.SerializeObject(modulesContentConfigContent)}"); var modOnConfigTask = _registryManager.ApplyConfigurationContentOnDeviceAsync(deviceid, modConfigContent); await Task.WhenAll(modOnConfigTask).ConfigureAwait(false); } catch (Exception e) { Console.WriteLine(e); } return(true); }
public static async Task <string> DeleteModuleOnDeviceAsync(string moduleName, string deviceName, string pipelineName, JObject moduleContent) { pipelineName = pipelineName.ToLower().Replace(" ", string.Empty); JObject modules = moduleContent["moduleContent"]["$edgeAgent"]["properties.desired"]["modules"] as JObject; modules.Property(moduleName).Remove(); JObject others = moduleContent["moduleContent"] as JObject; others.Property(moduleName).Remove(); var contentStr = moduleContent.ToString(); var content = JsonConvert.DeserializeObject <ConfigurationContent>(contentStr); RegistryManager manager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); await manager.ApplyConfigurationContentOnDeviceAsync(deviceName, content); return(contentStr); }
public async Task <Device> CreateDeviceDeploymentAsync(string deviceId) { Device device = await manager.GetDeviceAsync(deviceId); if (device != null) { await manager.RemoveDeviceAsync(deviceId); } device = new Device(deviceId); device.Capabilities = new DeviceCapabilities { IotEdge = true }; device = await manager.AddDeviceAsync(device); var config = JsonConvert.DeserializeObject <ConfigurationContent>(template); await manager.ApplyConfigurationContentOnDeviceAsync(deviceId, config); return(device); }
public async Task <Boolean> ApplyManifestConfigContent(string deviceid, ConfigurationContent manifestConfigContent, ILogger log) { log.LogInformation("Generate IoTEdge Manifest..."); try { deviceid = deviceid ?? throw new ArgumentNullException(nameof(deviceid)); Device targetDevice = await _registryManager.GetDeviceAsync(deviceid); //Check if the Device exists targetDevice = targetDevice ?? throw new ArgumentNullException(nameof(targetDevice)); var modOnConfigTask = _registryManager.ApplyConfigurationContentOnDeviceAsync(deviceid, manifestConfigContent); await Task.WhenAll(modOnConfigTask).ConfigureAwait(false); } catch (Exception e) { log.LogInformation(e.Message); _errMsg = e.Message; return(false); } return(true); }
public override void ExecuteCmdlet() { if (ShouldProcess(this.IotHubName, Properties.Resources.SetIotHubEdgeModules)) { IotHubDescription iotHubDescription; if (ParameterSetName.Equals(InputObjectParameterSet)) { this.ResourceGroupName = this.InputObject.Resourcegroup; this.IotHubName = this.InputObject.Name; iotHubDescription = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject); } else { if (ParameterSetName.Equals(ResourceIdParameterSet)) { this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId); this.IotHubName = IotHubUtils.GetIotHubName(this.ResourceId); } iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName); } IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName); SharedAccessSignatureAuthorizationRule policy = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite); PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName); RegistryManager registryManager = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString); PSConfigurationContent content = new PSConfigurationContent() { DeviceContent = null, ModulesContent = this.ModulesContent }; registryManager.ApplyConfigurationContentOnDeviceAsync(this.DeviceId, IotHubUtils.ConvertObject <PSConfigurationContent, ConfigurationContent>(content)).GetAwaiter().GetResult(); this.WriteObject(IotHubDataPlaneUtils.ToPSModules(registryManager.GetModulesOnDeviceAsync(this.DeviceId).GetAwaiter().GetResult()), true); } }
public static async System.Threading.Tasks.Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string connectionString = config.GetConnectionString("IoTHubConnectionString"); string deviceConfigurationUrl = Environment.GetEnvironmentVariable("DEVICE_CONFIG_LOCATION"); RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString); // parse query parameter var queryStrings = req.GetQueryParameterDictionary(); string deviceName = ""; string publishingUserName = ""; string publishingPassword = ""; queryStrings.TryGetValue("deviceName", out deviceName); queryStrings.TryGetValue("publishingUserName", out publishingUserName); queryStrings.TryGetValue("publishingPassword", out publishingPassword); Console.WriteLine("un " + publishingUserName); //Get function facade key var base64Auth = Convert.ToBase64String(Encoding.Default.GetBytes($"{publishingUserName}:{publishingPassword}")); var apiUrl = new Uri($"https://{Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE")}.scm.azurewebsites.net/api"); var siteUrl = new Uri($"https://{Environment.GetEnvironmentVariable("WEBSITE_CONTENTSHARE")}.azurewebsites.net"); string JWT; Console.WriteLine("api " + apiUrl); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", $"Basic {base64Auth}"); var result = client.GetAsync($"{apiUrl}/functions/admin/token").Result; JWT = result.Content.ReadAsStringAsync().Result.Trim('"'); //get JWT for call funtion key } string facadeKey = ""; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JWT); string jsonResult = client.GetAsync($"{siteUrl}/admin/host/keys").Result.Content.ReadAsStringAsync().Result; dynamic resObject = JsonConvert.DeserializeObject(jsonResult); facadeKey = resObject.keys[0].value; } Device edgeGatewayDevice = new Device(deviceName); edgeGatewayDevice.Capabilities = new DeviceCapabilities() { IotEdge = true }; await manager.AddDeviceAsync(edgeGatewayDevice); string json = ""; //todo correct using (WebClient wc = new WebClient()) { json = wc.DownloadString(deviceConfigurationUrl); } ConfigurationContent spec = JsonConvert.DeserializeObject <ConfigurationContent>(json); await manager.AddModuleAsync(new Module(deviceName, "LoRaWanNetworkSrvModule")); await manager.ApplyConfigurationContentOnDeviceAsync(deviceName, spec); Twin twin = new Twin(); twin.Properties.Desired = new TwinCollection(@"{FacadeServerUrl:'" + String.Format("https://{0}.azurewebsites.net/api/", GetEnvironmentVariable("FACADE_HOST_NAME")) + "',FacadeAuthCode: " + "'" + facadeKey + "'}"); var remoteTwin = await manager.GetTwinAsync(deviceName); await manager.UpdateTwinAsync(deviceName, "LoRaWanNetworkSrvModule", twin, remoteTwin.ETag); bool deployEndDevice = false; Boolean.TryParse(Environment.GetEnvironmentVariable("DEPLOY_DEVICE"), out deployEndDevice); //This section will get deployed ONLY if the user selected the "deploy end device" options. //Information in this if clause, is for demo purpose only and should not be used for productive workloads. if (deployEndDevice) { Device endDevice = new Device("47AAC86800430028"); await manager.AddDeviceAsync(endDevice); Twin endTwin = new Twin(); endTwin.Tags = new TwinCollection(@"{AppEUI:'BE7A0000000014E2',AppKey:'8AFE71A145B253E49C3031AD068277A1',GatewayID:''," + "SensorDecoder:'DecoderValueSensor'}"); var endRemoteTwin = await manager.GetTwinAsync(deviceName); await manager.UpdateTwinAsync("47AAC86800430028", endTwin, endRemoteTwin.ETag); } var template = @"{'$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#', 'contentVersion': '1.0.0.0', 'parameters': {}, 'variables': {}, 'resources': []}"; HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); Console.WriteLine(template); response.Content = new StringContent(template, System.Text.Encoding.UTF8, "application/json"); return(response); }
public static async System.Threading.Tasks.Task <HttpResponseMessage> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context) { var config = new ConfigurationBuilder() .SetBasePath(context.FunctionAppDirectory) .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables() .Build(); string connectionString = config.GetConnectionString("IoTHubConnectionString"); string deviceConfigurationUrl = Environment.GetEnvironmentVariable("DEVICE_CONFIG_LOCATION"); RegistryManager manager = RegistryManager.CreateFromConnectionString(connectionString); // parse query parameter var queryStrings = req.GetQueryParameterDictionary(); string deviceName = ""; string facadeKey = ""; queryStrings.TryGetValue("deviceName", out deviceName); queryStrings.TryGetValue("facadeKey", out facadeKey); Device edgeGatewayDevice = new Device(deviceName); edgeGatewayDevice.Capabilities = new DeviceCapabilities() { IotEdge = true }; await manager.AddDeviceAsync(edgeGatewayDevice); string json = ""; //todo correct using (WebClient wc = new WebClient()) { json = wc.DownloadString(deviceConfigurationUrl); } ConfigurationContent spec = JsonConvert.DeserializeObject <ConfigurationContent>(json); await manager.AddModuleAsync(new Module(deviceName, "lorawannetworksrvmodule")); await manager.ApplyConfigurationContentOnDeviceAsync(deviceName, spec); Twin twin = new Twin(); twin.Properties.Desired = new TwinCollection(@"{FacadeServerUrl:'" + String.Format("https://{0}.azurewebsites.net/api/", GetEnvironmentVariable("FACADE_HOST_NAME")) + "',FacadeAuthCode: " + "'" + facadeKey + "'}"); var remoteTwin = await manager.GetTwinAsync(deviceName); await manager.UpdateTwinAsync(deviceName, "lorawannetworksrvmodule", twin, remoteTwin.ETag); bool deployEndDevice = false; Boolean.TryParse(Environment.GetEnvironmentVariable("DEPLOY_DEVICE"), out deployEndDevice); if (deployEndDevice) { Device endDevice = new Device("47AAC86800430028"); await manager.AddDeviceAsync(endDevice); Twin endTwin = new Twin(); endTwin.Tags = new TwinCollection(@"{AppEUI:'BE7A0000000014E2',AppKey:'8AFE71A145B253E49C3031AD068277A1',GatewayID:''," + "SensorDecoder:'DecoderRotatorySensor'}"); var endRemoteTwin = await manager.GetTwinAsync(deviceName); await manager.UpdateTwinAsync("47AAC86800430028", endTwin, endRemoteTwin.ETag); } var template = @"{'$schema': 'https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#', 'contentVersion': '1.0.0.0', 'parameters': {}, 'variables': {}, 'resources': []}"; HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); Console.WriteLine(template); response.Content = new StringContent(template, System.Text.Encoding.UTF8, "application/json"); return(response); }