public async Task <Token> Get(string deviceId)
        {
            // Device Id - IoTHub Connection Information
            // string deviceId = "<<Replace with ID of your Device. - E.g.: Device01;>>";
            string ioTHubConnectionString = Environment.GetEnvironmentVariable("AZURE_IOT_HUB_OWNER_KEY"); // "<<Replace with IoT Hub Connection String from Azure Portal - E.g.:HostName=robertsiothub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=BZ1...Q=";
            string ioTHubName             = ioTHubConnectionString.ParseConnectionString()["HostName"];    //"<<Replace with Name of your IoT Hub instance>>.azure-devices.net - E.g.: robertsiothub.azure-devices.net";

            //Get Device Symmetric Key
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(ioTHubConnectionString);

            Device device;

            try
            {
                device = await registryManager.AddDeviceAsync(new Device(id : deviceId));
            }
            catch (DeviceAlreadyExistsException)
            {
                device = await registryManager.GetDeviceAsync(deviceId : deviceId);
            }

            string deviceSymmetricKey = device.Authentication.SymmetricKey.PrimaryKey;

            //Create Token with fixed Endtime - 31st of this year
            DateTime _epochTime       = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
            DateTime endLiveTime      = new DateTime(DateTime.UtcNow.Year, 12, 31);
            TimeSpan secondsEpochTime = endLiveTime.Subtract(_epochTime);

            var sas = MyExtensions.GetSASTokenPCL(
                hubHostname: ioTHubName,
                deviceId: deviceId,
                deviceKey: Convert.FromBase64String(deviceSymmetricKey),
                duration: secondsEpochTime);

            return(new Token {
                Hostname = ioTHubName, SAS = sas
            });
        }
示例#2
0
        async Task SendLargeMessageHandleExceptionTest(ITransportSettings[] transportSettings)
        {
            TestModule sender = null;

            string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey");

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString);

            try
            {
                sender = await TestModule.CreateAndConnect(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "sender1", transportSettings);

                Exception ex = null;
                try
                {
                    // create a large message
                    var message = new Message(new byte[400 * 1000]);
                    await sender.SendMessageAsync("output1", message);
                }
                catch (Exception e)
                {
                    ex = e;
                }

                Assert.NotNull(ex);
            }
            finally
            {
                if (rm != null)
                {
                    await rm.CloseAsync();
                }
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
示例#3
0
        public static async Task RegisterNewDevice()
        {
            var    deviceId = "1001";
            Device device;

            try
            {
                _registryManager = RegistryManager.CreateFromConnectionString(ConnectionString);
                device           = await _registryManager.AddDeviceAsync(new Device(deviceId));

                System.Console.WriteLine(device.Authentication.SymmetricKey.PrimaryKey);
            }
            catch (DeviceAlreadyExistsException)
            {
                device = await _registryManager.GetDeviceAsync(deviceId);

                System.Console.WriteLine(device.Authentication.SymmetricKey.PrimaryKey);
            }
            catch (Exception exception)
            {
                System.Console.WriteLine(exception.Message);
            }
        }
示例#4
0
        public async System.Threading.Tasks.Task <string> DeleteIoTHubDeviceAsync(string connectionString, string iotHubType)
        {
            RegistryManager registryManager;

            try
            {
                registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            }
            catch (Exception ex)
            {
                return("\t【DELETE】Cann't connect " + iotHubType + " IoTHub: " + Program.GetNonJsonExceptionMessage(ex.Message) + "\n");
            }

            try
            {
                await registryManager.RemoveDeviceAsync(_IoTHubDeviceId);
            }
            catch (Exception ex)
            {
                return("\t【DELETE】Cann't delete IoTDevice(" + iotHubType + " IoTHub, IoTDeviceId: " + this._IoTHubDeviceId + "): " + Program.GetNonJsonExceptionMessage(ex.Message) + "\n");
            }
            return("");
        }
示例#5
0
        //  Ensure device exists in IoT Hub, if not exist, create one.
        //  Returns Device reference
        private static async Task <Device> EnsureDeviceAsync(string deviceId)
        {
            var    connectionString = _appSettings.IoTHubOwnerConnectionString;
            var    registryManager  = RegistryManager.CreateFromConnectionString(connectionString);
            Device device;

            try
            {
                device = await registryManager.GetDeviceAsync(deviceId);

                if (device == null)
                {
                    device = await registryManager.AddDeviceAsync(new Device(deviceId));
                }
            }
            catch (DeviceAlreadyExistsException)
            {
                device = await registryManager.GetDeviceAsync(deviceId);

                Logger.Error($"device id {deviceId} : {device.Authentication.SymmetricKey.SecondaryKey}");
            }
            return(device);
        }
        private async Task AddDevices_Async()
        {
            // connect to IoT Hub device identity registry
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

            for (int i = 0; i < numberOfDevices; i++)
            {
                try
                {
                    string deviceID = prefixDevice + i;
                    await registryManager.AddDeviceAsync(new Device(deviceID));

                    // Output for console
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"Device added {deviceID}");
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(ex.Message);
                }
            }
        }
