Beispiel #1
0
        private static bool ValidateSingleFcnt(uint?fCntStart, uint?fCntStartRep, uint?fCntResetCounter, uint?fCntResetCounterRep, string fCntStartType)
        {
            if (fCntStart == null)
            {
                // fCntStart not set. Nothing to do.
                return(true);
            }

            // fCntStartRep not null
            if (fCntStartRep == null || fCntStart > fCntStartRep)
            {
                StatusConsole.WriteLogLine(MessageType.Info, $"{fCntStartType} {fCntStart} will be set on gateway.");
                return(true);
            }

            // fCntStartRep not null, fCntStartRep not null, fCntStart <= fCntStartRep
            if (fCntResetCounter == null)
            {
                StatusConsole.WriteLogLine(MessageType.Warning, $"{fCntStartType} {fCntStart} will not be set on gateway. Reported {fCntStartType} {fCntStartRep} is larger or equal and FCntResetCounter is not set.");
                return(true);
            }

            // fCntStartRep not null, fCntStartRep not null, fCntStart <= fCntStartRep,
            // fCntResetCounter not null
            if (fCntResetCounterRep == null || fCntResetCounter > fCntResetCounterRep)
            {
                StatusConsole.WriteLogLine(MessageType.Info, $"{fCntStartType} {fCntStart} will be set on gateway.");
                return(true);
            }

            // fCntStartRep not null, fCntStartRep not null, fCntStart <= fCntStartRep,
            // fCntResetCounter not null, fCntResetCounterRep not null, fCntResetCounter <= fCntResetCounterRep
            StatusConsole.WriteLogLine(MessageType.Warning, $"{fCntStartType} {fCntStart} will not be set on gateway. Reported {fCntStartType} {fCntStartRep} is larger or equal and FCntResetCounter {fCntResetCounter} is not larger than reported FCntResetCounter {fCntResetCounterRep}.");
            return(true);
        }
        public bool ReadConfig(string[] args)
        {
            string iotHubConnectionString, netId, storageConnectionString;

            Console.WriteLine("Reading configuration from command line and \"appsettings.json\" file...");

            // Read configuration file appsettings.json
            try
            {
                var configurationBuilder = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                           .AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: false)
                                           .AddCommandLine(args)
                                           .Build();

                iotHubConnectionString  = configurationBuilder["iothub-connection-string"];
                storageConnectionString = configurationBuilder["storage-connection-string"];
                netId = configurationBuilder["NetId"];

                if (iotHubConnectionString is null || netId is null)
                {
                    StatusConsole.WriteLogLine(MessageType.Error, "IoT Hub connection string and NetId are required.");
                    return(false);
                }
            }
            catch (FileNotFoundException)
            {
                StatusConsole.WriteLogLine(MessageType.Error, "Configuration file 'appsettings.json' was not found.");
                return(false);
            }

            // Validate connection setting
            if (string.IsNullOrEmpty(iotHubConnectionString))
            {
                StatusConsole.WriteLogLine(MessageType.Error, "IoT Hub connection string may not be empty.");
                return(false);
            }
            else
            {
                // Just show IoT Hub Hostname
                if (GetHostFromConnectionString(iotHubConnectionString, out var hostName))
                {
                    StatusConsole.WriteLogLine(MessageType.Info, $"Using IoT Hub: {hostName}");
                }
                else
                {
                    StatusConsole.WriteLogLine(MessageType.Error, "Invalid connection string in appsettings.json. Can not find \"HostName=\". The file should have the following structure: { \"IoTHubConnectionString\" : \"HostName=xxx.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xxx\" }.");
                    return(false);
                }
            }

            // Validate NetId setting
            if (string.IsNullOrEmpty(netId))
            {
                netId = ValidationHelper.CleanNetId(Constants.DefaultNetId.ToString(CultureInfo.InvariantCulture));
                StatusConsole.WriteLogLine(MessageType.Info, $"NetId is not set in settings file. Using default {netId}.");
            }
            else
            {
                netId = ValidationHelper.CleanNetId(netId);

                if (ValidationHelper.ValidateHexStringTwinProperty(netId, 3, out var customError))
                {
                    StatusConsole.WriteLogLine(MessageType.Info, $"Using NetId {netId} from settings file.");
                }
                else
                {
                    var netIdBad = netId;
                    netId = ValidationHelper.CleanNetId(Constants.DefaultNetId.ToString(CultureInfo.InvariantCulture));
                    StatusConsole.WriteLogLine(MessageType.Warning, $"NetId {netIdBad} in settings file is invalid. {customError}.");
                    StatusConsole.WriteLogLine(MessageType.Warning, $"Using default NetId {netId} instead.");
                }
            }

            StatusConsole.WriteLogLine(MessageType.Info, $"To override, use --netid parameter.");

            NetId = netId;

            // Create Registry Manager using connection string
            try
            {
                RegistryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            }
            catch (Exception ex) when(ex is ArgumentNullException
                                      or FormatException
                                      or ArgumentException)
            {
                StatusConsole.WriteLogLine(MessageType.Error, $"Failed to create Registry Manager from connection string: {ex.Message}.");
                return(false);
            }

            if (storageConnectionString != null)
            {
                try
                {
                    CertificateStorageContainerClient = new BlobContainerClient(storageConnectionString, CredentialsStorageContainerName);
                    FirmwareStorageContainerClient    = new BlobContainerClient(storageConnectionString, FirmwareStorageContainerName);
                }
                catch (FormatException)
                {
                    StatusConsole.WriteLogLine(MessageType.Info, "Storage account is incorrectly configured.");
                }
            }

            Console.WriteLine("done.");
            return(true);
        }
        public bool ReadConfig()
        {
            string connectionString, netId;

            Console.WriteLine("Reading configuration file \"appsettings.json\"...");

            // Read configuration file appsettings.json
            try
            {
                var configurationBuilder = new ConfigurationBuilder()
                                           .SetBasePath(Directory.GetCurrentDirectory())
                                           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                           .AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: false)
                                           .Build();

                connectionString = configurationBuilder["IoTHubConnectionString"];
                netId            = configurationBuilder["NetId"];
            }
            catch (Exception ex)
            {
                StatusConsole.WriteLogLine(MessageType.Error, $"{ex.Message}");
                StatusConsole.WriteLogLine(MessageType.Info, "The file should have the following structure: { \"IoTHubConnectionString\" : \"HostName=xxx.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xxx\" }");
                return(false);
            }

            // Validate connection setting
            if (string.IsNullOrEmpty(connectionString))
            {
                StatusConsole.WriteLogLine(MessageType.Error, "Connection string not found in settings file. The format should be: { \"IoTHubConnectionString\" : \"HostName=xxx.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xxx\" }.");
                return(false);
            }
            else
            {
                // Just show IoT Hub Hostname
                if (this.GetHostFromConnectionString(connectionString, out string hostName))
                {
                    StatusConsole.WriteLogLine(MessageType.Info, $"Using IoT Hub: {hostName}");
                }
                else
                {
                    StatusConsole.WriteLogLine(MessageType.Error, "Invalid connection string in appsettings.json. Can not find \"HostName=\". The file should have the following structure: { \"IoTHubConnectionString\" : \"HostName=xxx.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=xxx\" }.");
                    return(false);
                }
            }

            // Validate NetId setting
            if (string.IsNullOrEmpty(netId))
            {
                netId = ValidationHelper.CleanNetId(Constants.DefaultNetId.ToString());
                StatusConsole.WriteLogLine(MessageType.Info, $"NetId is not set in settings file. Using default {netId}.");
            }
            else
            {
                netId = ValidationHelper.CleanNetId(netId);

                if (ValidationHelper.ValidateHexStringTwinProperty(netId, 3, out string customError))
                {
                    StatusConsole.WriteLogLine(MessageType.Info, $"Using NetId {netId} from settings file.");
                }
                else
                {
                    var netIdBad = netId;
                    netId = ValidationHelper.CleanNetId(Constants.DefaultNetId.ToString());
                    StatusConsole.WriteLogLine(MessageType.Warning, $"NetId {netIdBad} in settings file is invalid. {customError}.");
                    StatusConsole.WriteLogLine(MessageType.Warning, $"Using default NetId {netId} instead.");
                }
            }

            StatusConsole.WriteLogLine(MessageType.Info, $"To override, use --netid parameter.");

            this.NetId = netId;

            // Create Registry Manager using connection string
            try
            {
                this.RegistryManager = RegistryManager.CreateFromConnectionString(connectionString);
            }
            catch (Exception ex)
            {
                StatusConsole.WriteLogLine(MessageType.Error, $"Can not connect to IoT Hub (possible error in connection string): {ex.Message}.");
                return(false);
            }

            Console.WriteLine("done.");
            return(true);
        }
