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); }
public EdgeConfiguration( string deviceId, IEnumerable <string> moduleImages, ConfigurationContent config) { this.config = config; this.deviceId = deviceId; this.moduleImages = moduleImages; }
public void ApplyAutoSaveOptions(ConfigurationContent configContent) { if (configContent.GeneralOptions.AutoSaveEnabled && (State == RecoveryManagerState.Stopped || WaitMinutes != configContent.GeneralOptions.AutoSaveInterval)) { Start(configContent.GeneralOptions.AutoSaveInterval); } else if (!configContent.GeneralOptions.AutoSaveEnabled && State == RecoveryManagerState.Started) { Stop(); } }
public static EdgeConfiguration Create(string deviceId, IEnumerable <ModuleConfiguration> moduleConfigs) { ModuleConfiguration[] modules = moduleConfigs.ToArray(); string[] names = modules.Select(m => m.Name).ToArray(); string[] images = modules.Select(m => m.Image).ToArray(); var config = new ConfigurationContent { ModulesContent = modules .Where(m => m.DesiredProperties.Count != 0) .ToDictionary( m => m.Name, m => (IDictionary <string, object>) new Dictionary <string, object> { ["properties.desired"] = m.DesiredProperties }) }; // Make a copy config = JsonConvert.DeserializeObject <ConfigurationContent>(JsonConvert.SerializeObject(config)); // Build the object we'll use later to verify the deployment ModuleConfiguration edgeAgent = modules.Where(m => m.Name == ModuleName.EdgeAgent).FirstOrDefault() ?? new ModuleConfiguration(); JObject desired = JObject.FromObject(edgeAgent.DesiredProperties); var reported = new Dictionary <string, object> { ["systemModules"] = desired .Value <JObject>("systemModules") .Children <JProperty>() .ToDictionary( p => p.Name, p => p.Name == ModuleName.EdgeAgent.Substring(1) ? CreateExpectedAgentModuleConfig((JObject)p.Value) : CreateExpectedModuleConfig((JObject)p.Value)) }; if (desired.ContainsKey("modules")) { reported["modules"] = desired .Value <JObject>("modules") .Children <JProperty>() .ToDictionary( p => p.Name, p => CreateExpectedModuleConfig((JObject)p.Value)); } var expected = new { properties = new { reported } }; return(new EdgeConfiguration(deviceId, names, images, config, expected)); }
public static void LoadFromConfig(ConfigurationContent configContent) { if (configContent == null) { throw new NullParameterException("Configuration content parameter is null!"); } foreach (ScriptEditorActions action in configContent.ScriptEditorShortcuts.Keys) { SetShortCut(action, configContent.ScriptEditorShortcuts[action]); } }
public EdgeConfiguration( string deviceId, IEnumerable <string> moduleNames, IEnumerable <string> moduleImages, ConfigurationContent config) { this.config = config; this.deviceId = deviceId; this.moduleImages = moduleImages; this.ModuleNames = moduleNames .Select(id => id.StartsWith('$') ? id.Substring(1) : id) .ToArray(); }
public async Task GetDeploymentMetricsTest(bool isEdgeDeployment) { // Arrange var content = new ConfigurationContent() { ModulesContent = isEdgeDeployment ? new Dictionary <string, IDictionary <string, object> >() : null, DeviceContent = !isEdgeDeployment ? new Dictionary <string, object>() : null, }; var label = isEdgeDeployment ? PackageType.EdgeManifest.ToString() : PackageType.DeviceConfiguration.ToString(); var firmware = "Firmware"; var configuration = new Configuration("test-config") { Labels = new Dictionary <string, string>() { { DeploymentNameLabel, string.Empty }, { DeploymentGroupIdLabel, string.Empty }, { this.packageTypeLabel, label }, { ConfigurationTypeLabel, firmware }, { RmCreatedLabel, bool.TrueString }, }, Content = content, }; var deploymentId = configuration.Id; this.registry.Setup(r => r.GetConfigurationAsync(deploymentId)).ReturnsAsync(configuration); this.registry.Setup(r => r.CreateQuery(It.IsAny <string>())).Returns(new ResultQuery(0)); this.tenantHelper.Setup(e => e.GetRegistry()).Returns(this.registry.Object); var deploymentStorageData = this.CreateDeploymentStorageData(0); this.storageAdapterClient.Setup(r => r.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(deploymentStorageData); // Act var returnedDeployment = await this.deployments.GetAsync(deploymentId); // Assert Should return Deplyment metrics according to label Assert.NotNull(returnedDeployment.DeploymentMetrics.DeviceMetrics); Assert.Equal(3, returnedDeployment.DeploymentMetrics.DeviceMetrics.Count()); deploymentStorageData = this.CreateDeploymentStorageData(0, false); this.storageAdapterClient.Setup(r => r.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(deploymentStorageData); returnedDeployment = await this.deployments.GetAsync("deployment0", false, false); Assert.NotNull(returnedDeployment.DeploymentMetrics.DeviceMetrics); Assert.Equal(3, returnedDeployment.DeploymentMetrics.DeviceMetrics.Count()); }
public EdgeConfiguration( string deviceId, IEnumerable <string> moduleNames, IEnumerable <string> moduleImages, ConfigurationContent config, object expectedConfig) { this.config = config; this.deviceId = deviceId; this.expectedConfig = expectedConfig; this.moduleImages = moduleImages; this.ModuleNames = moduleNames .Select(id => id) .ToArray(); }
/* 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 async Task <ConfigurationContent> GenerateManifestConfigContent(string manifestTemplate, List <ModuleDesiredPropertiesRoutes> requestMDPR, ILogger log) { log.LogInformation("Generate IoTEdge Manifest..."); ConfigurationContent modConfigContent = null; try { //Read the entire manifestTemplate log.LogInformation($"Reading Manifest Template"); IDictionary <string, object> manifestTemplateObj = JsonConvert.DeserializeObject <IDictionary <string, object> >(manifestTemplate); //What we essentially have is Dict<"ModulesContent",Object> string modulesContentManifestTemplateObjStr = JsonConvert.SerializeObject(manifestTemplateObj["modulesContent"]); IDictionary <string, object> modulesContentManifestTemplateObj = JsonConvert.DeserializeObject <IDictionary <string, object> >(modulesContentManifestTemplateObjStr); log.LogInformation($"Composing Modules & DesiredProperties DICT"); IDictionary <string, object> modulesDesiredPropertiesDICT = this.BuildDesiredPropertiesDICT(requestMDPR, log); IDictionary <string, object> moduleDefinitionDICT = await this.BuildModuleDefinitionDICT(requestMDPR, log); log.LogInformation($"Built Modules & DesiredProperties DICT"); //EdgeAgent with Module Definition log.LogInformation($"Generating $edgeAgent modules"); modulesContentManifestTemplateObj["$edgeAgent"] = this.GenerateEdgeAgent(modulesContentManifestTemplateObj, moduleDefinitionDICT, log); //EdgeHub with Routes log.LogInformation($"Generating $edgeHub routes"); modulesContentManifestTemplateObj["$edgeHub"] = this.GenerateEdgeHub(modulesContentManifestTemplateObj, requestMDPR, log); //Module Twins log.LogInformation($"Generating Module Twins"); modulesContentManifestTemplateObj = this.GenerateModuleTwins(modulesContentManifestTemplateObj, modulesDesiredPropertiesDICT, log); //Generate ConfigurationContent (modulesContent) modConfigContent = this.AssembleConfigurationContent(modulesContentManifestTemplateObj, log); } catch (Exception e) { log.LogInformation(e.Message); _errMsg = e.Message; return(null); } return(modConfigContent); }
public bool LoadContent(ConfigurationContent configContent) { if (configContent == null) { throw new NullParameterException("Configuration content param is null!"); } if (configContent.TextEditorOptions == null) { throw new NullPropertyException("Configuration content does not contain TextEditorOptions item!"); } _configContent = configContent; //TODO: LoadInitial(); _isContentLoaded = true; return(true); }
public static ConfigurationContent LoadCurrentConfiguration(string fileName) { ConfigurationContent result = null; if (!File.Exists(fileName)) { _currentConfig = new ConfigurationContent(); return(_currentConfig); } result = ObjectXMLSerializer <ConfigurationContent> .Load(fileName); if (result == null) { result = new ConfigurationContent(); } _currentConfig = result; return(result); }
private void PrintContent(string contentType, ConfigurationContent configurationContent) { Console.WriteLine($"Configuration Content [type = {contentType}]"); Console.WriteLine("ModuleContent:"); foreach (string modulesContentKey in configurationContent.ModulesContent.Keys) { foreach (string key in configurationContent.ModulesContent[modulesContentKey].Keys) { Console.WriteLine($"\t\t{key} = {configurationContent.ModulesContent[modulesContentKey][key]}"); } } Console.WriteLine("DeviceContent:"); foreach (string key in configurationContent.DeviceContent.Keys) { Console.WriteLine($"\t{key} = {configurationContent.DeviceContent[key]}"); } }
private ConfigurationContent AssembleConfigurationContent(IDictionary <string, object> modulesContentManifestTemplateObj, ILogger log) { IDictionary <string, IDictionary <string, object> > modulesContentConfigContent = new Dictionary <string, IDictionary <string, object> >(); foreach (var item in modulesContentManifestTemplateObj) { string valueStr = JsonConvert.SerializeObject(modulesContentManifestTemplateObj[item.Key]); IDictionary <string, object> valueObj = JsonConvert.DeserializeObject <IDictionary <string, object> >(valueStr); modulesContentConfigContent.Add(item.Key, valueObj); } ConfigurationContent modConfigContent = new ConfigurationContent { ModulesContent = modulesContentConfigContent }; Console.WriteLine(JsonConvert.SerializeObject(modConfigContent)); return(modConfigContent); }
/// <summary> /// 修改配置, /// TODO:仔细考虑多个场景,不能出现遗漏,极端情况下减少错误判断的可能性 /// </summary> /// <param name="fileName"></param> /// <param name="content"></param> public void Modify(string fileName, ConfigurationContent content) { var original = Config.Configurations.Find(p => p.Filename.Equals(fileName)); if (original == null) { throw new ConfigurationModifyException (ErrorCode.InvalidConfigurationFile, $"修改配置时无法找到相应的配置文件 : {fileName}"); } // 修改当前配置 Config.Configurations.Remove(original); Config.Configurations.Add(content); // 同步配置文件 using (var sw = new StreamWriter(LOCAL_CONFIG_FILENAME)) { serializer.Serialize(sw, Config); } // 重新初始化 Config.Init(); // 触发监听 registers.TryGetValue(fileName, out var eventList); if (eventList == null) { return; } lock (eventList) { foreach (var manualEvent in eventList) { manualEvent.Set(); } // 清空所有监听事件 eventList.Clear(); } }
static async Task UpdateDeploymentEnvironmentVariablesAsync(TestResultReportingClient apiClient, CancellationTokenSource cts) { RegistryManager registryManager = null; try { registryManager = RegistryManager.CreateFromConnectionString(Settings.Current.IoTHubConnectionString); JObject deploymentJson = await GetEdgeAgentDeploymentManifestJsonAsync(registryManager, Settings.Current.DeviceId); DateTime testStartAt = DateTime.UtcNow; long count = 1; while (!cts.IsCancellationRequested && DateTime.UtcNow - testStartAt < Settings.Current.TestDuration) { KeyValuePair <string, string> newEnvVar = AddEnvironmentValue(deploymentJson, Settings.Current.TargetModuleId, count); ConfigurationContent configContent = JsonConvert.DeserializeObject <ConfigurationContent>(deploymentJson.ToString()); await registryManager.ApplyConfigurationContentOnDeviceAsync(Settings.Current.DeviceId, configContent); var testResult = new DeploymentTestResult(Settings.Current.ModuleId + ".send", DateTime.UtcNow) { TrackingId = Settings.Current.TrackingId, EnvironmentVariables = new Dictionary <string, string> { { newEnvVar.Key, newEnvVar.Value } } }; 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}."); await Task.Delay(Settings.Current.DeploymentUpdatePeriod, cts.Token); count++; } } finally { registryManager?.Dispose(); } }
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 static EdgeConfiguration Create(string deviceId, IEnumerable <ModuleConfiguration> modules) { var names = modules.Select(m => m.Name).ToArray(); var images = modules.Select(m => m.Image).ToArray(); var config = new ConfigurationContent { ModulesContent = modules .Where(m => m.DesiredProperties.Count != 0) .ToDictionary( m => m.Name, m => (IDictionary <string, object>) new Dictionary <string, object> { ["properties.desired"] = m.DesiredProperties }) }; // Make a copy config = JsonConvert.DeserializeObject <ConfigurationContent>(JsonConvert.SerializeObject(config)); return(new EdgeConfiguration(deviceId, names, images, config)); }
public ActionResult GetContent(Guid?Id, string langid) { var contentContent = new ConfigurationContent { LanguageId = SessionParameters.Culture }; if (Id != null && Id != Guid.Empty) { var content = CongressComponent.Instance.BaseInfoComponents.ConfigurationContentFacade.Get((Guid)Id, string.IsNullOrEmpty(langid) ? SessionParameters.Culture : langid); if (content != null) { contentContent = content; } } ViewBag.Lanuages = new SelectList(CommonComponent.Instance.LanguageFacade.SelectKeyValuePair(x => x.Id, x => x.DisplayName), "Key", "Value"); ViewBag.CongressContents = new SelectList(CongressComponent.Instance.BaseInfoComponents.CongressContentFacade.SelectKeyValuePair(x => x.ContentId, x => x.Content.Title, x => x.CongressId == this.Homa.Id, new OrderByModel <CongressContent>() { Expression = x => x.Content.Title }), "Key", "Value"); return(PartialView("ConfigurationContent", contentContent)); }
private static async Task ApplyConfigurationOnDevice() { // load local sample deployment manifest dynamic config = JsonConvert.DeserializeObject(File.ReadAllText("deployment.json")); var cc = new ConfigurationContent() { ModulesContent = new Dictionary <string, IDictionary <string, object> >() }; foreach (var module in config.modulesContent) { cc.ModulesContent.Add(module.Name, new Dictionary <string, object> { ["properties.desired"] = module.Value["properties.desired"] }); } var rm = RegistryManager.CreateFromConnectionString(connectionString); await rm.ApplyConfigurationContentOnDeviceAsync(deviceId, cc); }
public async Task GetDeploymentMetricsTest(bool isEdgeDeployment) { // Arrange var content = new ConfigurationContent() { ModulesContent = isEdgeDeployment ? new Dictionary <string, IDictionary <string, object> >() : null, DeviceContent = !(isEdgeDeployment) ? new Dictionary <string, object>() : null }; var label = isEdgeDeployment ? PackageType.EdgeManifest.ToString() : PackageType.DeviceConfiguration.ToString(); var Firmware = "Firmware"; var configuration = new Configuration("test-config") { Labels = new Dictionary <string, string>() { { DEPLOYMENT_NAME_LABEL, string.Empty }, { DEPLOYMENT_GROUP_ID_LABEL, string.Empty }, { PACKAGE_TYPE_LABEL, label }, { CONFIG_TYPE_LABEL, Firmware }, { RM_CREATED_LABEL, bool.TrueString }, }, Content = content }; var deploymentId = configuration.Id; this.registry.Setup(r => r.GetConfigurationAsync(deploymentId)).ReturnsAsync(configuration); this.registry.Setup(r => r.CreateQuery(It.IsAny <string>())).Returns(new ResultQuery(0)); // Act var returnedDeployment = await this.deployments.GetAsync(deploymentId); // Assert Should return Deplyment metrics according to label Assert.NotNull(returnedDeployment.DeploymentMetrics.DeviceMetrics); Assert.Equal(3, returnedDeployment.DeploymentMetrics.DeviceMetrics.Count()); }
public override async Task <ConfigurationQueryResponseType> Process(ConfigurationQueryRequestType request) { logger.Info($"配置信息查询 : filename {request.File}, version : {request.CurrentVersion}"); ConfigurationContent content = null; await Task.Run(() => { content = DataAdapter.GetContent(request.File); if (content == null) { throw new ConfigurationQueryException (ErrorCode.InvalidConfigurationFile, $"无效的配置文件名 : {request.File}"); } }); // 这里要注意并发可能导致的问题 // TODO // 如果版本检查时是相同的,但是检查后发生了变化,并且已经触发了当前的所有事件,那么该注册的事件可能不会被触发,直到超时。 if (request.CurrentVersion == content.Version) { logger.Info($"配置文件版本没有发生变化,等待中"); // 注册监听事件 var manualEvent = DataAdapter.Register(request.File); manualEvent.Wait(DEFAULT_LONG_POOLING_TIMEOUT_IN_MS); if (manualEvent.IsSet) { return(BuildResponse(DataAdapter.GetContent(request.File))); } else { throw new ConfigurationQueryException (ErrorCode.ConfigurationNotChanged, $"配置文件没有发生变化,操作超时"); } } return(BuildResponse(content)); }
public static SqlConnection GetConnection(bool autoOpen) { ConfigurationContent config = ConfigHelper.Current; if (config == null) { throw new InvalidConfiguration("Application configuration not loaded properly!"); } if (config.PragmaSqlDbConn == null) { throw new NullPropertyException("Configuration content does not contain PragmaSqlDbConn item!"); } SqlConnection conn = new SqlConnection(); conn.ConnectionString = config.PragmaSqlDbConn.ConnectionString; if (autoOpen) { conn.Open(); } _connections.Add(conn); return conn; }
private ConfigurationQueryResponseType BuildResponse(ConfigurationContent content) { var response = new ConfigurationQueryResponseType { Version = content.Version, LastModifyDate = content.LastModifyDate, File = content.Filename }; if (content.Properties == null || content.Properties.Count == 0) { return(response); } response.Properties = new List <ConfigurationItemType>(); content.Properties.ForEach(p => response.Properties.Add(new ConfigurationItemType() { Key = p.Key, Value = p.Value })); return(response); }
public Task DeployDeviceConfigurationAsync( string deviceId, ConfigurationContent config, CancellationToken token) => this.RegistryManager.ApplyConfigurationContentOnDeviceAsync(deviceId, config, token);
public EdgeConfiguration(string deviceId, string agentImage, IotHub iotHub) { this.config = GetBaseConfig(agentImage); this.iotHub = iotHub; this.deviceId = deviceId; }
public async Task<HttpResponseMessage> CreateEdgeDeviceImp( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ExecutionContext context) { // parse query parameter var queryStrings = req.GetQueryParameterDictionary(); queryStrings.TryGetValue("deviceName", out string deviceName); queryStrings.TryGetValue("publishingUserName", out string publishingUserName); queryStrings.TryGetValue("publishingPassword", out string publishingPassword); queryStrings.TryGetValue("region", out string region); queryStrings.TryGetValue("resetPin", out string resetPin); queryStrings.TryGetValue("spiSpeed", out string spiSpeed); queryStrings.TryGetValue("spiDev", out string spiDev); bool.TryParse(Environment.GetEnvironmentVariable("DEPLOY_DEVICE"), out bool deployEndDevice); // 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; 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 = string.Empty; 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 }; try { await this.registryManager.AddDeviceAsync(edgeGatewayDevice); string deviceConfigurationUrl = Environment.GetEnvironmentVariable("DEVICE_CONFIG_LOCATION"); string json = null; // todo correct using (WebClient wc = new WebClient()) { json = wc.DownloadString(deviceConfigurationUrl); } json = ReplaceJsonWithCorrectValues(region, resetPin, json, spiSpeed, spiDev); ConfigurationContent spec = JsonConvert.DeserializeObject<ConfigurationContent>(json); await this.registryManager.AddModuleAsync(new Module(deviceName, "LoRaWanNetworkSrvModule")); await this.registryManager.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 this.registryManager.GetTwinAsync(deviceName); await this.registryManager.UpdateTwinAsync(deviceName, "LoRaWanNetworkSrvModule", twin, remoteTwin.ETag); // 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) { var otaaDevice = new Device(OtaaDeviceId); await this.registryManager.AddDeviceAsync(otaaDevice); var otaaEndTwin = new Twin(); otaaEndTwin.Properties.Desired = new TwinCollection(@"{AppEUI:'BE7A0000000014E2',AppKey:'8AFE71A145B253E49C3031AD068277A1',GatewayID:'',SensorDecoder:'DecoderValueSensor'}"); var otaaRemoteTwin = await this.registryManager.GetTwinAsync(OtaaDeviceId); await this.registryManager.UpdateTwinAsync(OtaaDeviceId, otaaEndTwin, otaaRemoteTwin.ETag); var abpDevice = new Device(AbpDeviceId); await this.registryManager.AddDeviceAsync(abpDevice); var abpTwin = new Twin(); abpTwin.Properties.Desired = new TwinCollection(@"{AppSKey:'2B7E151628AED2A6ABF7158809CF4F3C',NwkSKey:'3B7E151628AED2A6ABF7158809CF4F3C',GatewayID:'',DevAddr:'0228B1B1',SensorDecoder:'DecoderValueSensor'}"); var abpRemoteTwin = await this.registryManager.GetTwinAsync(AbpDeviceId); await this.registryManager.UpdateTwinAsync(AbpDeviceId, abpTwin, abpRemoteTwin.ETag); } } catch (Exception) { // In case of an exception in device provisioning we want to make sure that we return a proper template if our devices are successfullycreated var edgeGateway = await this.registryManager.GetDeviceAsync(deviceName); if (edgeGateway == null) { return PrepareResponse(HttpStatusCode.Conflict); } if (deployEndDevice) { var abpDevice = await this.registryManager.GetDeviceAsync(AbpDeviceId); var otaaDevice = await this.registryManager.GetDeviceAsync(OtaaDeviceId); if (abpDevice == null || otaaDevice == null) { return PrepareResponse(HttpStatusCode.Conflict); } } return PrepareResponse(HttpStatusCode.OK); } return PrepareResponse(HttpStatusCode.OK); }
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 async Task GetDeploymentTypeTest(bool isEdgeContent, bool addLabel, bool isEdgeLabel = false) { // Arrange var content = new ConfigurationContent() { ModulesContent = isEdgeContent ? new Dictionary <string, IDictionary <string, object> >() : null, DeviceContent = !isEdgeContent ? new Dictionary <string, object>() : null, }; var label = string.Empty; if (addLabel) { label = isEdgeLabel ? PackageType.EdgeManifest.ToString() : PackageType.DeviceConfiguration.ToString(); } var configuration = new Configuration("test-config") { Labels = new Dictionary <string, string>() { { DeploymentNameLabel, string.Empty }, { DeploymentGroupIdLabel, string.Empty }, { this.packageTypeLabel, label }, { ConfigurationTypeLabel, "CustomConfig" }, { RmCreatedLabel, bool.TrueString }, }, Content = content, }; var deploymentId = configuration.Id; this.registry.Setup(r => r.GetConfigurationAsync(deploymentId)).ReturnsAsync(configuration); this.registry.Setup(r => r.CreateQuery(It.IsAny <string>())).Returns(new ResultQuery(0)); this.tenantHelper.Setup(e => e.GetRegistry()).Returns(this.registry.Object); var deploymentStorageData = this.CreateDeploymentStorageData(0); this.storageAdapterClient.Setup(r => r.GetAsync(It.IsAny <string>(), It.IsAny <string>())).ReturnsAsync(deploymentStorageData); // Act var returnedDeployment = await this.deployments.GetAsync(deploymentId); // Assert Should returned Deplyment PackageType according to label if (addLabel) { if (isEdgeLabel) { Assert.Equal(PackageType.EdgeManifest, returnedDeployment.PackageType); } else { Assert.Equal(PackageType.DeviceConfiguration, returnedDeployment.PackageType); } } else { if (isEdgeContent) { Assert.Equal(PackageType.EdgeManifest, returnedDeployment.PackageType); } else { Assert.Equal(PackageType.DeviceConfiguration, returnedDeployment.PackageType); } } }
public async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req) { _log.LogInformation("C# HTTP trigger."); string deviceid = req.Query["deviceid"]; if (string.IsNullOrEmpty(deviceid)) { return(new BadRequestObjectResult("Missing deviceid in request")); } string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); /* * [ * { * "ModuleInstanceName": "ModuleA", * "Module": "lvaEdge", * "ToIoThub": true, * "DesiredProperties": "{\"NAME\":\"MODULEA\"}", * "RouteInstanceName": "A1toIoTHub", * "FromModule": "lvaEdge", * "ToModule": null, * "FromChannel": "ONE", * "ToChannel": null * } * ] * 1. Remove \n * 2. Convert \" to " * 3. Convert \"{ to { * 4. Convert \"} to } * 5. Convert from Array into Json Doc */ //Clean up \n requestBody = requestBody.Replace("\\n", ""); //Clean up \" requestBody = requestBody.Replace("\\\"", "\""); //Clean up "{ requestBody = requestBody.Replace("\"{", "{"); //Clean up }" requestBody = requestBody.Replace("}\"", "}"); _log.LogInformation(requestBody); //Load as List of Objects List <ModuleDesiredPropertiesRoutes> mdprInstances = JsonConvert.DeserializeObject <List <ModuleDesiredPropertiesRoutes> >(requestBody); string s_connectionString = Environment.GetEnvironmentVariable("IOTHUB_CONN_STRING_CSHARP"); string s_acruser = Environment.GetEnvironmentVariable("ACRUSER"); string s_acrpassword = Environment.GetEnvironmentVariable("ACRPASSWORD"); string s_acr = Environment.GetEnvironmentVariable("ACR"); string s_cosmosendpoint = Environment.GetEnvironmentVariable("COSMOSENDPOINT"); string s_cosmoskey = Environment.GetEnvironmentVariable("COSMOSKEY"); string s_cosmosAccountName = Environment.GetEnvironmentVariable("COSMOSACCOUNTNAME"); //Connect to IoTHub _registryManager = RegistryManager.CreateFromConnectionString(s_connectionString); //Connect to CosmosDB for Modules and Manifest information - IoTEdge Configuration _cosmosClient = new CosmosClient(s_cosmosendpoint, s_cosmoskey); IotEdgeConfigReader cosmosDBConfigReader = IotEdgeConfigReader.CreateWithCosmosDBConn(_cosmosClient, s_cosmosAccountName, Environment.GetEnvironmentVariable("COSMOSDBNAME"), Environment.GetEnvironmentVariable("COSMOSCONTAINER_MANIFEST"), Environment.GetEnvironmentVariable("COSMOSCONTAINER_ALLMODULES")); string iotEdgeTemplateJSON = await cosmosDBConfigReader.GetIoTEdgeTemplate(); //Replace $ACRUSER $ACRPASSWORD $ACR iotEdgeTemplateJSON = iotEdgeTemplateJSON.Replace("$ACRUSER", s_acruser).Replace("$ACRPASSWORD", s_acrpassword).Replace("$ACR", s_acr); IoTEdgeCTL iotedgeCTL = new IoTEdgeCTL(_registryManager, cosmosDBConfigReader); ConfigurationContent iotEdgeConfigContent = await iotedgeCTL.GenerateManifestConfigContent(iotEdgeTemplateJSON, mdprInstances, _log); string responseMessage; if (iotEdgeConfigContent == null) { responseMessage = $"Error Generating ConfigurationContent for {deviceid} - {iotedgeCTL.GetErrMsg()}"; return(new BadRequestObjectResult(responseMessage)); } var bRet = await iotedgeCTL.ApplyManifestConfigContent(deviceid, iotEdgeConfigContent, _log); if (bRet) { responseMessage = $"Hello, Caller. This HTTP triggered function executed successfully for {deviceid}"; return(new OkObjectResult(responseMessage)); } else { responseMessage = $"Error Applying ConfigurationContent for {deviceid} - {iotedgeCTL.GetErrMsg()}"; return(new BadRequestObjectResult(responseMessage)); } }