示例#7
0
        public async Task <HttpResponseMessage> RegisterDevices([FromBody] IoTHubRegisterWrapper input,
                                                                [Metadata(null, null, VisibilityType.Internal)] bool enable = false)
        {
            try
            {
                RegistryManager registryManager = RegistryManager.CreateFromConnectionString(input.ConnectionString);

                List <string> deviceIds = input.DeviceIds.Split(',').Select(x => x.Trim()).ToList();

                IEnumerable <DeviceRegistryOperationError> errors = await RegisterDevices(registryManager, deviceIds, enable);

                return(Request.CreateResponse(HttpStatusCode.Created, errors));
            }
            // TODO: Move exception handling for all these apis to a common method.
            catch (NullReferenceException ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, @"The input Received by the API was null. This sometimes happens if the message in the Logic App is malformed. Check the message to make sure there are no escape characters like '\'.", ex));
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex));
            }
        }
        private async Task Twin_DeviceSetsReportedPropertyAndServiceReceivesIt(Client.TransportType transport)
        {
            var propName  = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
                {
                    var patch = new TwinCollection();
                    patch[propName] = propValue;
                    await deviceClient.UpdateReportedPropertiesAsync(patch).ConfigureAwait(false);

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

                    var serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);

                    Assert.AreEqual <string>(serviceTwin.Properties.Reported[propName].ToString(), propValue);

                    _log.WriteLine("verified " + serviceTwin.Properties.Reported[propName].ToString() + "=" + propValue);
                }
        }
