Example #1
0
 public DeviceTwinQueueModel(string deploymentId, TwinServiceModel deviceTwin, TwinServiceModel existingTwin, string tenantId)
 {
     this.DeploymentId       = deploymentId;
     this.DeviceTwin         = deviceTwin;
     this.ExistingDeviceTwin = existingTwin;
     this.TenantId           = tenantId;
 }
Example #2
0
        public DeviceServiceModel ToServiceModel()
        {
            var twinModel = new TwinServiceModel
                            (
                etag: this.TwinEtag,
                deviceId: this.Id,
                desiredProperties: this.Properties?.Desired,
                reportedProperties: this.Properties?.Reported,
                tags: this.Tags,
                isSimulated: this.IsSimulated
                            );

            return(new DeviceServiceModel
                   (
                       etag: this.DeviceRegistryEtag,
                       id: this.Id,
                       c2DMessageCount: this.C2DMessageCount,
                       lastActivity: this.LastActivity,
                       connected: this.Connected,
                       enabled: this.Enabled,
                       isEdgeDevice: this.IsEdgeDevice,
                       lastStatusUpdated: this.LastStatusUpdated,
                       twin: twinModel,
                       ioTHubHostName: this.IoTHubHostName,
                       authentication: this.Authentication == null ? null : this.Authentication.ToServiceModel()
                   ));
        }
Example #3
0
        private DeviceServiceModel CreateDeviceTwinServiceModel(ValueApiModel input, DeviceServiceModel data)
        {
            TwinServiceModel output = JsonConvert.DeserializeObject <TwinServiceModel>(input.Data);

            data.Twin = output;
            return(data);
        }
Example #4
0
        public async Task <JobServiceModel> ScheduleTwinUpdateAsync(
            string jobId,
            string queryCondition,
            TwinServiceModel twin,
            DateTimeOffset startTimeUtc,
            long maxExecutionTimeInSeconds)
        {
            var result = await this.tenantConnectionHelper.GetJobClient().ScheduleTwinUpdateAsync(
                jobId,
                queryCondition,
                twin.ToAzureModel(),
                startTimeUtc.DateTime,
                maxExecutionTimeInSeconds);

            // Update the deviceProperties cache, no need to wait
            var model = new DevicePropertyServiceModel();

            var tagRoot = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(twin.Tags)) as JToken;

            if (tagRoot != null)
            {
                model.Tags = new HashSet <string>(tagRoot.GetAllLeavesPath());
            }

            var reportedRoot = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(twin.ReportedProperties)) as JToken;

            if (reportedRoot != null)
            {
                model.Reported = new HashSet <string>(reportedRoot.GetAllLeavesPath());
            }

            var unused = this.deviceProperties.UpdateListAsync(model);

            return(new JobServiceModel(result));
        }
