diff --git a/BackendWorkerService/Program.cs b/BackendWorkerService/Program.cs index df384df..f2ea9b1 100644 --- a/BackendWorkerService/Program.cs +++ b/BackendWorkerService/Program.cs @@ -150,12 +150,19 @@ namespace BackendWorkerService #endregion #region 定時檢查燈控排程 - services.AddSingleton< LightScheduleJob>(); + services.AddSingleton(); services.AddSingleton( new JobSchedule(jobType: typeof(LightScheduleJob), cronExpression: configuration.GetValue("BackgroundServiceCron:LightScheduleJob ")) ); #endregion + #region 定時記錄緊急應變告警排程 + services.AddSingleton(); + services.AddSingleton( + new JobSchedule(jobType: typeof(EmergencyRecordJob), cronExpression: configuration.GetValue("BackgroundServiceCron:EmergencyRecordJob ")) + ); + #endregion + }).ConfigureLogging((hostContext, logFactory) => { IConfiguration configuration = hostContext.Configuration; diff --git a/BackendWorkerService/Quartz/Jobs/EmergencyRecordJob.cs b/BackendWorkerService/Quartz/Jobs/EmergencyRecordJob.cs new file mode 100644 index 0000000..db01740 --- /dev/null +++ b/BackendWorkerService/Quartz/Jobs/EmergencyRecordJob.cs @@ -0,0 +1,156 @@ +嚜簑sing FrontendWebApi.Models; +using Microsoft.Extensions.Logging; +using Quartz; +using Repository.BackendRepository.Interface; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace BackendWorkerService.Quartz.Jobs +{ + [DisallowConcurrentExecution] + + class EmergencyRecordJob : IJob + { + private readonly ILogger logger; + private readonly IBackendRepository backendRepository; + private readonly ILogger loggers; + public EmergencyRecordJob(ILogger logger, IBackendRepository backendRepository, ILogger loggers) + { + this.logger = logger; + this.backendRepository = backendRepository; + this.loggers = loggers; + } + + public async Task Execute(IJobExecutionContext context) + { + Task_Detail task_Detail = new Task_Detail(loggers, backendRepository); + try + { + if (await task_Detail.GetNeedWorkTask("EmergencyRecordJob", "EmergencyRecord")) + { + try + { + await task_Detail.InsertWorkTime("EmergencyRecordJob", "EmergencyRecord"); + + var sqlString = $@"SELECT system_value FROM variable WHERE system_type = 'obixConfig' AND system_key = 'ApiBase' AND deleted = 0"; + string baseApiUrl = await backendRepository.GetOneAsync(sqlString); + + + sqlString = $@"SELECT system_value FROM variable WHERE system_type = 'emergencyConfig' AND system_key = 'getNiagaraAlarmMoveDayNumStart' AND deleted = 0"; + int moveDayNum = int.Parse((await backendRepository.GetOneAsync(sqlString)) ?? "-1"); + + string apiUrl = Path.Combine(baseApiUrl, "obix/config/Services/AlarmService/~alarmQuery/"); + + + var device_disaster = await backendRepository.GetAllAsync("device_disaster",""); + + using (HttpClient client = new HttpClient()) + { + string username = "stanGG"; + string password = "St12345678"; + string encoded = Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); + + client.DefaultRequestHeaders.Add("Authorization", "Basic " + encoded); + // 撱箸 XML 豢 + string xmlData = @$" + + + "; + HttpContent content = new StringContent(xmlData, Encoding.UTF8, "application/xml"); + + var response = await client.PostAsync(apiUrl, content); + var resString = (await response.Content.ReadAsStringAsync()).ToString(); + + XDocument xmlDoc = XDocument.Parse(resString); + + var list = xmlDoc.Descendants().Where(d => d.Name?.LocalName == "list").FirstOrDefault(); + var objs = list.Descendants().Where(d => d.Name?.LocalName == "obj" && (d.Attribute("is")?.Value?.Contains("obix:Alarm") ?? false)).ToList(); + var dictionaryList = new List>(); + + + List filterList = device_disaster.Select(x => x.device_number).ToList(); + + var filteredObjs = objs.Where(obj => + { + var deviceNumber = obj.Descendants().Where(d => d.Name.LocalName == "str" && d.Attribute("name").Value == "sourceName") + .Select(d => d.Attribute("val").Value) + .Select(d => string.Join("_", d.Split("_").Take(5))) + .FirstOrDefault(); + + return filterList.Contains(deviceNumber); + }).ToList(); + + foreach (var obj in filteredObjs) + { + var newguid = Guid.NewGuid(); + var alarm_timestamp = obj.Descendants().Where(d => d.Name.LocalName == "abstime" && d.Attribute("name").Value == "timestamp") + .Select(d => + { + DateTime valid; + if (DateTime.TryParse(d.Attribute("val").Value, out valid)) + { + return DateTime.Parse(d.Attribute("val").Value).ToString("yyyy-MM-dd HH:mm:ss"); + } + else + { + return null; + } + }).FirstOrDefault(); + var device_number = obj.Descendants().Where(d => d.Name.LocalName == "str" && d.Attribute("name").Value == "sourceName") + .Select(d => d.Attribute("val").Value) + .Select(d => string.Join("_", d.Split("_").Take(5))) + .FirstOrDefault(); + var filterDevice = device_disaster.Where(x => x.device_number == device_number).FirstOrDefault(); + + var dictionary = new Dictionary() + { + {"@emergency_event_guid",newguid}, + {"@disaster",filterDevice.device_system_value}, + {"@building_tag", filterDevice.device_building_tag}, + {"@device_guid",filterDevice.device_guid }, + {"@type",0}, + {"@alarm_time",alarm_timestamp} + }; + dictionaryList.Add(dictionary); + + } + + var mergeSql = @" + INSERT INTO emergency_event + (emergency_event_guid, disaster, device_guid, building_tag, type, alarm_time) + VALUES + (@emergency_event_guid, @disaster, @device_guid, @building_tag, @type, @alarm_time) + ON DUPLICATE KEY UPDATE + disaster = VALUES(disaster), + building_tag = VALUES(building_tag), + type = VALUES(type)"; + + + await backendRepository.ExecuteSql(mergeSql, dictionaryList); + + } + + await task_Detail.InsertWorkTime_End("EmergencyRecordJob", "EmergencyRecord"); + } + catch (Exception ex) + { + await task_Detail.WorkFail("EmergencyRecordJob", "EmergencyRecord", ex.Message.ToString()); + } + } + } + catch (Exception exception) + { + logger.LogError("EmergencyRecordJob隞餃憭望"); + logger.LogError("EmergencyRecordJob隞餃憭望[Exception]嚗{0}", exception.ToString()); + } + } + + } + +} diff --git a/BackendWorkerService/appsettings.Development.json b/BackendWorkerService/appsettings.Development.json index 2246065..b242733 100644 --- a/BackendWorkerService/appsettings.Development.json +++ b/BackendWorkerService/appsettings.Development.json @@ -16,6 +16,7 @@ "ArchiveElectricMeterHourJob": "0 0 2 * * ?", "ArchiveElectricMeterDayJob": "0/5 * * * * ?", "LightScheduleJob ": "0/5 * * * * ?", + "EmergencyRecordJob ": "0/5 * * * * ?", "WeatherAPIJob": "0/5 * * * * ?" }, "DBConfig": { diff --git a/BackendWorkerService/appsettings.json b/BackendWorkerService/appsettings.json index 55bfb05..7b21805 100644 --- a/BackendWorkerService/appsettings.json +++ b/BackendWorkerService/appsettings.json @@ -17,6 +17,7 @@ "ArchiveElectricMeterHourJob": "0 0 2 * * ?", "ArchiveElectricMeterDayJob": "0/5 * * * * ?", "LightScheduleJob ": "0 0/1 * * * ?", + "EmergencyRecordJob ": "0 0/1 * * * ?", "WeatherAPIJob": "0 0 2 * * ?" }, "DBConfig": { diff --git a/FrontendWebApi/ApiControllers/AlarmController.cs b/FrontendWebApi/ApiControllers/AlarmController.cs index a9bbf46..170053a 100644 --- a/FrontendWebApi/ApiControllers/AlarmController.cs +++ b/FrontendWebApi/ApiControllers/AlarmController.cs @@ -121,7 +121,7 @@ namespace FrontendWebApi.ApiControllers DateTime valid; if (DateTime.TryParse(d.Attribute("val").Value, out valid)) { - return DateTime.Parse(d.Attribute("val").Value).ToString("yyyy-MM-dd HH:mm:ss.fff"); + return DateTime.Parse(d.Attribute("val").Value).ToString("yyyy-MM-dd HH:mm:ss"); } else { diff --git a/FrontendWebApi/ApiControllers/EmergencyDeviceController.cs b/FrontendWebApi/ApiControllers/EmergencyDeviceController.cs index b7b2885..7173129 100644 --- a/FrontendWebApi/ApiControllers/EmergencyDeviceController.cs +++ b/FrontendWebApi/ApiControllers/EmergencyDeviceController.cs @@ -6,6 +6,7 @@ using Newtonsoft.Json; using Repository.BackendRepository.Interface; using Repository.FrontendRepository.Interface; using System; +using System.Collections; using System.Collections.Generic; using System.Data.SqlTypes; using System.Diagnostics; @@ -256,18 +257,44 @@ namespace FrontendWebApi.ApiControllers } try { - var newguid = Guid.NewGuid(); - var dictionary = new Dictionary() + if (eventpost.emergency_event_guid != null) + { + var dictionary = new Dictionary() + { + {"@finish_time",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} + }; + await backendRepository.UpdateOneByCustomTable(dictionary, "emergency_event", $"emergency_event_guid = '{eventpost.emergency_event_guid}'"); + apiResult.Code = "0000"; + apiResult.Msg = "湔啣"; + } + else + { + // 瑼X交臬行閰脩 + var sql = "SELECT * FROM emergency_event WHERE alarm_time = @alarmTime AND device_guid = @deviceGuid"; + var count = await backendRepository.GetOneAsync(sql, new { alarmTime = eventpost.alarm_time, deviceGuid = eventpost.device }); + if (count != null) + { + apiResult.Code = "0000"; + apiResult.Msg = "撌脫閰脩蝝"; + apiResult.Data = count.emergency_event_guid; + + return Ok(apiResult); + } + + var newguid = Guid.NewGuid(); + var dictionary = new Dictionary() { {"@emergency_event_guid",newguid}, {"@disaster",eventpost.disaster}, {"@building_tag", eventpost.build}, {"@device_guid",eventpost.device }, - {"@type",eventpost.type} + {"@type",eventpost.type}, + {"@alarm_time",eventpost.alarm_time} }; - await backendRepository.AddOneByCustomTable(dictionary, "emergency_event"); - apiResult.Data = newguid.ToString(); - apiResult.Code = "0000"; + await backendRepository.AddOneByCustomTable(dictionary, "emergency_event"); + apiResult.Data = newguid.ToString(); + apiResult.Code = "0000"; + } } catch (Exception exception) { diff --git a/FrontendWebApi/ApiControllers/EmergencyRecordController.cs b/FrontendWebApi/ApiControllers/EmergencyRecordController.cs index 871cb49..21a3159 100644 --- a/FrontendWebApi/ApiControllers/EmergencyRecordController.cs +++ b/FrontendWebApi/ApiControllers/EmergencyRecordController.cs @@ -71,7 +71,7 @@ namespace FrontendWebApi.ApiControllers } EmergencyRecordEvent = await backendRepository.GetAllAsync($@" - select d.device_number device_name,v.system_key disaster_name,ee.*,b.full_name building_name from emergency_event ee + select d.device_number device_name,v.system_key disaster_name,ee.*,b.full_name building_name,ee.alarm_time,ee.finish_time from emergency_event ee left join (select * from variable v where v.system_type = 'disaster') v on v.system_value = ee.disaster left join device d on d.device_guid = ee.device_guid left join building b on b.building_tag = ee.building_tag diff --git a/FrontendWebApi/Models/EmergencyDevice.cs b/FrontendWebApi/Models/EmergencyDevice.cs index a7ffe41..800230d 100644 --- a/FrontendWebApi/Models/EmergencyDevice.cs +++ b/FrontendWebApi/Models/EmergencyDevice.cs @@ -113,10 +113,13 @@ namespace FrontendWebApi.Models public class Eventpost { + public string emergency_event_guid { get; set; } public int disaster { get; set; } public string build { get; set; } public byte type { get; set; } public string device { get; set; } + public string alarm_time { get; set; } = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); + } public class EmergencySetting diff --git a/FrontendWebApi/Models/EmergencyRecord.cs b/FrontendWebApi/Models/EmergencyRecord.cs index a0bab2f..458ae63 100644 --- a/FrontendWebApi/Models/EmergencyRecord.cs +++ b/FrontendWebApi/Models/EmergencyRecord.cs @@ -19,11 +19,15 @@ namespace FrontendWebApi.Models public class EmergencyRecordEvent : Actor { + private string _alarm_time; + private string _finish_time; public string emergency_event_guid { get; set; } public int disaster { get; set; } public string device_guid { get; set; } public string building_guid { get; set; } public byte type { get; set; } + public string alarm_time { get { return Convert.ToDateTime(_alarm_time).ToString("yyyy-MM-dd HH:mm:ss"); } set { _alarm_time = value; } } + public string finish_time { get { return Convert.ToDateTime(_finish_time).ToString("yyyy-MM-dd HH:mm:ss"); } set { _finish_time = value; } } } public class EmergencyRecordEventTable : EmergencyRecordEvent diff --git a/FrontendWebApi/Views/EmergencyDeviceMenu/Index.cshtml b/FrontendWebApi/Views/EmergencyDeviceMenu/Index.cshtml index 133df90..713ed78 100644 --- a/FrontendWebApi/Views/EmergencyDeviceMenu/Index.cshtml +++ b/FrontendWebApi/Views/EmergencyDeviceMenu/Index.cshtml @@ -1,12 +1,12 @@ 嚜濃{ ViewData["MainNum"] = "4"; ViewData["SubNum"] = "1"; - ViewData["Title"] = "閮剖蝮質汗"; + ViewData["Title"] = "鈭隞嗆"; } @@ -94,7 +94,10 @@ @**@ - +
+ @**@ + +