Beispiel #4
0
        public static bool ValidateSensorDecoder(string sensorDecoder, bool isVerbose)
        {
            var isValid   = true;
            var isWarning = false;

            if (sensorDecoder == null)
            {
                StatusConsole.WriteLogLine(MessageType.Error, "SensorDecoder is missing.");
                return(false);
            }

            if (sensorDecoder == string.Empty)
            {
                if (isVerbose)
                {
                    StatusConsole.WriteLogLine(MessageType.Info, "SensorDecoder is empty. No decoder will be used.");
                }

                return(true);
            }

            if (sensorDecoder.StartsWith("http", StringComparison.OrdinalIgnoreCase) || sensorDecoder.Contains('/'))
            {
                if (!Uri.TryCreate(sensorDecoder, UriKind.Absolute, out Uri validatedUri))
                {
                    StatusConsole.WriteLogLine(MessageType.Error, "SensorDecoder has an invalid URL.");
                    isValid = false;
                }

                // if (validatedUri.Host.Any(char.IsUpper))
                if (!sensorDecoder.StartsWith(validatedUri.Scheme, StringComparison.OrdinalIgnoreCase) ||
                    sensorDecoder.IndexOf(validatedUri.Host) != validatedUri.Scheme.Length + 3)
                {
                    StatusConsole.WriteLogLine(MessageType.Error, "SensorDecoder Hostname must be all lowercase.");
                    isValid = false;
                }

                if (validatedUri.AbsolutePath.IndexOf("/api/") < 0)
                {
                    if (isVerbose)
                    {
                        StatusConsole.WriteLogLine(MessageType.Warning, "SensorDecoder is missing \"api\" keyword.");
                    }

                    isWarning = true;
                }
            }

            if (isVerbose)
            {
                if (!isValid || isWarning)
                {
                    StatusConsole.WriteLogLine(MessageType.Info, "Make sure the URI based SensorDecoder Twin desired property looks like \"http://containername/api/decodername\".");
                }
                else
                {
                    StatusConsole.WriteLogLine(MessageType.Info, $"SensorDecoder {sensorDecoder} is valid.");
                }
            }

            return(isValid);
        }