示例#9
0
        static void Main(string[] args)
        {
            registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            AddDeviceAsync().Wait();

            deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("miiotdevice", deviceKey));

            SerialPort serialPort = new SerialPort("COM4");

            serialPort.BaudRate  = 9600;
            serialPort.Parity    = Parity.None;
            serialPort.StopBits  = StopBits.One;
            serialPort.DataBits  = 8;
            serialPort.Handshake = Handshake.None;

            serialPort.DataReceived += SerialPort_DataReceived;

            serialPort.Open();

            Console.WriteLine("Press Any Key to terminate");
            Console.ReadKey();
            serialPort.Close();
        }
        private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGet(Client.TransportType transport)
        {
            var propName  = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
                using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
                {
                    var twinPatch = new Twin();
                    twinPatch.Properties.Desired[propName] = propValue;
                    await registryManager.UpdateTwinAsync(testDevice.Id, twinPatch, "*").ConfigureAwait(false);

                    var deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false);

                    Assert.AreEqual <string>(deviceTwin.Properties.Desired[propName].ToString(), propValue);

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

                    await registryManager.CloseAsync().ConfigureAwait(false);
                }
        }
        public PatrolCar(string serviceBusConnectionString, string topicName, string subscriptionName, string connectionString, string iotHubUri, int carNum, string carName, double carLatPosition,
                         double carLongPosition, double milesPerDegreeLat, double milesPerDegreeLong, int locationReportingInterval)
        {
            this.subscriptionClient = SubscriptionClient.CreateFromConnectionString(serviceBusConnectionString, topicName, subscriptionName);
            //this.subscriptionClient.AddRule("PatrolCarIDRule", new SqlFilter($"CarID = {this.carName}")); // ASA Does not yet support message properties, so cannot apply filters to Topics!
            Microsoft.ServiceBus.ServiceBusEnvironment.SystemConnectivity.Mode = Microsoft.ServiceBus.ConnectivityMode.Http;
            this.subscriptionClient.OnMessage(message => chaseCar(message));
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(connectionString);

            this.deviceClient              = this.GetOrCreateDevice(registryManager, iotHubUri, carName).Result;
            this.carNum                    = carNum;
            this.carName                   = carName;
            this.carLatPosition            = carLatPosition;
            this.carLongPosition           = carLongPosition;
            this.milesPerDegreeLat         = milesPerDegreeLat;
            this.milesPerDegreeLong        = milesPerDegreeLong;
            this.locationReportingInterval = locationReportingInterval;
            this.speed = 0;
            this.previousDirectionFactorLat  = 0;
            this.previousDirectionFactorLong = 0;
            this.chasing           = false;
            this.targetCoordinates = null;
        }
示例#12
0
        /// <summary>
        /// Factory method.
        /// </summary>
        /// <param name="namePrefix"></param>
        /// <param name="type"></param>
        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();

            using (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);
            }
        }
示例#13
0
        static async Task Main(string[] args)
        {
            var serviceConnectionString = "HostName=lrac-demo-hub.azure-devices.net;SharedAccessKeyName=service;SharedAccessKey=BkNHrdM+H5c8v5BRm0uWxnFH32dk+yO1syccKHXtT2w=";


            var serviceClient   = ServiceClient.CreateFromConnectionString(serviceConnectionString);
            var registryManager = RegistryManager.CreateFromConnectionString(serviceConnectionString);



            ReveiveFeedback(serviceClient);

            while (true)
            {
                Console.WriteLine("Which device do you wish to send a message to? ");
                Console.Write("> ");
                var deviceId = Console.ReadLine();

                //await SendCloudToDeviceMessage(serviceClient, deviceId);
                //await CallDirectMethod(serviceClient, deviceId);
                await UpdateDeviceFirmware(registryManager, deviceId);
            }
        }
示例#14
0
        /// <summary>
        /// 將裝置從Azure IoT Hub上解除註冊
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnUnregistry_Click(object sender, EventArgs e)
        {
            string strDeviceId = txtDeviceId.Text;
            // 先從Azure IoT Hub上取得裝置是不是已經存在
            Device          objDevice       = null;
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(strIoTHubConnectionString);

            objDevice = await registryManager.GetDeviceAsync(strDeviceId);

            // 如果裝置已經存在,就解除註冊
            if (objDevice != null)
            {
                await registryManager.RemoveDeviceAsync(objDevice);

                txtDeviceKey.Text = "";
                deviceClient      = null;
                MessageBox.Show("該裝置已解除註冊");
            }
            else
            {
                MessageBox.Show("該裝置不存在於Azure IoT Hub之中");
            }
        }
示例#15
0
        /// <summary>
        /// get a list of iot devices
        /// </summary>
        /// <param name="subId"></param>
        /// <param name="group"></param>
        /// <param name="hubname"></param>
        /// <param name="policy"></param>
        /// <returns></returns>
        public static async Task <ICollection <string> > GetIoTDevices(string subId, string group, string hubname, string policy)
        {
            List <string> devices = new List <string>();

            try
            {
                string key = await GetPrimaryKey(subId, group, hubname, policy);

                if (key != null)
                {
                    var connectionString = "HostName=" + hubname + ".azure-devices.net;SharedAccessKeyName=" + policy + ";SharedAccessKey=" + key;
                    var registryManager  = RegistryManager.CreateFromConnectionString(connectionString);
                    var devs             = await registryManager.GetDevicesAsync(1000);

                    devices.AddRange(devs.Select(_ => _.Id));
                }
            } catch (System.Exception e)
            {
                Debug.WriteLine(e);
            }

            return(devices);
        }
