using FrontendWebApi.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using Repository.FrontendRepository.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; using System.Xml.Linq; namespace FrontendWebApi.ApiControllers { /// /// 告警紀錄 /// public class AlarmController : MyBaseApiController { private readonly IFrontendRepository frontendRepository; public AlarmController ( IFrontendRepository frontendRepository ) { this.frontendRepository = frontendRepository; } [HttpPost] [Route("api/Alarm/GetAlarmFromObix")] public async Task>> GetAlarmFromObix() { ApiResult apiResult = new ApiResult(jwt_str); if (!jwtlife) { apiResult.Code = "5000"; return BadRequest(apiResult); } try { var sqlString = $@"SELECT system_value FROM variable WHERE system_type = 'obixConfig' AND system_key = 'ApiBase' AND deleted = 0"; string baseApiUrl = await frontendRepository.GetOneAsync(sqlString); if (string.IsNullOrEmpty(baseApiUrl)) { apiResult.Code = "9998"; apiResult.Msg = "未找到 obixConfig baseAPI,請聯絡管理者。"; return BadRequest(apiResult); } string apiUrl = Path.Combine(baseApiUrl, "obix/config/Services/AlarmService/~alarmQuery/"); 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(); // 宣告要丟出去的資料容器 AlarmObj alarmObj = new AlarmObj() { alarmorion = new List(), buildingAlarmDeviceAmount = new List() }; // 篩選 toState != normal objs = objs.Where(d => d.Descendants().Any(dd => dd?.Name?.LocalName == "str" && dd?.Attribute("name")?.Value == "toState" && dd?.Attribute("val")?.Value != "normal")).ToList(); // // alarmObj.alarmorion = objs.Select(obj => new AlarmorionString() { 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.fff"); } else { return null; } }).FirstOrDefault(), 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(), }).ToList(); // obix alarm 回傳 device_number + point 取出棟別分組 alarmObj.buildingAlarmDeviceAmount = alarmObj.alarmorion.Where(a => a.device_number?.Contains("_") ?? false) .GroupBy(g => g.device_number.Split("_")[0]).Select(g => new BuildingAlarmDeviceAmount() { building_tag = g.Key, device_amount = g.Count() }).ToList(); apiResult.Data = alarmObj; } apiResult.Msg = "讀取成功"; apiResult.Code = "0000"; } catch (Exception exception) { apiResult.Code = "9999"; apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); return Ok(apiResult); } return Ok(apiResult); } } }