Example #5
0
 public DeviceServiceModel(
     string etag,
     string id,
     int c2DMessageCount,
     DateTime lastActivity,
     bool connected,
     bool enabled,
     bool isEdgeDevice,
     DateTime lastStatusUpdated,
     TwinServiceModel twin,
     AuthenticationMechanismServiceModel authentication,
     string ioTHubHostName)
 {
     this.Etag              = etag;
     this.Id                = id;
     this.C2DMessageCount   = c2DMessageCount;
     this.LastActivity      = lastActivity;
     this.Connected         = connected;
     this.Enabled           = enabled;
     this.IsEdgeDevice      = isEdgeDevice;
     this.LastStatusUpdated = lastStatusUpdated;
     this.Twin              = twin;
     this.IoTHubHostName    = ioTHubHostName;
     this.Authentication    = authentication;
 }
        public static async Task Run([EventHubTrigger(eventHubName: "twin-change", Connection = "TwinChangeEventHubConnectionString", ConsumerGroup = "%DeviceDeploymentHistoryConsumerGroup%")] EventData[] events, ILogger log)
        {
            bool        exceptionOccurred = false;
            List <Task> list = new List <Task>();

            foreach (EventData message in events)
            {
                try
                {
                    message.Properties.TryGetValue("tenant", out object tenant);

                    if (tenant != null)
                    {
                        string                      eventData          = Encoding.UTF8.GetString(message.Body.Array);
                        Twin                        twin               = JsonConvert.DeserializeObject <Twin>(eventData);
                        TwinServiceModel            twinServiceModel   = new TwinServiceModel(twin);
                        Dictionary <string, JToken> reportedProperties = twinServiceModel.ReportedProperties;
                        var  json             = JToken.Parse(JsonConvert.SerializeObject(reportedProperties));
                        var  fieldsCollector  = new JsonFieldsCollector(json);
                        var  fields           = fieldsCollector.GetAllFields();
                        bool isFirmWareUpdate = false;
                        foreach (var field in fields)
                        {
                            isFirmWareUpdate = field.Key.Contains(FIRMWARE, StringComparison.OrdinalIgnoreCase);
                            if (isFirmWareUpdate)
                            {
                                break;
                            }
                        }

                        if (isFirmWareUpdate)
                        {
                            message.SystemProperties.TryGetValue("iothub-connection-device-id", out object deviceId);
                            var newTwin = await TenantConnectionHelper.GetRegistry(Convert.ToString(tenant)).GetTwinAsync(deviceId.ToString());

                            var appliedConfigurations = newTwin.Configurations.Where(c => c.Value.Status.Equals(ConfigurationStatus.Applied));
                            if (appliedConfigurations != null && appliedConfigurations.Count() > 0)
                            {
                                DeploymentSyncService service    = new DeploymentSyncService();
                                var appliedDeploymentFromStorage = service.GetDeploymentsByIdFromStorage(Convert.ToString(tenant), appliedConfigurations.Select(ac => ac.Key).ToArray()).Result.FirstOrDefault();
                                await service.SaveDeploymentHistory(Convert.ToString(tenant), appliedDeploymentFromStorage, newTwin);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.LogError($"Error occurrred : {ex.Message} StackTrace: {ex.StackTrace}  Inner Exception: {(string.IsNullOrEmpty(ex.StackTrace) ? string.Empty : ex.StackTrace)}");
                    exceptionOccurred = true;
                }
            }

            if (exceptionOccurred)
            {
                throw new Exception("Function Failed with exception");
            }
        }
Example #7
0
 public JobUpdateTwinApiModel(string deviceId, TwinServiceModel deviceTwin)
 {
     if (deviceTwin != null)
     {
         this.ETag        = deviceTwin.ETag;
         this.DeviceId    = deviceId;
         this.Properties  = new TwinPropertiesApiModel(deviceTwin.DesiredProperties, deviceTwin.ReportedProperties);
         this.Tags        = deviceTwin.Tags;
         this.IsSimulated = deviceTwin.IsSimulated;
     }
 }
Example #8
0
        private async Task SaveModuleTwin(string deploymentId, TwinServiceModel moduleTwin, string existingModuleTwinEtag)
        {
            var value = JsonConvert.SerializeObject(
                moduleTwin,
                Formatting.Indented,
                new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            });

            await this.client.UpdateAsync(string.Format(DeploymentEdgeModulePropertiesCollection, deploymentId), $"{moduleTwin.DeviceId}-{this.RemoveSpecialCharacters(moduleTwin.ModuleId)}", value, existingModuleTwinEtag);
        }
Example #9
0
        private async Task SaveDeviceTwin(string deploymentId, TwinServiceModel deviceTwin, string existingDeviceTwinEtag)
        {
            var value = JsonConvert.SerializeObject(
                deviceTwin,
                Formatting.Indented,
                new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
            });

            await this.client.UpdateAsync(string.Format(DeploymentDevicePropertiesCollection, deploymentId), deviceTwin.DeviceId, value, existingDeviceTwinEtag);
        }
Example #10
0
        private TwinServiceModel CreateTwinServiceModel(ValueApiModel input)
        {
            TwinServiceModel output = JsonConvert.DeserializeObject <TwinServiceModel>(input.Data);

            return(output);
        }
Example #11
0
 private DeviceServiceModel CreateDeviceTwinListServiceModel(TwinServiceModel input, DeviceServiceModel data)
 {
     data.Twin = input;
     return(data);
 }
Example #12
0
        public async Task <JobServiceModel> ScheduleTwinUpdateAsync(
            string jobId,
            string queryCondition,
            TwinServiceModel twin,
            DateTimeOffset startTimeUtc,
            long maxExecutionTimeInSeconds)
        {
            //var result = await this.jobClient.ScheduleTwinUpdateAsync(
            //    jobId,
            //    queryCondition,
            //    twin.ToAzureModel(),
            //    startTimeUtc.DateTime,
            //    maxExecutionTimeInSeconds);


            var devicelistString = queryCondition.Replace("deviceId in", "").Trim();
            var devicelist       = JsonConvert.DeserializeObject <List <dynamic> >(devicelistString);
            List <DeviceJobServiceModel> devicemodellist = new List <DeviceJobServiceModel>();

            foreach (var item in devicelist)
            {
                DeviceJobServiceModel data = new DeviceJobServiceModel();
                data.DeviceId           = item;
                data.Status             = DeviceJobStatus.Scheduled;
                data.CreatedDateTimeUtc = DateTime.UtcNow;
                devicemodellist.Add(data);
            }
            var             devicecount = devicemodellist.Count();
            JobServiceModel json        = new JobServiceModel();

            json.CreatedTimeUtc = DateTime.UtcNow;
            json.Devices        = devicemodellist.ToList();
            json.Status         = JobStatus.Scheduled;
            json.UpdateTwin     = twin;
            json.Type           = JobType.ScheduleUpdateTwin;
            JobStatistics ResultStatistics = new JobStatistics();

            ResultStatistics.DeviceCount    = devicecount;
            ResultStatistics.SucceededCount = 0;
            ResultStatistics.FailedCount    = 0;
            ResultStatistics.PendingCount   = 0;
            ResultStatistics.RunningCount   = 0;
            json.ResultStatistics           = ResultStatistics;
            var value = JsonConvert.SerializeObject(json, Formatting.Indented, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });
            var result = await this.client.CreateAsync(DEVICE_JOBS_COLLECTION_ID, value);

            var Job = this.CreatejobServiceModel(result);
            // Update the deviceProperties cache, no need to wait
            var model = new DevicePropertyServiceModel();

            var tagRoot = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(twin.Tags)) as JToken;

            if (tagRoot != null)
            {
                model.Tags = new HashSet <string>(tagRoot.GetAllLeavesPath());
            }

            var reportedRoot = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(twin.ReportedProperties)) as JToken;

            if (reportedRoot != null)
            {
                model.Reported = new HashSet <string>(reportedRoot.GetAllLeavesPath());
            }
            var unused = deviceProperties.UpdateListAsync(model);

            return(Job);
        }