示例#16
0
        static async Task <IList <string> > CreateDevices(string connectionString, int devicesCount = 10)
        {
            var list = new List <string>();

            var registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            var devices         = new List <Device>();

            for (int i = 0; i < devicesCount; ++i)
            {
                var deviceId = $"device{i.ToString("000")}";
                devices.Add(new Device(deviceId));
                list.Add(deviceId);
            }

            var result = await registryManager.AddDevices2Async(devices);

            if (!result.IsSuccessful)
            {
                return(new string[0]);
            }

            return(list);
        }
        // This function will get triggered/executed when a new message is written
        // on an Azure Queue called queue.
        public static void ProcessQueueMessage([ServiceBusTrigger("c2dalarm")] BrokeredMessage message, TextWriter log)
        {
            var     text        = GetMessagePayload(message);
            dynamic obj         = JsonConvert.DeserializeObject(text);
            var     registryMgr = RegistryManager.CreateFromConnectionString(ConfigurationManager.AppSettings["iotHubConnectionString"]);

            try
            {
                var           device           = registryMgr.GetDeviceAsync((string)obj.DeviceId).GetAwaiter().GetResult();
                var           deviceConnString = $"HostName={ConfigurationManager.AppSettings["iotHubUri"]};DeviceId={device.Id};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}";
                var           dc = DeviceClient.CreateFromConnectionString(deviceConnString);
                ServiceClient sc = ServiceClient.CreateFromConnectionString(ConfigurationManager.AppSettings["iotHubConnectionString"]);
                sc.SendAsync(device.Id,
                             new Microsoft.Azure.Devices.Message(Encoding.UTF8.GetBytes($"Command:{text}"))).Wait();
                sc.CloseAsync().Wait();

                message.Complete();
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine($"Exception:{exp.Message}");
            }
        }
示例#18
0
        public static async void Run([TimerTrigger("0/13 * * * * *")] TimerInfo myTimer, ILogger log)
        {
            try
            {
                RegistryManager manager = RegistryManager.CreateFromConnectionString(Environment.GetEnvironmentVariable("IOTHubMainConnectionstring"));
                var             twin    = await manager.GetTwinAsync("testpi");

                if (twin.ConnectionState.ToString() == "Connected")
                {
                    log.LogInformation("fired");
                    ServiceClient sCli;
                    string        iotconstr = Environment.GetEnvironmentVariable("IOTHubMainConnectionstring");
                    sCli = ServiceClient.CreateFromConnectionString(iotconstr);
                    string device  = "testpi";
                    var    message = new Message(Encoding.ASCII.GetBytes("keep alive"));
                    await sCli.SendAsync(device, message);
                }
            }
            catch (Exception ex)
            {
                log.LogError(ex + "        --------> keep alive");
            }
        }
示例#19
0
        public override void ExecuteCmdlet()
        {
            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);

            Twin deviceTwin = registryManager.GetTwinAsync(this.DeviceId).GetAwaiter().GetResult();

            if (deviceTwin == null)
            {
                throw new ArgumentException($"The entered non-edge device \"{this.DeviceId}\" doesn't exist.");
            }

            IotHubDataPlaneUtils.ValidateDeviceTracing(this.DeviceId, iotHubDescription.Sku.Tier.Value.ToString(), iotHubDescription.Location, deviceTwin.Capabilities.IotEdge);

            this.WriteObject(IotHubDataPlaneUtils.GetDeviceTracing(this.DeviceId, deviceTwin));
        }
