Exemplo n.º 1
0
        private async Task <LoRaDevice> InitializeDeviceAsync(LoRaDevice loRaDevice)
        {
            try
            {
                // Our device if it does not have a gateway assigned or is assigned to our
                var isOurDevice = string.IsNullOrEmpty(loRaDevice.GatewayID) || string.Equals(loRaDevice.GatewayID, this.configuration.GatewayID, StringComparison.InvariantCultureIgnoreCase);
                // Only create client if the device is our
                if (!isOurDevice)
                {
                    loRaDevice.IsOurDevice = false;
                    return(loRaDevice);
                }

                // Calling initialize async here to avoid making async calls in the concurrent dictionary
                // Since only one device will be added, we guarantee that initialization only happens once
                if (await loRaDevice.InitializeAsync())
                {
                    // revalidate based on device twin property
                    loRaDevice.IsOurDevice = string.IsNullOrEmpty(loRaDevice.GatewayID) || string.Equals(loRaDevice.GatewayID, this.configuration.GatewayID, StringComparison.InvariantCultureIgnoreCase);
                    if (loRaDevice.IsOurDevice)
                    {
                        // once added, call initializers
                        if (this.initializers != null)
                        {
                            foreach (var initializer in this.initializers)
                            {
                                initializer.Initialize(loRaDevice);
                            }
                        }
                    }

                    // checking again in case one of the initializers change the value
                    if (!loRaDevice.IsOurDevice)
                    {
                        // Initialization does not use activity counters
                        // This should not fail
                        if (!loRaDevice.TryDisconnect())
                        {
                            Logger.Log(loRaDevice.DevEUI, "failed to disconnect device from another gateway", LogLevel.Error);
                        }
                    }

                    return(loRaDevice);
                }
            }
            catch (Exception ex)
            {
                // device does not have the required properties
                Logger.Log(loRaDevice.DevEUI ?? this.devAddr, $"error initializing device {loRaDevice.DevEUI}. {ex.Message}", LogLevel.Error);
            }

            // instance not used, dispose the connection
            loRaDevice.Dispose();
            return(null);
        }