diff --git a/Backend/Controllers/NiagaraDataSynchronizeController.cs b/Backend/Controllers/NiagaraDataSynchronizeController.cs index 2f2c473..22bf9d8 100644 --- a/Backend/Controllers/NiagaraDataSynchronizeController.cs +++ b/Backend/Controllers/NiagaraDataSynchronizeController.cs @@ -113,13 +113,13 @@ namespace Backend.Controllers building = data.GroupBy(x => x.tag_name.Split("_")[1]).Select(x => x.Key).ToList(); } - string LightSwitchLevel = await niagaraDataSynchronizeRepository.getLightSwitchLevel(); //獲取照明開關 是否在 device or device_node - await niagaraDataSynchronizeRepository.InsertNiagaraTagList(ds, building, tag_quantity); // 匯入 MySQL table: import_niagara_tag - await niagaraDataSynchronizeRepository.DeviceComparison(LightSwitchLevel); - await niagaraDataSynchronizeRepository.CheckDiffFullNameAndCover(); - await niagaraDataSynchronizeRepository.CheckFullNameEmptyReplaceByDeviceName(); - await niagaraDataSynchronizeRepository.InsertBuildingMenu(); - await niagaraDataSynchronizeRepository.InsertSubSystemFloor(); + //string LightSwitchLevel = await niagaraDataSynchronizeRepository.getLightSwitchLevel(); //獲取照明開關 是否在 device or device_node + //await niagaraDataSynchronizeRepository.InsertNiagaraTagList(ds, building, tag_quantity); // 匯入 MySQL table: import_niagara_tag + //await niagaraDataSynchronizeRepository.DeviceComparison(LightSwitchLevel); + //await niagaraDataSynchronizeRepository.CheckDiffFullNameAndCover(); + //await niagaraDataSynchronizeRepository.CheckFullNameEmptyReplaceByDeviceName(); + //await niagaraDataSynchronizeRepository.InsertBuildingMenu(); + //await niagaraDataSynchronizeRepository.InsertSubSystemFloor(); await this.DeviceDisasterAsync(); result = true; diff --git a/Backend/Services/Implement/webRequestService.cs b/Backend/Services/Implement/webRequestService.cs index e8ccca6..7219dcd 100644 --- a/Backend/Services/Implement/webRequestService.cs +++ b/Backend/Services/Implement/webRequestService.cs @@ -331,62 +331,113 @@ namespace Backend.Services.Implement public List obixDevDisaster(string urlString, string bql, string tag_quantity, string acc, string pass, string dt) { List result = new List(); - //String username = "obixUser"; - //String password = "Admin123456"; - String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(acc + ":" + pass)); - String API_Url = urlString; - - HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url); - Postrequest.Method = "POST"; - Postrequest.Headers.Add("Authorization", "Basic " + encoded); - Postrequest.PreAuthenticate = true; - - using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream())) + try { - string json = ""; + //String username = "obixUser"; + //String password = "Admin123456"; + String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(acc + ":" + pass)); + String API_Url = urlString; - streamWriter.Write(json); - } + HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url); + Postrequest.Method = "POST"; + Postrequest.Headers.Add("Authorization", "Basic " + encoded); + Postrequest.PreAuthenticate = true; - HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse(); - var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); - - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(responseString); - - string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); - var data = Welcome.FromJson(jsonText); - - if (data.Obj.Str != null) - { - foreach (var item in data.Obj.Str) - { - Device_value_disaster row = new Device_value_disaster(); - row.value = item.Val; - string[] s1 = item.Val.Split(','); - string[] s2 = s1[0].Split('/'); - row.tag_name = ""; - row.disasterValue = dt; - - for (int i = 0; i < s2.Length; i++) + using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream())) { - if (i == s2.Length - 2) + string json = ""; + + streamWriter.Write(json); + } + + HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse(); + var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); + + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(responseString); + + string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); + bool welcome = false; + try + { + Welcome.FromJson(jsonText); + welcome = true; + } + catch + { + + } + + if (welcome) + { + var data = Welcome.FromJson(jsonText); + if (data.Obj.Str != null) { - row.point_name = s2[i]; - } - else if (i == 1) - { - row.tag_name += s2[i]; - } - else if (i > 1 && i < s2.Length - 2) - { - row.tag_name += "_" + s2[i].Replace("$3", ""); + foreach (var item in data.Obj.Str) + { + Device_value_disaster row = new Device_value_disaster(); + row.value = item.Val; + string[] s1 = item.Val.Split(','); + string[] s2 = s1[0].Split('/'); + row.tag_name = ""; + row.disasterValue = dt; + + for (int i = 0; i < s2.Length; i++) + { + if (i == s2.Length - 2) + { + row.point_name = s2[i]; + } + else if (i == 1) + { + row.tag_name += s2[i]; + } + else if (i > 1 && i < s2.Length - 2) + { + row.tag_name += "_" + s2[i].Replace("$3", ""); + } + } + result.Add(row); + } } } - result.Add(row); - } - } + else + { + var data = WelcomeSingle.FromJson(jsonText); + if (data.Obj.Str != null) + { + var item = data.Obj.Str; + Device_value_disaster row = new Device_value_disaster(); + row.value = item.Val; + string[] s1 = item.Val.Split(','); + string[] s2 = s1[0].Split('/'); + row.tag_name = ""; + row.disasterValue = dt; + + for (int i = 0; i < s2.Length; i++) + { + if (i == s2.Length - 2) + { + row.point_name = s2[i]; + } + else if (i == 1) + { + row.tag_name += s2[i]; + } + else if (i > 1 && i < s2.Length - 2) + { + row.tag_name += "_" + s2[i].Replace("$3", ""); + } + } + result.Add(row); + } + } + } + catch(Exception e) + { + var a = e; + } return result; } diff --git a/Backend/appsettings.Development.json b/Backend/appsettings.Development.json index b5af96e..83cd09a 100644 --- a/Backend/appsettings.Development.json +++ b/Backend/appsettings.Development.json @@ -18,10 +18,10 @@ "Port": "js2LutKe+rdjzdxMPQUrvQ==", //"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30 //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp - //"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome + "Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome //"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel //"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office - "Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut + //"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut "Root": "SzdxEgaJJ7tcTCrUl2zKsA==", "Password": "FVAPxztxpY4gJJKQ/se4bQ==" }, diff --git a/FrontendWebApi/ApiControllers/HydroMeterController.cs b/FrontendWebApi/ApiControllers/HydroMeterController.cs index 07d2ed2..baa6388 100644 --- a/FrontendWebApi/ApiControllers/HydroMeterController.cs +++ b/FrontendWebApi/ApiControllers/HydroMeterController.cs @@ -1,6 +1,7 @@ using FrontendWebApi.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; +using MySqlX.XDevAPI; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using Repository.BackendRepository.Interface; @@ -100,6 +101,15 @@ namespace FrontendWebApi.ApiControllers sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp "; var table = input.tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + input.tableType + (input.tableType == "day" ? "_" + dbDateName : ""); + var schema = await backendRepository.GetOneAsync($"select system_value from variable where system_type = 'project_name'"); + var isTable = await backendRepository.GetOneAsync($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'"); + if (string.IsNullOrEmpty(isTable)) //check for has table or not + { + apiResult.Code = "0000"; + apiResult.Data = new List() { }; + return Ok(apiResult); + } + var dateFormat = input.tableType == "day" || input.tableType == "week" ? "%Y-%m-%d" : input.tableType == "month" ? "%Y-%m" : input.tableType == "year" ? "%Y" : null; var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})"; var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date"; @@ -262,7 +272,18 @@ namespace FrontendWebApi.ApiControllers sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp "; var table = input.tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + input.tableType + (input.tableType == "day" ? "_" + dbDateName : ""); + var schema = await backendRepository.GetOneAsync($"select system_value from variable where system_type = 'project_name'"); + var isTable = await backendRepository.GetOneAsync($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'"); + if (string.IsNullOrEmpty(isTable)) //check for has table or not + { + apiResult.Code = "0000"; + apiResult.Data = new List() { }; + return Ok(apiResult); + } + var dateFormat = input.tableType == "day" || input.tableType == "week" ? "%Y-%m-%d" : input.tableType == "month" ? "%Y-%m" : input.tableType == "year" ? "%Y" : null; + var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})"; + var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date"; var sql = $@"set @i = -1; select fd.device_number, aemm.avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp from ( @@ -285,7 +306,7 @@ namespace FrontendWebApi.ApiControllers left join ( select device_number, {sqlAvgRawData} from {table} - where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'RCV' {buildingSql} + where start_timestamp >= {aemmStaDate} and end_timestamp < {aemmEndDate} and point = 'RCV' {buildingSql} {sqlWhere} {sqlGroup} ) aemm on aemm.start_timestamp >= fd.date and aemm.end_timestamp < DATE_ADD(fd.date, INTERVAL +1 {input.tableType}) and aemm.device_number = fd.device_number order by fd.device_number, fd.date"; diff --git a/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs b/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs index 8ffba7b..7fe8a27 100644 --- a/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs +++ b/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs @@ -12,6 +12,7 @@ using Repository.Models; using System.Data.SqlTypes; using Microsoft.Extensions.Primitives; using System.Web; +using Org.BouncyCastle.Utilities.Collections; namespace Repository.BackendRepository.Implement { @@ -864,26 +865,28 @@ namespace Repository.BackendRepository.Implement using (IDbConnection conn = GetDbConnection()) { conn.Open(); - using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled, new TimeSpan(0, 5, 0))) { try { StringBuilder sb = new StringBuilder(); - sb.Append("select * from device_disaster"); + sb.Append("select * from device_disaster;"); var deviceDisaster = (await conn.QueryAsync(sb.ToString())).ToList(); sb.Clear(); - sb.Append("select * from device where deleted = 0"); + sb.Append("select * from device where deleted = 0;"); var device = (await conn.QueryAsync(sb.ToString())).ToList(); dv = dv.Where(x => device.Any(d => d.device_number == x.value.Split('/')[6])).ToList(); sb.Clear(); - foreach (var d in dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6]))) + var updateList = dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6] && dd.device_system_value != x.disasterValue)); + foreach (var d in updateList) { string device_number = d.value.Split('/')[6]; sb.Append($"update device_disaster set device_system_value = '{d.disasterValue}' where device_number = '{device_number}'; "); } - foreach (var d in dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6]))) + var insertList = dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6])); + foreach (var d in insertList) { string device_number = d.value.Split('/')[6]; string device_guid = device.Where(x => x.device_number == device_number).Select(x => x.device_guid).FirstOrDefault(); @@ -892,8 +895,8 @@ namespace Repository.BackendRepository.Implement sb.Append($@" insert into device_disaster (device_guid, device_system_value, device_building_tag, device_system_tag, device_name_tag, device_floor_tag, device_serial_tag, device_number) - values ({device_guid}, {d.disasterValue}, {device_number.Split('_')[0]}, {device_number.Split('_')[1]}, {device_system_tag}, {device_name_tag}, - {device_number.Split('_')[2]}, {device_number.Split('_')[4]}, {device_number}); "); + values ('{device_guid}', '{d.disasterValue}', '{device_number.Split('_')[0]}', '{device_system_tag}', '{device_name_tag}', '{device_number.Split('_')[2]}', + '{device_number.Split('_')[4]}', '{device_number}'); "); } if (!string.IsNullOrEmpty(sb.ToString())) diff --git a/Repository/Models/BackgroundServiceTask.cs b/Repository/Models/BackgroundServiceTask.cs index c049778..d806dad 100644 --- a/Repository/Models/BackgroundServiceTask.cs +++ b/Repository/Models/BackgroundServiceTask.cs @@ -141,6 +141,7 @@ namespace Repository.Models public string device_floor_tag { get; set; } public string device_serial_tag { get; set; } public string device_number { get; set; } + public string device_system_value { get; set; } } public class Device_value_disaster diff --git a/Repository/Models/quickType.cs b/Repository/Models/quickType.cs index 13eb593..d215aef 100644 --- a/Repository/Models/quickType.cs +++ b/Repository/Models/quickType.cs @@ -20,11 +20,6 @@ namespace Repository.Models public partial class Obj { - [JsonProperty("@href")] - public string? href { get; set; } - [JsonProperty("@icon")] - public string? icon { get; set; } - [JsonProperty("@display")] public string Display { get; set; } @@ -38,11 +33,7 @@ namespace Repository.Models public Uri XmlnsXsi { get; set; } [JsonProperty("str")] - public Str[] Str { get; set; } - - [JsonProperty("ref")] - public Str[] Ref { get; set; } - //public Ref Ref { get; set; } + public List Str { get; set; } } public partial class Str @@ -55,25 +46,6 @@ namespace Repository.Models [JsonProperty("@href")] public string Href { get; set; } - [JsonProperty("@display")] - public string display { get; set; } - [JsonProperty("@_icon")] - public string _icon { get; set; } - } - - public class Ref - { - [JsonProperty("_name")] - public string Name { get; set; } - - [JsonProperty("_href")] - public string Href { get; set; } - - [JsonProperty("_display")] - public string Display { get; set; } - - [JsonProperty("_icon")] - public string Icon { get; set; } } public partial class Xml diff --git a/Repository/Models/quickTypeSingle.cs b/Repository/Models/quickTypeSingle.cs new file mode 100644 index 0000000..7c38efe --- /dev/null +++ b/Repository/Models/quickTypeSingle.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Repository.Models +{ + public partial class WelcomeSingle + { + [JsonProperty("?xml")] + public XmlSingle Xml { get; set; } + + [JsonProperty("?xml-stylesheet")] + public string XmlStylesheet { get; set; } + + [JsonProperty("obj")] + public ObjSingle Obj { get; set; } + } + + public partial class ObjSingle + { + [JsonProperty("@display")] + public string Display { get; set; } + + [JsonProperty("@xmlns")] + public Uri Xmlns { get; set; } + + [JsonProperty("@xsi:schemaLocation")] + public Uri XsiSchemaLocation { get; set; } + + [JsonProperty("@xmlns:xsi")] + public Uri XmlnsXsi { get; set; } + + [JsonProperty("str")] + public Str Str { get; set; } + } + + public partial class StrSingle + { + [JsonProperty("@name")] + public string Name { get; set; } + + [JsonProperty("@val")] + public string Val { get; set; } + + [JsonProperty("@href")] + public string Href { get; set; } + } + + public partial class XmlSingle + { + [JsonProperty("@version")] + public string Version { get; set; } + + [JsonProperty("@encoding")] + public string Encoding { get; set; } + } + + public partial class WelcomeSingle + { + public static WelcomeSingle FromJson(string json) => JsonConvert.DeserializeObject(json, Models.ConverterSingle.Settings); + } + + public static class SerializeSingle + { + public static string ToJson(this WelcomeSingle self) => JsonConvert.SerializeObject(self, Models.ConverterSingle.Settings); + } + + internal static class ConverterSingle + { + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings + { + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, + DateParseHandling = DateParseHandling.None, + Converters = + { + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } + }, + }; + } +}