示例#20
0
        public async void Receive_C2D_NotSubscribed_OfflineSingleMessage_ShouldThrow()
        {
            // Arrange
            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

            (string deviceName, string deviceConnectionString) = await RegistryManagerHelper.CreateDevice(DeviceNamePrefix, iotHubConnectionString, rm);

            ServiceClient serviceClient = null;
            DeviceClient  deviceClient  = null;

            try
            {
                serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
                await serviceClient.OpenAsync();

                // Act
                // Send message before device is listening
                Message message = this.CreateMessage(out string payload);
                await serviceClient.SendAsync(deviceName, message);

                // Wait to make sure message is not received because of ClockSkewAdjustment
                await Task.Delay(ClockSkewAdjustment);

                ITransportSettings[] settings = this.GetTransportSettings();
                deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings);
                await deviceClient.OpenAsync();

                // Assert
                await Assert.ThrowsAsync <TimeoutException>(() => this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]));
            }
            finally
            {
                await this.Cleanup(deviceClient, serviceClient, rm, deviceName);
            }
        }
示例#21
0
        /// Get the list of devices registered to the IoT Hub
        ///   and export it to a blob as deserialized objects.
        public async Task ExportDevices(string containerURI, string hubConnectionString)
        {
            try
            {
                // Create an instance of the registry manager class.
                RegistryManager registryManager =
                    RegistryManager.CreateFromConnectionString(hubConnectionString);

                // Call an export job on the IoT Hub to retrieve all devices.
                // This writes them to devices.txt in the container.
                // The second parameter indicates whether to export the keys or not.
                JobProperties exportJob = await
                                          registryManager.ExportDevicesAsync(containerURI, false).ConfigureAwait(false);

                // Poll every 5 seconds to see if the job has finished executing.
                while (true)
                {
                    exportJob = await registryManager.GetJobAsync(exportJob.JobId).ConfigureAwait(false);

                    if (exportJob.Status == JobStatus.Completed ||
                        exportJob.Status == JobStatus.Failed ||
                        exportJob.Status == JobStatus.Cancelled)
                    {
                        // Job has finished executing
                        break;
                    }

                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                }
            }
            catch (Exception ex)
            {
                Debug.Print("Error exporting devices to blob storage. Description = {0}", ex.Message);
            }

            // Note: could add twin data here if you want to export it.
        }
示例#22
0
        private async Task Twin_ClientHandlesRejectionInvalidPropertyName(Client.TransportType transport)
        {
            var propName1 = "$" + Guid.NewGuid().ToString();
            var propName2 = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);
            
            using (var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
            {
                var exceptionThrown = false;
                try
                {
                    await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection
                    {
                        [propName1] = 123,
                        [propName2] = "abcd"
                    }).ConfigureAwait(false);
                }
                catch (Exception)
                {
                    exceptionThrown = true;
                }

                if (!exceptionThrown)
                {
                    throw new AssertFailedException("Exception was expected, but not thrown.");
                }

                var serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);
                Assert.IsFalse(serviceTwin.Properties.Reported.Contains(propName1));

                await deviceClient.CloseAsync().ConfigureAwait(false);
            }

            await registryManager.CloseAsync().ConfigureAwait(false);
        }
