示例#1
0
        public async Task DeviceRegistryAsync()
        {
            registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(Store.Instance.IotHubRegistryConnectionString);
            device          = await registryManager.GetDeviceAsync(GetDeviceID());

            if (device == null)
            {
                device = await registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(GetDeviceID()));
            }
        }
示例#2
0
        public async Task <int> SaveChangesAsync()
        {
            int    modified = 0;
            string twinJson = "";

            foreach (var modifiedDevice in modelDevices.modifiedDevices)
            {
                if (modifiedDevice.State == EntityState.Added || modifiedDevice.State == EntityState.Modified)
                {
                    twinJson = "{\"properties\":{\"desired\":" + modifiedDevice.Device.DesiredPropertiesToJson() + "}}";
                    var test = Newtonsoft.Json.JsonConvert.DeserializeObject(twinJson);
                }
                switch (modifiedDevice.State)
                {
                case EntityState.Added:
                    var newDevice = new Microsoft.Azure.Devices.Device(modifiedDevice.Device.Id);
                    newDevice = await registryManager.AddDeviceAsync(newDevice);

                    var twin = await registryManager.GetTwinAsync(newDevice.Id);

                    await registryManager.UpdateTwinAsync(newDevice.Id, twinJson, twin.ETag);

                    modified++;
                    break;

                case EntityState.Modified:
                    var managedDevice = await registryManager.GetDeviceAsync(modifiedDevice.Device.Id);

                    var manageDeviceTwin = await registryManager.GetTwinAsync(modifiedDevice.Device.Id);

                    string etag = manageDeviceTwin.ETag;
                    await registryManager.UpdateTwinAsync(modifiedDevice.Device.Id, twinJson, etag);

                    modified++;
                    break;

                case EntityState.Deleted:
                    var registered = await registryManager.GetDeviceAsync(modifiedDevice.Device.Id);

                    await registryManager.RemoveDeviceAsync(registered);

                    modified++;
                    break;
                }
            }
            modelDevices.modifiedDevices.Clear();

            return(modified);
        }
示例#3
0
        public async Task StartAsync(CancellationToken ct)
        {
            // TODO: You cannot install certificate on Windows by script - we need to implement certificate verification callback handler.
            IEnumerable <X509Certificate2> certs = await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(this.workloadUri), this.apiVersion, this.workloadClientApiVersion, this.moduleId, this.moduleGenerationId);

            ITransportSettings transportSettings = ((Protocol)Enum.Parse(typeof(Protocol), this.transportType.ToString())).ToTransportSettings();

            OsPlatform.Current.InstallCaCertificates(certs, transportSettings);
            Microsoft.Azure.Devices.RegistryManager registryManager = null;
            try
            {
                registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(this.iotHubConnectionString);
                Microsoft.Azure.Devices.Device device = await registryManager.AddDeviceAsync(new Microsoft.Azure.Devices.Device(this.deviceId), ct);

                string deviceConnectionString = $"HostName={this.iotHubHostName};DeviceId={this.deviceId};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey};GatewayHostName={this.gatewayHostName}";
                this.deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, new ITransportSettings[] { transportSettings });
                await this.deviceClient.OpenAsync();

                while (!ct.IsCancellationRequested)
                {
                    this.logger.LogInformation("Ready to receive message");
                    try
                    {
                        Message message = await this.deviceClient.ReceiveAsync();

                        this.logger.LogInformation($"Message received. " +
                                                   $"Sequence Number: {message.Properties[TestConstants.Message.SequenceNumberPropertyName]}, " +
                                                   $"batchId: {message.Properties[TestConstants.Message.BatchIdPropertyName]}, " +
                                                   $"trackingId: {message.Properties[TestConstants.Message.TrackingIdPropertyName]}.");
                        await this.ReportTestResult(message);

                        await this.deviceClient.CompleteAsync(message);
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, "Error occurred while receiving message.");
                    }
                }
            }
            finally
            {
                registryManager?.Dispose();
            }
        }
示例#4
0
        public async Task StartAsync(CancellationToken ct)
        {
            // TODO: You cannot install certificate on Windows by script - we need to implement certificate verification callback handler.
            IEnumerable <X509Certificate2> certs = await CertificateHelper.GetTrustBundleFromEdgelet(new Uri(this.workloadUri), this.apiVersion, this.workloadClientApiVersion, this.moduleId, this.moduleGenerationId);

            ITransportSettings transportSettings = ((Protocol)Enum.Parse(typeof(Protocol), this.transportType.ToString())).ToTransportSettings();

            OsPlatform.Current.InstallCaCertificates(certs, transportSettings);
            Microsoft.Azure.Devices.RegistryManager registryManager = null;

            try
            {
                registryManager = Microsoft.Azure.Devices.RegistryManager.CreateFromConnectionString(this.iotHubConnectionString);
                var edgeDevice = await registryManager.GetDeviceAsync(this.edgeDeviceId);

                var leafDevice = new Microsoft.Azure.Devices.Device(this.deviceId);
                leafDevice.Scope = edgeDevice.Scope;
                Microsoft.Azure.Devices.Device device = await registryManager.AddDeviceAsync(leafDevice, ct);

                string deviceConnectionString = $"HostName={this.iotHubHostName};DeviceId={this.deviceId};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey};GatewayHostName={this.gatewayHostName}";
                this.deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, new ITransportSettings[] { transportSettings });

                var retryStrategy = new Incremental(15, RetryStrategy.DefaultRetryInterval, RetryStrategy.DefaultRetryIncrement);
                var retryPolicy   = new RetryPolicy(new FailingConnectionErrorDetectionStrategy(), retryStrategy);
                await retryPolicy.ExecuteAsync(
                    async() =>
                {
                    await this.deviceClient.OpenAsync(ct);
                }, ct);

                while (!ct.IsCancellationRequested)
                {
                    this.logger.LogInformation("Ready to receive message");
                    try
                    {
                        Message message = await this.deviceClient.ReceiveAsync();

                        if (message == null)
                        {
                            this.logger.LogWarning("Received message is null");
                            continue;
                        }

                        if (!message.Properties.ContainsKey(TestConstants.Message.SequenceNumberPropertyName) ||
                            !message.Properties.ContainsKey(TestConstants.Message.BatchIdPropertyName) ||
                            !message.Properties.ContainsKey(TestConstants.Message.TrackingIdPropertyName))
                        {
                            string messageBody  = new StreamReader(message.BodyStream).ReadToEnd();
                            string propertyKeys = string.Join(",", message.Properties.Keys);
                            this.logger.LogWarning($"Received message doesn't contain required key. property keys: {propertyKeys}, message body: {messageBody}, lock token: {message.LockToken}.");
                            continue;
                        }

                        this.logger.LogInformation($"Message received. " +
                                                   $"Sequence Number: {message.Properties[TestConstants.Message.SequenceNumberPropertyName]}, " +
                                                   $"batchId: {message.Properties[TestConstants.Message.BatchIdPropertyName]}, " +
                                                   $"trackingId: {message.Properties[TestConstants.Message.TrackingIdPropertyName]}, " +
                                                   $"LockToken: {message.LockToken}.");
                        await this.ReportTestResult(message);

                        await this.deviceClient.CompleteAsync(message);
                    }
                    catch (Exception ex)
                    {
                        this.logger.LogError(ex, "Error occurred while receiving message.");
                    }
                }
            }
            finally
            {
                registryManager?.Dispose();
            }
        }