Пример #1
0
 /// <summary>
 /// Creates a new instance of a DeviceModel.
 /// </summary>
 private GatewayController(GatewayModel gatewayDeviceConfig)
 {
     this.GatewayConfig       = gatewayDeviceConfig;
     this.GatewayDeviceConfig = new DeviceModel();
     this.GatewayDeviceConfig.DeviceProperties.HubEnabledState = gatewayDeviceConfig.ReportEnabledState;
     this.GatewayDeviceConfig.DeviceProperties.CreatedTime     = DateTime.UtcNow.ToString();
 }
Пример #2
0
        public void UpdateGatewayModel(GatewayModel config)
        {
            bool hasMutex = false;

            try{
                hasMutex = this.telemetryMutex.WaitOne(this.GatewayConfig.ReportingInterval);
                if (hasMutex)
                {
                    this.GatewayConfig.ReportEnabledState = config.ReportEnabledState;
                    this.GatewayConfig.ReportingInterval  = config.ReportingInterval;

                    // Clear DeviceInfo, it will be updated soon
                    // TODO: Copy telemetry matched metadata from existing GatewayDeviceConfig
                    this.GatewayDeviceConfig.Telemetry.Clear();
                }
                else
                {
                    Console.WriteLine("Error. Can't get mutext for telemetry data for {0} ms. Timeout!", this.GatewayConfig.ReportingInterval);
                }
            }finally{
                if (hasMutex)
                {
                    this.telemetryMutex.ReleaseMutex();
                }
            }
        }
Пример #3
0
        public static GatewayModel CreateGatewayModel(TwinCollection settings)
        {
            string serializedStr = JsonConvert.SerializeObject(settings);

            if (string.IsNullOrEmpty(serializedStr))
            {
                throw new ArgumentOutOfRangeException("No configuration provided for the module Twin.");
            }
            else
            {
                Console.WriteLine(String.Format("Attempt to parse configuration JSON: {0}", serializedStr));
                GatewayModel model = JsonConvert.DeserializeObject <GatewayModel>(serializedStr);
                if (model == null)
                {
                    throw new ArgumentOutOfRangeException("Errorparsing gateway twin settings");
                }
                else
                {
                    return(model);
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Callback to handle Twin desired properties updates�
        /// </summary>
        static async Task OnDesiredPropertiesUpdate(TwinCollection desiredProperties, object userContext)
        {
            var userContextValues = userContext as Tuple <ModuleClient, GatewayController>;

            if (userContextValues == null)
            {
                throw new InvalidOperationException("UserContext doesn't contain expected values");
            }
            ModuleClient      ioTHubModuleClient = userContextValues.Item1;
            GatewayController gatewayHandle      = userContextValues.Item2;

            try
            {
                // stop all activities while updating configuration
                await ioTHubModuleClient.SetInputMessageHandlerAsync(InputName, DummyCallBack, null);

                GatewayModel updateModel = GatewayController.CreateGatewayModel(desiredProperties);

                gatewayHandle.UpdateGatewayModel(updateModel);

                // restore message handling
                await ioTHubModuleClient.SetInputMessageHandlerAsync(InputName, PipeMessage, userContext);
            }
            catch (AggregateException ex)
            {
                foreach (Exception exception in ex.InnerExceptions)
                {
                    Console.WriteLine();
                    Console.WriteLine("Error when receiving desired property: {0}", exception);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine("Error when receiving desired property: {0}", ex.Message);
            }
        }
Пример #5
0
        /**
         * Initialize and Send DeviceInfo message
         */
        public static async Task <GatewayController> Start(ModuleClient ioTHubModuleClient, Twin moduleTwin, CancellationToken cancelToken)
        {
            if (moduleTwin == null || moduleTwin.Properties == null)
            {
                throw new ArgumentOutOfRangeException("No module Twin desired properties provided.");
            }
            GatewayModel gatewayDeviceConfig = CreateGatewayModel(moduleTwin.Properties.Desired);

            GatewayController gatewayHandle = new GatewayController(gatewayDeviceConfig);

            DeviceProperties gatewayProperties = gatewayHandle.GatewayDeviceConfig.DeviceProperties;

            gatewayProperties.DeviceID = moduleTwin.ModuleId;

            // This is the place you can specify the metadata for your device. The below fields are not mandatory.

            gatewayProperties.UpdatedTime     = DateTime.UtcNow.ToString();
            gatewayProperties.FirmwareVersion = "1.0";
            gatewayProperties.InstalledRAM    = "Unknown";
            gatewayProperties.Manufacturer    = "Unknown";
            gatewayProperties.ModelNumber     = "Unknown";
            gatewayProperties.Platform        = RuntimeInformation.OSDescription;
            gatewayProperties.Processor       = Enum.GetName(typeof(Architecture), RuntimeInformation.OSArchitecture);
            gatewayProperties.SerialNumber    = "Unknown";

            // Create send task
            await Task.Factory.StartNew(async() => {
                while (true)
                {
                    if (gatewayHandle.GatewayConfig.ReportEnabledState)
                    {
                        bool hasMutex = false;
                        try{
                            hasMutex = gatewayHandle.telemetryMutex.WaitOne(gatewayHandle.GatewayConfig.ReportingInterval);
                            if (hasMutex)
                            {
                                if (gatewayHandle.Telemetry.Count > 0)             // Send current telemetry data
                                {
                                    gatewayHandle.SendData(ioTHubModuleClient, gatewayHandle.Telemetry);
                                    gatewayHandle.Telemetry.Clear();
                                }
                                if (gatewayHandle.IsDeviceInfoUpdated)             // Send DeviceInfo structure into module twin

                                {
                                    string serializedStr    = JsonConvert.SerializeObject(gatewayHandle.GatewayDeviceConfig);
                                    TwinCollection reported = JsonConvert.DeserializeObject <TwinCollection>(serializedStr);
                                    await ioTHubModuleClient.UpdateReportedPropertiesAsync(reported);
                                    gatewayHandle.IsDeviceInfoUpdated = false;
                                }
                            }
                            else
                            {
                                Console.WriteLine("Error. Can't get mutext for telemetry data for {0} ms. Timeout!", gatewayHandle.GatewayConfig.ReportingInterval);
                            }
                        }catch (Exception ex) {
                            Console.WriteLine("Error upload data: {0}, {1}", ex.Message, ex.StackTrace);
                        }
                        finally{
                            if (hasMutex)
                            {
                                gatewayHandle.telemetryMutex.ReleaseMutex();
                            }
                        }
                    }
                    await Task.Delay(gatewayHandle.GatewayConfig.ReportingInterval);

                    if (cancelToken.IsCancellationRequested)
                    {
                        // Cancel was called
                        Console.WriteLine("Sending task canceled");
                        break;
                    }
                }
            }, cancelToken);

            return(gatewayHandle);
        }