示例#23
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("Get Inactive Device function called");

            // parse query parameter
            string minutesValue = req.GetQueryNameValuePairs()
                                  .FirstOrDefault(q => string.Compare(q.Key, "minutes", true) == 0)
                                  .Value;

            double minutes;

            if (double.TryParse(minutesValue, out minutes))
            {
                var timeWindow = DateTime.Now.AddMinutes(-minutes);

                registryManager = RegistryManager.CreateFromConnectionString(System.Environment.GetEnvironmentVariable("IOT_HUB_OWNER_CONNECTION_STRING"));

                //Currently IoTHub allows only to get 1000 devices. There is no way currently to send a query for the device identity. Would be nice to have the lastactivitytime on the device twins
                var devices = await registryManager.GetDevicesAsync(int.MaxValue);

                var inactiveDevices = devices.Where(d => d.LastActivityTime < timeWindow).Select(d => new
                {
                    deviceId                  = d.Id,
                    status                    = d.Status,
                    statusUpdatedTime         = d.StatusUpdatedTime,
                    lastActivityTime          = d.LastActivityTime,
                    cloudToDeviceMessageCount = d.CloudToDeviceMessageCount
                });


                return(req.CreateResponse(HttpStatusCode.OK, inactiveDevices));
            }
            else
            {
                return(req.CreateResponse(HttpStatusCode.BadRequest));
            }
        }
示例#24
0
        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);
            }
        }
示例#25
0
        public static void Main(string[] args)
        {
            const string configFilePath   = @"../../../config/config.yaml";
            var          config           = configFilePath.GetIoTConfiguration();
            var          testDevice       = config.DeviceConfigs.First();
            var          azureConfig      = config.AzureIoTHubConfig;
            var          serviceBusConfig = config.AzureServiceBusConfig;

            var cts             = new CancellationTokenSource();
            var registryManager = RegistryManager.CreateFromConnectionString(azureConfig.ConnectionString);

            CriticalNotificationMonitor(serviceBusConfig, azureConfig.ConnectionString, testDevice.DeviceId, cts.Token);

            var consoleReadTask = Task.Run(async() => {
                while (true)
                {
                    Console.WriteLine("Enter a value to set device reporting frequency (in MS) or `exit` to terminate: ");

                    var userInput = Console.ReadLine();
                    var newMessageSendDelayValue = userInput.IsNullOrWhiteSpace() ? "" : userInput?.ToLowerInvariant();
                    switch (newMessageSendDelayValue)
                    {
                    // Allow the user to exit the application gracefully
                    case "exit":
                        cts.Cancel();
                        return;

                    // Take all other user input and forward as change request to device
                    default:
                        await SendDesiredConfiguration(registryManager, testDevice.DeviceId, cts.Token, newMessageSendDelayValue);
                        break;
                    }
                }
            }, cts.Token);

            Task.WaitAll(consoleReadTask);
        }
        /// <summary>
        /// Create numberOfDevices devices linked to the iot hub
        /// </summary>
        /// <param name="numberOfDevices">the number of devices to create</param>
        public static void CreateDevice(int numberOfDevices)
        {
            const string configFilePath = @"../../config.yaml";

            IoTHubExamples.Core.Configuration config = configFilePath.GetIoTConfiguration();
            deviceConfigs = config.DeviceConfigs;
            AzureIoTHubConfig azureConfig = config.AzureIoTHubConfig;

            _registryManager = RegistryManager.CreateFromConnectionString(azureConfig.ConnectionString);

            deviceConfigs = config.DeviceConfigs = new System.Collections.Generic.List <DeviceConfig>();

            for (int deviceNumber = 0; deviceNumber < numberOfDevices; deviceNumber++)
            {
                var testDevice = new DeviceConfig()
                {
                    DeviceId = $"{"test"}{deviceNumber:0000}",
                    Nickname = $"{"test"}{deviceNumber:0000}",
                    Status   = "Enabled"
                };
                deviceConfigs.Add(testDevice);

                Task <string> task = AddDeviceAsync(testDevice);
                task.Wait();

                testDevice.Key = task.Result;
            }

            if (configFilePath.UpdateIoTConfiguration(config).Item1)
            {
                foreach (var testDevice in deviceConfigs)
                {
                    Console.WriteLine(
                        $"DeviceId: {testDevice.DeviceId} has DeviceKey: {testDevice.Key} \r\nConfig file: {configFilePath} has been updated accordingly.");
                }
            }
        }
        private static async Task CreateDeviceAsync(TestDeviceType type, string prefix)
        {
            string deviceName = prefix + Guid.NewGuid();

            s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Device with prefix {prefix} not found.");

            // Delete existing devices named this way and create a new one.
            using (RegistryManager rm = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
            {
                s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Creating device {deviceName} with type {type}.");

                Client.IAuthenticationMethod auth = null;

                Device requestDevice = new Device(deviceName);
                if (type == TestDeviceType.X509)
                {
                    requestDevice.Authentication = new AuthenticationMechanism()
                    {
                        X509Thumbprint = new X509Thumbprint()
                        {
                            PrimaryThumbprint = Configuration.IoTHub.GetCertificateWithPrivateKey().Thumbprint
                        }
                    };

                    auth = new DeviceAuthenticationWithX509Certificate(deviceName, Configuration.IoTHub.GetCertificateWithPrivateKey());
                }

                Device device = await rm.AddDeviceAsync(requestDevice).ConfigureAwait(false);

                s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Pausing for {DelayAfterDeviceCreationSeconds}s after device was created.");
                await Task.Delay(DelayAfterDeviceCreationSeconds * 1000).ConfigureAwait(false);

                s_deviceCache[prefix] = new TestDevice(device, auth);

                await rm.CloseAsync().ConfigureAwait(false);
            }
        }
        public async Task RegistryManager_QueryDevicesInvalidServiceCertificateHttp_Fails()
        {
            var    rm        = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionStringInvalidServiceCertificate);
            IQuery query     = rm.CreateQuery("select * from devices");
            var    exception = await Assert.ThrowsExceptionAsync <IotHubCommunicationException>(
                () => query.GetNextAsTwinAsync()).ConfigureAwait(false);

#if NET451 || NET47
            Assert.IsInstanceOfType(exception.InnerException.InnerException.InnerException, typeof(AuthenticationException));
#elif NETCOREAPP2_0
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // WinHttpException (0x80072F8F): A security error occurred
                Assert.AreEqual(unchecked ((int)0x80072F8F), exception.InnerException.InnerException.HResult);
            }
            else
            {
                // CURLE_SSL_CACERT (60): Peer certificate cannot be authenticated with known CA certificates.
                Assert.AreEqual(60, exception.InnerException.InnerException.HResult);
            }
