private async Task <Module> AddModuleToDeviceAsync(string deviceId, string moduleId)
        {
            if (string.IsNullOrEmpty(deviceId))
            {
                throw new ArgumentNullException(nameof(deviceId));
            }

            if (string.IsNullOrEmpty(moduleId))
            {
                throw new ArgumentNullException(nameof(moduleId));
            }

            Module module;

            try
            {
                module = await _registryManager.AddModuleAsync(new Module(deviceId, moduleId));
            }
            catch (ModuleAlreadyExistsException ex)
            {
                _logger.LogWarning(ex, ex.Message);
                module = await _registryManager.GetModuleAsync(deviceId, moduleId);
            }

            return(module);
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.ModuleId, Properties.Resources.AddIotHubModule))
            {
                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);

                PSAuthenticationMechanism auth = new PSAuthenticationMechanism();
                PSModule module = new PSModule();
                module.Id       = this.ModuleId;
                module.DeviceId = this.DeviceId;
                switch (this.AuthMethod)
                {
                case PSDeviceAuthType.x509_thumbprint:
                    auth.Type           = PSAuthenticationType.SelfSigned;
                    auth.X509Thumbprint = new PSX509Thumbprint();
                    auth.X509Thumbprint.PrimaryThumbprint   = this.authTypeDynamicParameter.PrimaryThumbprint;
                    auth.X509Thumbprint.SecondaryThumbprint = this.authTypeDynamicParameter.SecondaryThumbprint;
                    break;

                case PSDeviceAuthType.x509_ca:
                    auth.Type = PSAuthenticationType.CertificateAuthority;
                    break;

                default:
                    auth.SymmetricKey = new PSSymmetricKey();
                    auth.Type         = PSAuthenticationType.Sas;
                    break;
                }
                module.Authentication = auth;

                RegistryManager registryManager = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);
                this.WriteObject(IotHubDataPlaneUtils.ToPSModule(registryManager.AddModuleAsync(IotHubDataPlaneUtils.ToModule(module)).GetAwaiter().GetResult()));
            }
        }
        public static async Task <string> GetOrCreateModule(RegistryManager registryManager, string hostName, string deviceId, string moduleId)
        {
            Module module = await registryManager.GetModuleAsync(deviceId, moduleId);

            if (module == null)
            {
                module = await registryManager.AddModuleAsync(new Module(deviceId, moduleId));
            }

            string gatewayHostname = ConfigHelper.TestConfig["GatewayHostname"];

            return($"HostName={hostName};DeviceId={module.DeviceId};ModuleId={module.Id};SharedAccessKey={module.Authentication.SymmetricKey.PrimaryKey};GatewayHostName={gatewayHostname}");
        }
        public static async Task <string> CreateModuleIfNotExists(RegistryManager registryManager, string hostname, string deviceId, string moduleId)
        {
            Module module = await registryManager.GetModuleAsync(deviceId, moduleId);

            if (module == null)
            {
                module = await registryManager.AddModuleAsync(new Module(deviceId, moduleId));
            }

            await Task.Delay(1000);

            string moduleConnectionString = GetModuleConnectionString(module, hostname);

            return(moduleConnectionString);
        }
Exemple #5
0
        public async Task ModulesClient_GetModulesOnDevice()
        {
            int    moduleCount  = 5;
            string testDeviceId = $"IdentityLifecycleDevice{Guid.NewGuid()}";

            string[] testModuleIds = new string[moduleCount];
            for (int i = 0; i < moduleCount; i++)
            {
                testModuleIds[i] = $"IdentityLifecycleModule{i}-{Guid.NewGuid()}";
            }

            Device          device = null;
            RegistryManager client = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            try
            {
                // Create a device to house the modules
                device = await client.AddDeviceAsync(new Device(testDeviceId)).ConfigureAwait(false);

                // Create the modules on the device
                for (int i = 0; i < moduleCount; i++)
                {
                    Module createdModule = await client.AddModuleAsync(
                        new Module(testDeviceId, testModuleIds[i])).ConfigureAwait(false);
                }

                // List the modules on the test device
                IEnumerable <Module> modulesOnDevice = await client.GetModulesOnDeviceAsync(testDeviceId).ConfigureAwait(false);

                IList <string> moduleIdsOnDevice = modulesOnDevice
                                                   .Select(module => module.Id)
                                                   .ToList();

                Assert.AreEqual(moduleCount, moduleIdsOnDevice.Count);
                for (int i = 0; i < moduleCount; i++)
                {
                    Assert.IsTrue(moduleIdsOnDevice.Contains(testModuleIds[i]));
                }
            }
            finally
            {
                await Cleanup(client, testDeviceId).ConfigureAwait(false);
            }
        }
Exemple #6
0
        public async Task ModulesClient_IdentityLifecycle()
        {
            string testDeviceId = $"IdentityLifecycleDevice{Guid.NewGuid()}";
            string testModuleId = $"IdentityLifecycleModule{Guid.NewGuid()}";

            RegistryManager client = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            try
            {
                // Create a device to house the module
                Device device = await client.AddDeviceAsync(new Device(testDeviceId)).ConfigureAwait(false);

                // Create a module on the device
                Module createdModule = await client.AddModuleAsync(
                    new Module(testDeviceId, testModuleId)).ConfigureAwait(false);

                createdModule.DeviceId.Should().Be(testDeviceId);
                createdModule.Id.Should().Be(testModuleId);

                // Get device
                // Get the device and compare ETag values (should remain unchanged);
                Module retrievedModule = await client.GetModuleAsync(testDeviceId, testModuleId).ConfigureAwait(false);

                retrievedModule.ETag.Should().BeEquivalentTo(createdModule.ETag, "ETag value should not have changed between create and get.");

                // Update a module
                string managedByValue = "SomeChangedValue";
                retrievedModule.ManagedBy = managedByValue;

                Module updatedModule = await client.UpdateModuleAsync(retrievedModule).ConfigureAwait(false);

                updatedModule.ManagedBy.Should().Be(managedByValue, "Module should have changed its managedBy value");

                // Delete the device
                // Deleting the device happens in the finally block as cleanup.
            }
            finally
            {
                await Cleanup(client, testDeviceId).ConfigureAwait(false);
            }
        }
        /// <summary>
        /// Factory method.
        /// IMPORTANT: Not thread safe!
        /// </summary>
        /// <param name="namePrefix"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static async Task <TestModule> GetTestModuleAsync(string deviceNamePrefix, string moduleNamePrefix)
        {
            var        log        = TestLogging.GetInstance();
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(deviceNamePrefix).ConfigureAwait(false);

            string deviceName = testDevice.Id;
            string moduleName = moduleNamePrefix + Guid.NewGuid();

            RegistryManager rm = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            log.WriteLine($"{nameof(GetTestModuleAsync)}: Creating module for device {deviceName}.");

            Module requestModule = new Module(deviceName, moduleName);
            Module module        = await rm.AddModuleAsync(requestModule).ConfigureAwait(false);

            await rm.CloseAsync().ConfigureAwait(false);

            TestModule ret = new TestModule(module);

            log.WriteLine($"{nameof(GetTestModuleAsync)}: Using device {ret.DeviceId} with module {ret.Id}.");
            return(ret);
        }
Exemple #8
0
        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);
        }
Exemple #9
0
        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);
        }