private List <ModuleObjectValue> GetObjectValuesFrom(string package) { List <ModuleObjectValue> objectValues = new List <ModuleObjectValue>(); foreach (var entry in SensoricConsts.GetSupportedSensorsToObjects()) { string sensorValue = GetSensorValueFromPackageOrEmpty(package, entry.Key); if (string.IsNullOrEmpty(sensorValue)) { continue; } int objectId = entry.Value; string logicalId = FindLogicalIdForRequiredObjectId(entry.Value); ApplicationCore.GetInstance().GetLogger().LogDebug($"В пакете найдено значение: {entry.Key}:{sensorValue}"); objectValues.Add( new ModuleObjectValue() { ModuleValue = sensorValue, ObjectId = objectId, ReceivedTime = DateTime.Now, LogicalDeviceId = logicalId }); } return(objectValues); }
static void Main() { try { // Загрузить настройки приложения из файла конфигурации. var configFilePath = "./appconfig.ini"; // Debug string. var config = new AppConfig(configFilePath); // Инициализировать приложение исходя из параметров конфигурационного файла. Console.WriteLine("Application initialization..."); ApplicationCore.GetInstance().Initialize(config); } catch (Exception e) { // log error. Console.Error.WriteLine("ERROR!"); Console.Error.WriteLine(e.Message); } finally { // Закончить все процессы программы при завершении работы ядра. Console.Error.WriteLine("Stopping application..."); ApplicationCore.GetInstance().Stop(); } }
private LoggerConfiguration NewLoggerConfiguration() { var loggerConfig = new LoggerConfiguration(); string loggerLevel = ApplicationCore.GetInstance().GetAppConfig().GetKeyValueOr("logLevel", infoLevel); if (loggerLevel == debugLevel) { loggerConfig.MinimumLevel.Debug(); } else if (loggerLevel == warnLevel) { loggerConfig.MinimumLevel.Warning(); } else if (loggerLevel == infoLevel) { loggerConfig.MinimumLevel.Information(); } string logFile = ApplicationCore.GetInstance().GetAppConfig().GetKeyValueOr("logPath", "snsrLog.log"); loggerConfig.WriteTo.File(logFile, rollingInterval: RollingInterval.Day); loggerConfig.WriteTo.Console(); return(loggerConfig); }
private void ListenInputClients(CancellationToken cancellationToken) { using (cancellationToken.Register(() => StopChannel())) { while (isStarted) { TcpClient client = listener.AcceptTcpClient(); ApplicationCore.GetInstance().GetLogger().LogInfo($"Client connected! {client.Client.RemoteEndPoint.ToString()}"); Task.Factory.StartNew(() => HandleClientAsync(client, cancellationToken)); } } }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. var config = ApplicationCore.GetInstance().GetAppConfig(); var dbHost = config.GetKeyValueOr("DbHost", "localhost"); var dbName = config.GetKeyValueOr("DbName", "snsr"); var dbUser = config.GetKeyValueOr("DbUser", "postgres"); var dbPassword = config.GetKeyValueOr("DbPassword", "masterkey"); optionsBuilder.UseNpgsql($"Host={dbHost};Database={dbName};Username={dbUser};Password={dbPassword}"); } }
/// <summary> /// Смотри базовый класс. /// </summary> public void Start(CancellationToken cancellationToken) { if (isStarted) { ApplicationCore.GetInstance().GetLogger().LogDebug($"Channel already started...{host}:{port}"); return; } ApplicationCore.GetInstance().GetLogger().LogDebug($"Starting channel...{host}:{port}"); // Стартует канал для прослушивания. isStarted = true; // Захостить сервер. var hostAddress = IPAddress.Parse(host); listener = new TcpListener(hostAddress, this.port); listener.Start(); Task.Factory.StartNew(() => ListenInputClients(cancellationToken)); }
private async void HandleClientAsync(TcpClient client, CancellationToken token) // async void - avoid, надо сделать шт { ApplicationCore.GetInstance().GetLogger().LogDebug($"Handle input connection from {client.Client.RemoteEndPoint.ToString()}"); var stream = client.GetStream(); byte[] buffer = new byte[256]; int readCount; try { while ((readCount = await stream.ReadAsync(buffer, 0, buffer.Length, token)) != 0) { ApplicationCore.GetInstance().GetLogger().LogInfo($"New data received from {client.Client.RemoteEndPoint.ToString()}"); ApplicationCore.GetInstance().GetLogger().LogInfo($"<-: {BinaryUtils.BytesToHexString(buffer, 0, readCount)}"); foreach (var module in modules) { var data = new byte[readCount]; Array.Copy(buffer, 0, data, 0, data.Length); if (module.IsPackageBelongsToModule(data)) { if (module.HasCorrectPackage(data)) { ApplicationCore.GetInstance().GetLogger().LogInfo($"{module.GetSerial()} handling data..."); module.HandleData(data); } } } } } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } finally { client.Close(); } }
public void ProcessPollResults(List <ModuleObjectValue> objectValues) { DbService.WriteValuesToDb(objectValues); ApplicationCore.GetInstance().GetLogger().LogInfo($"Закончен опрос {GetSerial()}"); }