#else
            Assert.IsInstanceOfType(exception.InnerException.InnerException, typeof(AuthenticationException));
#endif
        }
示例#29
0
        static async Task UpdateDeploymentEnvironmentVariablesAsync(TestResultReportingClient apiClient, CancellationTokenSource cts)
        {
            RegistryManager registryManager = null;

            try
            {
                registryManager = RegistryManager.CreateFromConnectionString(Settings.Current.IoTHubConnectionString.OrDefault());

                DateTime testStartAt = DateTime.UtcNow;
                long     count       = 1;
                var      envVars     = new Dictionary <string, string>();

                while (!cts.IsCancellationRequested && DateTime.UtcNow - testStartAt < Settings.Current.TestDuration)
                {
                    JObject deploymentJson = await GetEdgeAgentDeploymentManifestJsonAsync(registryManager, Settings.Current.DeviceId);

                    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();
            }
        }
示例#30
0
        public async Task <DeviceData> GetDeviceData(string deviceId)
        {
            DeviceData result = new DeviceData();

            dynamic registryManager = RegistryManager.CreateFromConnectionString(_iotHubConnectionString);

            try
            {
                var deviceTwin = await registryManager.GetTwinAsync(deviceId);

                if (deviceTwin != null)
                {
                    result.deviceJson             = deviceTwin.ToJson();
                    result.tagsJson               = deviceTwin.Tags.ToJson();
                    result.reportedPropertiesJson = deviceTwin.Properties.Reported.ToJson();
                    result.desiredPropertiesJson  = deviceTwin.Properties.Desired.ToJson();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + Environment.NewLine + "Make sure you are using the latest Microsoft.Azure.Devices package.", "Device Twin Properties");
            }
            return(result);
        }