Exemplo n.º 1
0
        public async Task <bool> SaveConfigAsync(string key)
        {
            var configs = new HardwareConfig
            {
                CpuCoreCount       = Environment.ProcessorCount,
                ClockFrequency     = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds,
                RandomAccessMemory = (int)Process.GetCurrentProcess().WorkingSet64 / 1024,
                DiskSpace          = DriveInfo.GetDrives().Select(o => o.TotalFreeSpace).Sum()
            };

            var message = new SaveConfigMessage()
            {
                SessionKey = key, Config = configs
            };

            var deSerializedData = await GetDataAsync(message);

            switch (deSerializedData)
            {
            case ErrorMessage errorMessage:
                MessageBox.Show(errorMessage.Error);
                return(false);

            case SuccessfulMessage successfulMessage:
                MessageBox.Show(successfulMessage.ToString());
                return(true);

            default:
                throw new Exception();
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// SetNewSpectrumControls retrieves the Hardware configuration
        /// and enables or disables the New Spectrum button.
        /// </summary>
        private void SetNewSpectrumControls()
        {
            //Get the Hardware Configuration and set the New Enable
            ConfigHelper <HardwareConfig> helper = new ConfigHelper <HardwareConfig>(ConfigLocation.AllUsers);
            HardwareConfig hc = helper.GetConfig();

            this.NewEnabled = hc.IsConfigured;
        }
Exemplo n.º 3
0
        public async Task <bool> FindDevicesAsync(HardwareConfig config)
        {
            var modified = false;

            if (config.MiHome != null)
            {
                foreach (var gatewayConfig in config.MiHome.Gateways)
                {
                    var miHome = new MiHome(gatewayConfig.Password, gatewayConfig.Id);
                    m_MiHomeObjects.Add(miHome);
                    await Task.Delay(5000);

                    var gateway = miHome.GetGateway();
                    if (gateway != null)
                    {
                        AddDevice(gatewayConfig.Name, gatewayConfig.Description, gateway);
                        foreach (var device in miHome.GetDevices())
                        {
                            var deviceConfig = gatewayConfig.Devices.SingleOrDefault(deviceConfig => deviceConfig.Id == device.Sid);
                            if (deviceConfig == null)
                            {
                                deviceConfig = CreateDeviceConfig(device);
                                gatewayConfig.Devices.Add(deviceConfig);
                                modified = true;
                            }
                            AddDevice(deviceConfig.Name, deviceConfig.Description, device);
                        }
                    }
                }
            }

            if (config.Http != null)
            {
                foreach (var deviceConfig in config.Http.Devices)
                {
                    var device = HttpDevice.Create(deviceConfig.Type);
                    if (device != null)
                    {
                        device.Host = deviceConfig.Host;
                        AddDevice(deviceConfig.Name, deviceConfig.Description, device);
                    }
                }
            }

            if (config.Virtual != null)
            {
                foreach (var switchConfig in config.Virtual.Switches)
                {
                    var @switch = new Virtual.Switch();
                    @switch.SetStatus(switchConfig.Status);
                    AddDevice(switchConfig.Name, switchConfig.Description, @switch);
                }
            }

            return(modified);
        }
Exemplo n.º 4
0
        public void AssertConnectedAndConfigured(HardwareConfig config)
        {
            if (config.Simulated)
            {
                throw new Exception("Carte simulée");
            }

            if (!Connected)
            {
                throw new Exception("Carte non connectée");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// CheckHardwareConfiguration is called when the ShellView
        /// Window is created.  It shows the Hardware Configuration
        /// Wizard if necessary when the application starts.
        /// </summary>
        public void CheckHardwareConfiguration()
        {
            //Get the Hardware Config
            ConfigHelper <HardwareConfig> helper = new ConfigHelper <HardwareConfig>(ConfigLocation.AllUsers);
            HardwareConfig config = helper.GetConfig();

            //If the Hardware hasn't been configured and the user
            //hasn't clicked the Do Not Configure checkbox,
            //show the Wizard.
            if (config.IsConfigured == false && config.DoNotConfigure == false)
            {
                this.OnConfigureHardware();
            }
        }
Exemplo n.º 6
0
        public void ClassToXml()
        {
            string         startupPath      = System.IO.Path.GetFullPath(@"..\..\..\..\");
            HardwareConfig m_list           = XmlHandler.XmlReader <HardwareConfig>(startupPath + @"HardwareConfig.xml");
            SoftwareConfig mySoftwareConfig = XmlHandler.XmlReader <SoftwareConfig>(startupPath + @"SoftwareConfig.xml");


            Dictionary <string, string> myTestDictionary = new Dictionary <string, string>();

            foreach (SoftwareConfigPathsFile item in mySoftwareConfig.paths.installedFonts)
            {
                myTestDictionary.Add(item.type, item.Value);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Default constructor for the HardwareViewModel object.
        /// </summary>
        /// <param name="unity">The Unity container to get objects</param>
        public HardwareViewModel(IUnityContainer unity)
        {
            //Save the input in member variables
            this._unity = unity;

            //Get the HardwareConfig from app.config
            ConfigHelper <HardwareConfig> helper = new ConfigHelper <HardwareConfig>(ConfigLocation.AllUsers);

            this._config = helper.GetWriteableConfig();

            //Set the value so that the hardware is not configured
            //by default
            this._config.IsConfigured = false;

            //Create the Wizard Pages
            this.CreateWizardPages();
        }
Exemplo n.º 8
0
        public bool SaveConfig(string sessionKey, HardwareConfig config)
        {
            var cmd    = _sqLiteConnection.CreateCommand();
            int userID = default;

            try
            {
                var getLogin =
                    $"SELECT UserID FROM Users WHERE login = '******'";
                cmd.CommandText = getLogin;
                var result = cmd.ExecuteScalar();
                if (result is null)
                {
                    return(false);
                }
                userID = (int)(long)result;
            }
            catch (InvalidOperationException)
            {
                return(false);
            }

            try
            {
                var newConfigs = $"INSERT INTO Configs VALUES(null,{config.CpuCoreCount}, " +
                                 $"{config.ClockFrequency.ToString(CultureInfo.InvariantCulture)}, " +
                                 $"{config.RandomAccessMemory.ToString(CultureInfo.InvariantCulture)}," +
                                 $"{config.DiskSpace.ToString(CultureInfo.InvariantCulture)}, " +
                                 $"{userID}, " +
                                 $"'{ConvertFormatData(DateTime.Now)}')";
                cmd.CommandText = newConfigs;
                cmd.ExecuteNonQuery();
                return(true);
            }
            catch (InvalidOperationException)
            {
                return(false);
            }
        }
Exemplo n.º 9
0
        public HardwareConfig[] GetListOfConfig(string sessionKey, DateTime from, DateTime to)
        {
            var    cmd    = _sqLiteConnection.CreateCommand();
            string userID = default;

            try
            {
                userID          = $"SELECT UserID FROM Users WHERE login = '******'";
                cmd.CommandText = userID;
                cmd.ExecuteNonQuery();
            }
            catch (InvalidOperationException)
            {
                return(null);
            }
            var getHardwareConfigs = $"SELECT CpuCoreCount, ClockFrequency, RandomAccessMemory, DiskSpace FROM Configs WHERE ConfigData BETWEEN '{ConvertFormatData(from)}' AND '{ConvertFormatData(to)}'";

            cmd.CommandText = getHardwareConfigs;

            var listOfConfigs = new List <HardwareConfig>();

            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var hardwareConfigs = new HardwareConfig()
                    {
                        CpuCoreCount       = reader.GetInt32(reader.GetOrdinal("CpuCoreCount")),
                        ClockFrequency     = reader.GetDouble(reader.GetOrdinal("ClockFrequency")),
                        RandomAccessMemory = reader.GetDouble(reader.GetOrdinal("RandomAccessMemory")),
                        DiskSpace          = reader.GetDouble(reader.GetOrdinal("DiskSpace")),
                    };
                    listOfConfigs.Add(hardwareConfigs);
                }
            }

            return(listOfConfigs.ToArray());
        }
Exemplo n.º 10
0
        private static void SaveHardwareConfig(string filePath, HardwareConfig config)
        {
            var document = new XDocument(config.ToXml());

            document.Save(filePath);
        }
Exemplo n.º 11
0
        private static HardwareConfig LoadHardwareConfig(string filePath)
        {
            var document = XDocument.Load(filePath);

            return(HardwareConfig.FromXml(document.Root));
        }
Exemplo n.º 12
0
 public void SaveHardwareConfig(string fileName, HardwareConfig config) => SaveConfig(fileName, config, config => config.ToXml());
Exemplo n.º 13
0
 public HardwareConfig LoadHardwareConfig(string fileName) => LoadConfig(fileName, element => HardwareConfig.FromXml(element));
Exemplo n.º 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <IrrigationConfig>(_configRoot.GetSection("Irrigation"));
            services.Configure <HardwareConfig>(_configRoot.GetSection("Hardware"));

            var channel = Channel.CreateUnbounded <IrrigationJob>(
                new UnboundedChannelOptions()
            {
                AllowSynchronousContinuations = false,
                SingleWriter = false,
                SingleReader = true
            });

            services.AddSingleton(channel);
            services.AddTransient(sp =>
            {
                var resolvedChannel = sp.GetRequiredService <Channel <IrrigationJob> >();
                return(channel.Reader);
            });
            services.AddTransient(sp =>
            {
                var resolvedChannel = sp.GetRequiredService <Channel <IrrigationJob> >();
                return(channel.Writer);
            });

            var driverSettings = new HardwareConfig();

            _configRoot.GetSection("Hardware").Bind(driverSettings);

            if (driverSettings.UseMemoryDriver)
            {
                services.AddSingleton(new GpioController(PinNumberingScheme.Logical, new MemoryGpioDriver(pinCount: 50)));
            }
            else
            {
                services.AddSingleton(new GpioController());
            }

            services.AddSingleton <RelayBoard>(sp =>
            {
                var hardwareConfig   = sp.GetRequiredService <IOptions <HardwareConfig> >().Value;
                var irrigationConfig = sp.GetRequiredService <IOptions <IrrigationConfig> >().Value;
                var controller       = sp.GetRequiredService <GpioController>();
                var pins             = (irrigationConfig.Valves.Select(v => v.GpioPin).Union(new[] { irrigationConfig.MasterControlValveGpio })).ToArray();

                return(new RelayBoard(hardwareConfig.RelayType, controller, pins));
            });

            services.AddHostedService <PinInitializer>();
            services.AddHostedService <IrrigationProcessor>();

            services.AddSingleton <IIrrigationStopper, IrrigationStopper>();
            services.AddSingleton <IrrigationProcessorStatus>();

            services.AddControllers().AddNewtonsoftJson();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Irrigation API", Version = "v1"
                });
            });

            services.AddHealthChecks()
            .AddCheck <ApplicationHealthCheck>("Application", tags: new[] { "application" })
            .AddCheck <IrrigationProcessorHealthCheck>("Irrigation", tags: new[] { "irrigation" });
        }