示例#1
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);
        }
示例#2
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()));
            }
        }
示例#3
0
        private async Task <DeviceClient> GetDeviceClient(string deviceId)
        {
            DeviceClient deviceClient;

            if (!deviceClients.TryGetValue(deviceId, out deviceClient))
            {
                Microsoft.Azure.Devices.Device azureDevice = await registryManager.GetDeviceAsync(deviceId);

                if (azureDevice != null)
                {
                    deviceClient = DeviceClient.Create(
                        iotHubUri, AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(
                            deviceId, azureDevice.Authentication.SymmetricKey.PrimaryKey), TransportType.Amqp);
                    deviceClients[deviceId] = deviceClient;
                }
            }

            return(deviceClient);
        }
示例#4
0
        private async Task <List <TDevice> > LoadIoTHubDevicesAsync()
        {
            List <TDevice> resultSet = new List <TDevice>();

            devices.Clear();
            string devIdQuery = "SELECT deviceId FROM devices";
            var    query      = registryManager.CreateQuery(devIdQuery);

            while (query.HasMoreResults)
            {
                var page = await query.GetNextAsJsonAsync();

                foreach (var twin in page)
                {
                    var jdevice        = Newtonsoft.Json.JsonConvert.DeserializeObject(twin) as Newtonsoft.Json.Linq.JObject;
                    var deviceId       = jdevice.Value <string>("DeviceId");
                    var registedDevice = await registryManager.GetDeviceAsync(deviceId);

                    var registedDeviceTwin = await registryManager.GetTwinAsync(deviceId);

                    var device = new TDevice()
                    {
                        Id = registedDevice.Id
                    };
                    device.SetDesiredProperties(registedDeviceTwin.Properties.Desired.ToJson());

                    // Set Reported Properties.
                    var rpJSON = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(registedDeviceTwin.Properties.Reported.ToJson(Newtonsoft.Json.Formatting.None));
                    rpJSON.Remove("$metadata");
                    rpJSON.Remove("$version");
                    device.Reported = Newtonsoft.Json.JsonConvert.SerializeObject(rpJSON);

                    devices.Add(new IoTDeviceEntry <TDevice>()
                    {
                        Device = device,
                        State  = EntityState.Unchanged
                    });
                    resultSet.Add(device);
                }
            }

            return(resultSet);
        }
示例#5
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();
            }
        }