diff --git a/Backend/Controllers/NiagaraDataSynchronizeController.cs b/Backend/Controllers/NiagaraDataSynchronizeController.cs new file mode 100644 index 0000000..5687558 --- /dev/null +++ b/Backend/Controllers/NiagaraDataSynchronizeController.cs @@ -0,0 +1,95 @@ +using Microsoft.AspNetCore.Mvc; +using Repository.BackendRepository.Interface; +using System.Collections.Generic; +using System.Threading.Tasks; +using System; +//using Backend.Models; +using Microsoft.Extensions.Logging; +using Backend.Services; +using Backend.Services.Implement; +using Repository.Models; + +namespace Backend.Controllers +{ + public class NiagaraDataSynchronizeController : MybaseController + { + private readonly IBackendRepository backendRepository; + //private readonly IDeviceImportRepository deviceImportRepository; + private readonly INiagaraDataSynchronizeRepository niagaraDataSynchronizeRepository; + public NiagaraDataSynchronizeController(IBackendRepository backendRepository, INiagaraDataSynchronizeRepository niagaraDataSynchronizeRepository) + { + this.backendRepository = backendRepository; + //this.deviceImportRepository = deviceImportRepository; + this.niagaraDataSynchronizeRepository = niagaraDataSynchronizeRepository; + } + + public IActionResult Index() + { + return View(); + } + + /// + /// N4匯入列表 + /// + /// + [HttpPost] + public Task>> RawDataList() + { + ApiResult> apiResult = new ApiResult>(); + + try + { + List ds; + string url_slot = "slot:/Arena/H|"; + string top100 = " top 100 "; + webRequestService svc = new webRequestService(); + string bql = url_slot + "bql:select " + top100 + " * from control:ControlPoint "; + ds = svc.obixQuery("http://60.251.164.125:8080/obix/config/Arena/Program/ObixQuery/query/", bql); + + apiResult.Code = "0000"; + apiResult.Data = ds; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + + //return apiResult; + return Task.FromResult(apiResult); + } + + /// + /// 比對N4與資料表,有差異在同步至資料表中 + /// + /// + [HttpPost] + public async Task> CompareData(List ds, string building) + { + bool result = false; + ApiResult apiResult = new ApiResult(); + try + { + + await niagaraDataSynchronizeRepository.InsertNiagaraTagList(ds, building); + await niagaraDataSynchronizeRepository.InsertItemFromNiagara(ds, building); + await niagaraDataSynchronizeRepository.DeviceComparison(); + await niagaraDataSynchronizeRepository.DeviceItemComparison(); + await niagaraDataSynchronizeRepository.InsertBuildingMenu(); + await niagaraDataSynchronizeRepository.InsertSubSystemFloor(); + result = true; + + apiResult.Code = "0000"; + apiResult.Data = result; + } + catch (Exception exception) + { + apiResult.Code = "9999"; + Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + + return apiResult; + } + + } +} diff --git a/Backend/N4.xml b/Backend/N4.xml new file mode 100644 index 0000000..2764606 --- /dev/null +++ b/Backend/N4.xml @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Backend/Services/Implement/webRequestService.cs b/Backend/Services/Implement/webRequestService.cs new file mode 100644 index 0000000..aa56566 --- /dev/null +++ b/Backend/Services/Implement/webRequestService.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Xml; +using Newtonsoft.Json; +using Repository.Models; +using Newtonsoft.Json.Linq; +using System.IO; +using System.Net; +using System.Text; +using System.Xml.Linq; +using Repository.BackendRepository.Implement; +using Repository.BackendRepository; + +namespace Backend.Services.Implement +{ + public class webRequestService + { + public List obixQuery(string urlString, string bql) + { + List result = new List(); + String username = "obixUser"; + String password = "Admin123456"; + String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); + String API_Url = urlString; + + XmlDocument xmlDoc = new XmlDocument(); + //xmlDoc.LoadXml(responseString); + xmlDoc.Load("N4.xml");//N4v1021 + + //xmlDoc.Save("N4.xml"); + + string jsonText = JsonConvert.SerializeXmlNode(xmlDoc); + var data = Welcome.FromJson(jsonText); + + foreach (var item in data.Obj.Str) + { + Device_value row = new Device_value(); + row.value = item.Val; + string[] s1 = item.Val.Split(','); + + string[] s2 = s1[0].Split('/'); + foreach (var ss in s2) + { + if (ss.Contains('_')) + { + string[] s3 = ss.Split('_'); + if (s3.Count() > 3) + { + row.tag_name = ss; + row.point_name = s2[s2.Length - 2]; + break; + } + } + } + result.Add(row); + + } + return result; + } + + //public void getObix() + //{ + // //#region 取得obix 設定 + // //var obixApiConfig = new ObixApiConfig(); + + // //var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; + + // //var variableObix = await backgroundServiceRepository.GetAllAsync(sqlObix); + // //obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); + // //obixApiConfig.UserName = ed.AESDecrypt(variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault()); + // //obixApiConfig.Password = ed.AESDecrypt(variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault()); + + // //String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password)); + // //#endregion 取得obix 設定 + + + // HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/FIC_Center/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); + // //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/FIC_Center/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); + // archiveMonthRequest.Method = "POST"; + // archiveMonthRequest.Headers.Add("Authorization", "Basic " + encoded); + // archiveMonthRequest.PreAuthenticate = true; + + // byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter); + // using (Stream reqStream = archiveMonthRequest.GetRequestStream()) + // { + // reqStream.Write(byteArray, 0, byteArray.Length); + // } + + // HttpWebResponse archiveMonthResponse = (HttpWebResponse)archiveMonthRequest.GetResponse(); + // var archiveMonthResponseContent = new StreamReader(archiveMonthResponse.GetResponseStream()).ReadToEnd(); + + // xmlDocument.LoadXml(archiveMonthResponseContent); + // string archiveMonthJson = JsonConvert.SerializeXmlNode(xmlDocument); + // JObject archiveMonthJsonResult = (JObject)JsonConvert.DeserializeObject(archiveMonthJson); + + // if (archiveMonthJsonResult.ContainsKey("err")) //抓取錯誤 + // { + // //logger.LogError("【ArchiveElectricMeterDayJob】【月歸檔】【取得資料失敗】"); + // //logger.LogError("【ArchiveElectricMeterDayJob】【月歸檔】【取得資料失敗】[錯誤內容]:{0}", archiveMonthJsonResult); + + // Dictionary archiveMonthRawData = new Dictionary(); + // archiveMonthRawData.Add("@device_number", deviceNumberPoint.DeviceNumber); + // archiveMonthRawData.Add("@point", deviceNumberPoint.Point); + // archiveMonthRawData.Add("@start_timestamp", startTimestamp.Replace("T", " ").Substring(0, 19)); + // archiveMonthRawData.Add("@end_timestamp", endTimestamp.Replace("T", " ").Substring(0, 19)); + // archiveMonthRawData.Add("@is_complete", 0); + // archiveMonthRawData.Add("@repeat_times", 0); + // archiveMonthRawData.Add("@fail_reason", archiveMonthJson); + + // archiveMonthRawData.Add("@count_rawdata", 0); + // archiveMonthRawData.Add("@min_rawdata", 0); + // archiveMonthRawData.Add("@max_rawdata", 0); + // archiveMonthRawData.Add("@avg_rawdata", 0); + // archiveMonthRawData.Add("@sum_rawdata", 0); + // archiveMonthRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); + + // archiveMonthRawDatas.Add(archiveMonthRawData); + // } + + // if (archiveMonthJsonResult.ContainsKey("obj")) //表示可以讀取到內容 + // { + // var ArrangeRawDatas = ArrangeRawData(deviceNumberPoint, archiveMonthJsonResult); + // if (ArrangeRawDatas != null && ArrangeRawDatas.Count() > 0) + // { + // archiveMonthRawDatas.AddRange(ArrangeRawDatas); + // } + // } + //} + } +} diff --git a/Backend/Startup.cs b/Backend/Startup.cs index f1f29ac..53a99f0 100644 --- a/Backend/Startup.cs +++ b/Backend/Startup.cs @@ -95,6 +95,7 @@ namespace Backend services.AddTransient(); services.AddTransient(); services.AddTransient(); + services.AddTransient(); #endregion Repository `J #region JWT `J diff --git a/Backend/Views/NiagaraDataSynchronize/Index.cshtml b/Backend/Views/NiagaraDataSynchronize/Index.cshtml new file mode 100644 index 0000000..ac25e57 --- /dev/null +++ b/Backend/Views/NiagaraDataSynchronize/Index.cshtml @@ -0,0 +1,168 @@ +@{ + ViewData["MainNum"] = "2"; + ViewData["SubNum"] = "3"; + ViewData["Title"] = "Niagara資料同步"; +} + + + +
+
+
+
+
+ +
+
+
+ + +
+ @*
+ + +
*@ +
+
+ +
+ + +
+ +
+
+ +
+

+
+ +
+
+
+
+ Niagara資料 +
+
+
+
+ + + + + + + + + + + +
valuetag_namepoint_name
+
+
+
+
+ +
+
+
+
+
+ +@section Scripts { + +} \ No newline at end of file diff --git a/Backend/Views/Shared/_Layout.cshtml b/Backend/Views/Shared/_Layout.cshtml index 47f35ad..3092ef9 100644 --- a/Backend/Views/Shared/_Layout.cshtml +++ b/Backend/Views/Shared/_Layout.cshtml @@ -112,7 +112,7 @@ } - @if (ViewBag.role.Contains("DeviceImportIndex") || ViewBag.role.Contains("DeviceManageIndex")) + @if (ViewBag.role.Contains("DeviceImportIndex") || ViewBag.role.Contains("DeviceManageIndex") || ViewBag.role.Contains("NiagaraDataSynchronizeIndex")) {
  • @@ -136,6 +136,14 @@
  • } + @if (ViewBag.role.Contains("NiagaraDataSynchronizeIndex")) + { +
  • + + Niagara資料同步 + +
  • + } } diff --git a/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs b/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs new file mode 100644 index 0000000..dc135f5 --- /dev/null +++ b/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs @@ -0,0 +1,507 @@ +using Dapper; +using Repository.BackendRepository.Interface; +using Repository.Helper; +using System; +using System.Text; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Threading.Tasks; +using System.Transactions; +using Repository.Models; + + +namespace Repository.BackendRepository.Implement +{ + public class NiagaraDataSynchronizeRepository : BackendRepository, INiagaraDataSynchronizeRepository + { + public NiagaraDataSynchronizeRepository(IDatabaseHelper databaseHelper) : base(databaseHelper) + { + } + + /// + /// 更新import_niagara_tag資料表 + /// + /// + /// + /// + public async Task InsertNiagaraTagList(List ds, string building) + { + using (IDbConnection conn = GetDbConnection()) + { + conn.Open(); + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + try + { + string sql = @"CREATE TABLE IF NOT EXISTS `import_niagara_tag` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `db_tags` varchar(50) DEFAULT NULL, + `niagara_tags` varchar(50) DEFAULT NULL, + `device_area_tag` varchar(50) DEFAULT NULL, + `device_building_tag` varchar(50) DEFAULT NULL, + `device_system_tag` varchar(50) DEFAULT NULL, + `device_name_tag` varchar(50) DEFAULT NULL, + `device_floor_tag` varchar(50) DEFAULT NULL, + `device_master_tag` varchar(50) DEFAULT NULL, + `device_last_name_tag` varchar(50) DEFAULT NULL, + `device_serial_tag` varchar(50) DEFAULT NULL, + `atDateTime` datetime(1) DEFAULT NULL, + `is_used` smallint(1) DEFAULT 0, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"; + await conn.ExecuteAsync(sql); + sql = "delete from import_niagara_tag where device_building_tag = '" + building + "'"; + await conn.ExecuteAsync(sql); + + //N4資料groupBy後放入import_niagara_tag資料表 + var ds2 = ds.GroupBy(x => new + { + tag_name2 = x.tag_name + }).Select(x => new Device_value + { + tag_name = x.Key.tag_name2 + }); + + StringBuilder sb = new StringBuilder(); + + foreach (var row in ds2) + { + if (string.IsNullOrEmpty(row.tag_name)) continue; + string[] arrTag = row.tag_name.Split('_'); + + sb.Append($@" insert import_niagara_tag(niagara_tags, device_area_tag, device_building_tag, device_system_tag, + device_name_tag, device_floor_tag, device_master_tag, device_last_name_tag, device_serial_tag, atDateTime) values('" + + row.tag_name + "', '" + + arrTag[0] + "', '" + + arrTag[1] + "', '" + + arrTag[2] + "', '" + + arrTag[3] + "', '" + + arrTag[4] + "', '" + + arrTag[5] + "', '" + + arrTag[6] + "', '" + + arrTag[7] + "', " + + "now());"); + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + } + } + catch (Exception exception) + { + throw exception; + } + finally + { + conn.Close(); + } + } + } + } + + /// + /// 更新import_niagara_tag資料表 + /// + /// + /// + /// + public async Task InsertItemFromNiagara(List ds, string building) + { + using (IDbConnection conn = GetDbConnection()) + { + conn.Open(); + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + try + { + #region 刪除 import_niagara_item資料表中選取的棟別 + string sql = @"CREATE TABLE IF NOT EXISTS `import_niagara_item` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `device_area_tag` varchar(50) DEFAULT NULL, + `device_building_tag` varchar(50) DEFAULT NULL, + `device_system_tag` varchar(50) DEFAULT NULL, + `device_name_tag` varchar(50) DEFAULT NULL, + `device_point_name` varchar(50) DEFAULT NULL, + `check_status` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"; + await conn.ExecuteAsync(sql); + sql = "delete from import_niagara_item where device_building_tag = '" + building + "'"; + await conn.ExecuteAsync(sql); + #endregion + + List dt_item = new List(); + + foreach (var row in ds) + { + if (string.IsNullOrEmpty(row.tag_name)) continue; + string[] arrTag = row.tag_name.Split('_'); + + #region for item + Device_item8 row_item = new Device_item8(); + row_item.tag_name = row.tag_name; + row_item.device_area_tag = arrTag[0]; + row_item.device_building_tag = arrTag[1]; + row_item.device_system_tag = arrTag[2]; + row_item.device_name_tag = arrTag[3]; + row_item.device_floor_tag = arrTag[4]; + row_item.device_master_tag = arrTag[5]; + row_item.device_last_name_tag = arrTag[6]; + row_item.device_serial_tag = arrTag[7]; + row_item.point_name = row.point_name; + dt_item.Add(row_item); + #endregion + } + + #region N4資料groupBy後放入import_niagara_item資料表 + var ds2_item = dt_item.GroupBy(x => new + { + device_area_tag2 = x.device_area_tag, + device_building_tag2 = x.device_building_tag, + device_system_tag2 = x.device_system_tag, + device_name_tag2 = x.device_name_tag, + point_name2 = x.point_name + }).Select(x => new Device_item8 + { + device_area_tag = x.Key.device_area_tag2, + device_building_tag = x.Key.device_building_tag2, + device_system_tag = x.Key.device_system_tag2, + device_name_tag = x.Key.device_name_tag2, + point_name = x.Key.point_name2 + }); + + StringBuilder sb = new StringBuilder(); + + foreach (var row2 in ds2_item) + { + sb.Append($@" insert import_niagara_item(device_area_tag, device_building_tag, device_system_tag, device_name_tag, device_point_name) + values('" + + row2.device_area_tag + "', '" + + row2.device_building_tag + "', '" + + row2.device_system_tag + "', '" + + row2.device_name_tag + "', '" + + row2.point_name + "'" + + ");"); + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + } + #endregion + } + catch (Exception exception) + { + throw exception; + } + finally + { + conn.Close(); + } + } + } + } + /// + /// 比對 device + /// + /// + public async Task DeviceComparison() + { + using (IDbConnection conn = GetDbConnection()) + { + conn.Open(); + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + try + { + List result; + StringBuilder sb = new StringBuilder(); + StringBuilder sb2 = new StringBuilder(); + sb.Append($@" SELECT m.* + FROM import_niagara_tag m + LEFT JOIN device d + ON m.niagara_tags = d.device_number + WHERE d.device_number IS NULL"); + result = (await conn.QueryAsync(sb.ToString())).ToList(); + + sb.Clear(); + //新增至device, is_link = 1 + if (result.Count > 0) + { + foreach (var data in result) + { + sb.Append($@" insert device(device_guid, deleted, status, priority, is_link, device_area_tag, + device_building_tag, device_system_tag, device_name_tag, device_floor_tag, device_master, + device_last_name, device_serial_tag, device_number, device_system_category_layer3, created_at, updated_at) + values(uuid(), 0, 1, 0, 1, '" + + data.device_area_tag + "', '" + + data.device_building_tag + "', '" + + data.device_system_tag + "', '" + + data.device_name_tag + "', '" + + + data.device_floor_tag + "', '" + + data.device_master_tag + "', '" + + data.device_last_name_tag + "', '" + + data.device_serial_tag + "', '" + + data.niagara_tags + "', '" + + data.device_system_tag + "', now(), now() );"); + + sb2.Append($@"INSERT device_kind (device_kind_guid, device_building_tag, device_system_tag, device_name_tag, + device_normal_flashing, device_close_flashing, device_error_flashing, device_error_independent, + created_by, created_at) + VALUES (uuid(), '" + data.device_building_tag + "', '" + data.device_system_tag + "', '" + data.device_name_tag + + "', 0, 0, 1, 0, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now());"); + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + await conn.ExecuteAsync(sb2.ToString()); + sb.Clear(); + sb2.Clear(); + } + } + + //device有,niagara沒有,is_link 更新成 0 + sb.Append($@" SET SQL_SAFE_UPDATES = 0; + UPDATE device d LEFT JOIN import_niagara_tag m ON d.device_number = m.niagara_tags + SET d.is_link = 0 + WHERE m.niagara_tags IS NULL"); + await conn.ExecuteAsync(sb.ToString()); + + } + catch (Exception exception) + { + throw exception; + } + finally + { + conn.Close(); + } + } + } + } + + /// + /// 比對 device_item + /// + /// + public async Task DeviceItemComparison() + { + using (IDbConnection conn = GetDbConnection()) + { + conn.Open(); + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + try + { + List result; + StringBuilder sb = new StringBuilder(); + sb.Append($@" SELECT m.* + FROM import_niagara_item m + LEFT JOIN device_item d + ON m.device_system_tag = d.device_system_tag and m.device_name_tag = d.device_name_tag and m.device_point_name = d.points + WHERE d.points IS NULL"); + result = (await conn.QueryAsync(sb.ToString())).ToList(); + + sb.Clear(); + //新增至device, is_link = 1 + if (result.Count > 0) + { + foreach (var data in result) + { + var isControll = 0; + var isBool = 0; + if (data.device_point_name == "ER" || data.device_point_name == "AL" || data.device_point_name == "ST") + { + isControll = 1; + } + if (data.device_point_name == "ER" || data.device_point_name == "ST") + { + isBool = 1; + } + sb.Append($@"insert device_item(deleted, points, is_show, is_show_riserDiagram, is_controll, is_bool, is_link, + device_system_tag, device_name_tag, created_at, updated_at) + VALUES (0, '" + + data.device_point_name + "', 1, 0, " + + isControll + "," + + isBool + ", 1, '" + + data.device_system_tag + "', '" + + data.device_name_tag + "', " + + "now(), now());"); + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + } + } + //device有,niagara沒有,is_link 更新成 0 + sb.Append($@" SET SQL_SAFE_UPDATES = 0; + UPDATE device_item d LEFT JOIN import_niagara_item m + ON d.device_system_tag = m.device_system_tag and d.device_name_tag = m.device_name_tag and d.points = m.device_point_name + SET d.is_link = 0 + WHERE m.device_point_name IS NULL"); + await conn.ExecuteAsync(sb.ToString()); + } + catch (Exception exception) + { + throw exception; + } + finally + { + conn.Close(); + } + } + } + } + + /// + /// 新增資料至 buildingMenu + /// + /// + public async Task InsertBuildingMenu() + { + using (IDbConnection conn = GetDbConnection()) + { + conn.Open(); + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + try + { + List result; + StringBuilder sb = new StringBuilder(); + #region comparison building_menu and import_niagara_tag + sb.Append($@" select a.* from ( + select device_building_tag, device_system_tag, device_name_tag + from import_niagara_tag + group by device_building_tag, device_system_tag, device_name_tag + ) AS a + LEFT JOIN building_menu b + ON a.device_building_tag = b.device_building_tag and a.device_system_tag = b.device_system_tag and a.device_name_tag = b.sub_system_tag + WHERE b.device_building_tag IS NULL"); + result = (await conn.QueryAsync(sb.ToString())).ToList(); + #endregion + sb.Clear(); + + if (result.Count > 0) + { + foreach (var data in result) + { + #region insert building_menu + sb.Append(@"insert building_menu(building_tag, main_system_tag, sub_system_tag, device_building_tag, device_system_tag, + is_link, created_by, created_at, updated_by, updated_at) + VALUES ('" + data.device_building_tag + "', '" + + data.device_system_tag + "', '" + + data.device_name_tag + "', '" + + data.device_building_tag + "', '" + + data.device_system_tag + "', " + + "1, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now(), 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now() );"); + #endregion + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + } + } + //building_menu有,import_niagara_tag沒有,is_link 更新成 0 + sb.Append($@" SET SQL_SAFE_UPDATES = 0; + UPDATE building_menu b LEFT JOIN ( + select device_building_tag, device_system_tag, device_name_tag + from import_niagara_tag + group by device_building_tag, device_system_tag, device_name_tag + ) AS a ON b.device_building_tag = a.device_building_tag + and a.device_system_tag = b.device_system_tag and a.device_name_tag = b.sub_system_tag + SET b.is_link = 0 + WHERE b.device_building_tag IS NULL"); + await conn.ExecuteAsync(sb.ToString()); + } + catch (Exception exception) + { + throw exception; + } + finally + { + conn.Close(); + } + } + } + } + + /// + /// 新增資料至 subSystemFloor + /// + /// + public async Task InsertSubSystemFloor() + { + using (IDbConnection conn = GetDbConnection()) + { + conn.Open(); + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + try + { + List result; + StringBuilder sb = new StringBuilder(); + #region comparison sub_system_floor and import_niagara_tag + sb.Append($@" select a.* from ( + select device_building_tag, device_system_tag, device_name_tag, device_floor_tag + from import_niagara_tag + group by device_building_tag, device_system_tag, device_name_tag, device_floor_tag + ) AS a + LEFT JOIN sub_system_floor b + ON a.device_building_tag = b.building_tag and a.device_system_tag = b.main_system_tag and a.device_name_tag = b.sub_system_tag and a.device_floor_tag = b.floor_tag + WHERE b.building_tag IS NULL"); + result = (await conn.QueryAsync(sb.ToString())).ToList(); + #endregion + + sb.Clear(); + if (result.Count > 0) + { + foreach (var data in result) + { + #region insert building_menu + sb.Append(@"insert sub_system_floor(building_tag, main_system_tag, sub_system_tag, floor_tag, + is_link, created_by, created_at, updated_by, updated_at) + VALUES ('" + + data.device_building_tag + "', '" + + data.device_system_tag + "', '" + + data.device_name_tag + "', '" + + data.device_floor_tag + "', " + + "1, 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now(), 'B43E3CA7-96DD-4FC7-B6E6-974ACC3B0878', now());"); + #endregion + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + } + } + //building_menu有,import_niagara_tag沒有,is_link 更新成 0 + sb.Append($@" SET SQL_SAFE_UPDATES = 0; + UPDATE sub_system_floor b LEFT JOIN ( + select device_building_tag, device_system_tag, device_name_tag, device_floor_tag + from import_niagara_tag + group by device_building_tag, device_system_tag, device_name_tag, device_floor_tag + ) AS a ON b.building_tag = a.device_building_tag + and b.main_system_tag = a.device_system_tag and b.sub_system_tag = a.device_name_tag and b.floor_tag = a.device_floor_tag + SET b.is_link = 0 + WHERE b.building_tag IS NULL"); + await conn.ExecuteAsync(sb.ToString()); + } + catch (Exception exception) + { + throw exception; + } + finally + { + conn.Close(); + } + } + } + } + + } +} diff --git a/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs b/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs new file mode 100644 index 0000000..fdcead3 --- /dev/null +++ b/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs @@ -0,0 +1,44 @@ +using System.Collections.Generic; +using System.Threading.Tasks; +using Repository.Models; + +namespace Repository.BackendRepository.Interface +{ + public interface INiagaraDataSynchronizeRepository : IBackendRepository + { + /// + /// 同步N4至資料表 import_niagara_tag + /// + /// + /// + /// + Task InsertNiagaraTagList(List ds, string building); + /// + /// 同步N4至資料表 import_niagara_item + /// + /// + /// + /// + Task InsertItemFromNiagara(List ds, string building); + /// + /// 比對 device + /// + /// + Task DeviceComparison(); + /// + /// 比對 device_item + /// + /// + Task DeviceItemComparison(); + /// + /// 新增資料至 buildingMenu + /// + /// + Task InsertBuildingMenu(); + /// + /// 新增資料至 subSystemFloor + /// + /// + Task InsertSubSystemFloor(); + } +} diff --git a/Repository/Models/BackgroundServiceTask.cs b/Repository/Models/BackgroundServiceTask.cs index 920fbbf..fafd4d4 100644 --- a/Repository/Models/BackgroundServiceTask.cs +++ b/Repository/Models/BackgroundServiceTask.cs @@ -37,4 +37,60 @@ namespace Repository.Models public string FileName { get; set; } public string File { get; set; } } + + /// + /// 取得niagara資料 + /// + public class Device_value + { + public string name { get; set; } + public string value { get; set; } + public string tag_name { get; set; } + public string point_name { get; set; } + } + + public class Device_item8 + { + public string name { get; set; } + public string value { get; set; } + public string tag_name { get; set; } + public string device_area_tag { get; set; } + public string device_building_tag { get; set; } + public string device_system_tag { get; set; } + public string device_name_tag { get; set; } + public string device_floor_tag { get; set; } + public string device_master_tag { get; set; } + public string device_last_name_tag { get; set; } + public string device_serial_tag { get; set; } + public string point_name { get; set; } + + //public string result_value { get; set; } + } + + public class NiagaraTags + { + public int id { get; set; } + public string db_tags { get; set; } + public string niagara_tags { get; set; } + public string device_area_tag { get; set; } + public string device_building_tag { get; set; } + public string device_system_tag { get; set; } + public string device_name_tag { get; set; } + public string device_floor_tag { get; set; } + public string device_master_tag { get; set; } + public string device_last_name_tag { get; set; } + public string device_serial_tag { get; set; } + public string atDateTime { get; set; } + public int is_used { get; set; } + } + + public class NiagaraTagsForItem + { + public string device_area_tag { get; set; } + public string device_building_tag { get; set; } + public string device_system_tag { get; set; } + public string device_name_tag { get; set; } + public string device_point_name { get; set; } + } + } diff --git a/Repository/Models/quickType.cs b/Repository/Models/quickType.cs new file mode 100644 index 0000000..226c03d --- /dev/null +++ b/Repository/Models/quickType.cs @@ -0,0 +1,81 @@ +using System; +using System.Globalization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; + +namespace Repository.Models +{ + public partial class Welcome + { + [JsonProperty("?xml")] + public Xml Xml { get; set; } + + [JsonProperty("?xml-stylesheet")] + public string XmlStylesheet { get; set; } + + [JsonProperty("obj")] + public Obj Obj { get; set; } + } + + public partial class Obj + { + [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 Str + { + [JsonProperty("@name")] + public string Name { get; set; } + + [JsonProperty("@val")] + public string Val { get; set; } + + [JsonProperty("@href")] + public string Href { get; set; } + } + + public partial class Xml + { + [JsonProperty("@version")] + public string Version { get; set; } + + [JsonProperty("@encoding")] + public string Encoding { get; set; } + } + + public partial class Welcome + { + public static Welcome FromJson(string json) => JsonConvert.DeserializeObject(json, Models.Converter.Settings); + } + + public static class Serialize + { + public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Models.Converter.Settings); + } + + internal static class Converter + { + public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings + { + MetadataPropertyHandling = MetadataPropertyHandling.Ignore, + DateParseHandling = DateParseHandling.None, + Converters = + { + new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal } + }, + }; + } +}