diff --git a/Backend/Controllers/BuildMenuController.cs b/Backend/Controllers/BuildMenuController.cs index dcdac30..3609530 100644 --- a/Backend/Controllers/BuildMenuController.cs +++ b/Backend/Controllers/BuildMenuController.cs @@ -153,7 +153,8 @@ namespace Backend.Controllers {"@right_drawing",buildMenu.right_drawing }, {"@created_by",myUserInfo.Userinfo_guid }, {"@left_planimetric_click",buildMenu.left_planimetric_click}, - {"@right_planimetric_click",buildMenu.right_planimetric_click} + {"@right_planimetric_click",buildMenu.right_planimetric_click}, + {"@is_link", 1} }; if (buildMenu.left_drawing == 2) @@ -383,9 +384,9 @@ namespace Backend.Controllers from building_menu bm join variable mv on bm.main_system_tag = mv.system_value and mv.system_type = @main_system_type and mv.deleted = 0 join variable sv on bm.sub_system_tag = sv.system_value and sv.system_type = @sub_system_type and sv.deleted = 0 - join floor lf on lf.floor_guid = bm.left_planimetric_floor_guid - join floor rf on rf.floor_guid = bm.right_planimetric_floor_guid - where bm.building_tag = @building_tag and bm.main_system_tag in @MainList + left join floor lf on lf.floor_guid = bm.left_planimetric_floor_guid + left join floor rf on rf.floor_guid = bm.right_planimetric_floor_guid + where bm.building_tag = @building_tag and bm.main_system_tag in @MainList and bm.is_link > 0 ORDER BY bm.priority, mv.system_priority ASC, sv.system_priority ASC, sv.created_at DESC ", new { building_tag = post.building_tag, MainList = post.MainList, main_system_type = main_system_type, sub_system_type = sub_system_type }); diff --git a/Backend/Controllers/NiagaraDataSynchronizeController.cs b/Backend/Controllers/NiagaraDataSynchronizeController.cs index f85cca4..682f9b4 100644 --- a/Backend/Controllers/NiagaraDataSynchronizeController.cs +++ b/Backend/Controllers/NiagaraDataSynchronizeController.cs @@ -13,6 +13,7 @@ using Microsoft.Extensions.DependencyInjection; using NPOI.SS.Formula.Functions; using Repository.Helper; using Microsoft.AspNetCore.Routing.Matching; +using Newtonsoft.Json; namespace Backend.Controllers { @@ -61,7 +62,7 @@ namespace Backend.Controllers string top100 = "";//" top 100 "; webRequestService svc = new webRequestService(); var urlSlots = backendRepository.GetAllAsync("select obixSlot from building where deleted = 0").Result; - foreach(var us in urlSlots) + foreach (var us in urlSlots) { string bql = us + "bql:select " + top100 + " * from baja:Folder "; //ds = svc.obixQuery("http://192.168.0.136:8080/obix/config/Arena/Program/ObixQuery/query/", bql); @@ -99,7 +100,7 @@ namespace Backend.Controllers string tag_quantity = variableObix.Where(x => x.Name == "tag_quantity").Select(x => x.Value).FirstOrDefault(); try - { + { string ss = ds.Where(x => x.tag_name != "").FirstOrDefault().tag_name; var data = ds.Where(x => x.tag_name != ""); List building = null; @@ -160,15 +161,24 @@ namespace Backend.Controllers obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); obixApiConfig.UserName = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault(); obixApiConfig.Password = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault(); - //obixApiConfig.UrlSlot = variableObix.Where(x => x.Name == "url_slot").Select(x => x.Value).FirstOrDefault(); + obixApiConfig.UrlSlot = variableObix.Where(x => x.Name == "url_slot").Select(x => x.Value).FirstOrDefault(); var urlSlots = backendRepository.GetAllAsync("select obixSlot, area_tag from building where deleted = 0").Result; - foreach(var us in urlSlots) + var data2 = new List(); + foreach (var us in urlSlots) { var data = svc.obixHisQuery(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", us.obixSlot, obixApiConfig.UserName, obixApiConfig.Password, us.area_tag); + + data2.AddRange(svc.obixAllDevicePoint(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", us.obixSlot, + obixApiConfig.UserName, obixApiConfig.Password, us.area_tag)); + ds.AddRange(data); } - + + if (data2.Any()) + { + niagaraDataSynchronizeRepository.DeviceControlPoint(data2); + } var buildings = backendRepository.GetAllAsync("select building_tag from building where deleted = 0").Result; apiResult.Code = "0000"; apiResult.Data = ds.Where(x => buildings.Contains(x.device_building_tag)).ToList(); @@ -192,7 +202,7 @@ namespace Backend.Controllers public async Task> DevIteComData([FromBody] List ds) { bool result = false; - + var oldDs = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(ds)); ApiResult apiResult = new ApiResult(); try { @@ -200,34 +210,34 @@ namespace Backend.Controllers { //string ss = ds.Where(x => x.tag_name != "").FirstOrDefault().tag_name; //var building = ss.Split("_")[0]; + //var building = ds.GroupBy(x => x.device_building_tag).Select(x => x.Key).ToList(); + //#region 歷史資料處理 + //ds.Clear(); + //var isDome = await backendRepository.GetOneAsync("select system_value from variable where deleted = 0 and system_type = 'project_name';"); + //var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; + //var variableObix = backendRepository.GetAllAsync(sqlObix).Result; + //var obixApiConfig = new Backend.Models.ObixApiConfig(); + //EDFunction ed = new EDFunction(); + //obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); + //obixApiConfig.UserName = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault(); + //obixApiConfig.Password = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault(); + ////obixApiConfig.UrlSlot = variableObix.Where(x => x.Name == "url_slot").Select(x => x.Value).FirstOrDefault(); + //webRequestService svc = new webRequestService(); + //var data = svc.obixHisQuery_v2(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", "", + // obixApiConfig.UserName, obixApiConfig.Password); + //ds.AddRange(data); - var building = ds.GroupBy(x => x.device_building_tag).Select(x => x.Key).ToList(); - await niagaraDataSynchronizeRepository.InsertItemFromNiagara(ds, building); // insert 暫存table import_niagara_item - await niagaraDataSynchronizeRepository.DeviceItemComparison(); //insert device_item - await niagaraDataSynchronizeRepository.CheckItemDiffFullNameAndCover(); // update device_item.fullname - await niagaraDataSynchronizeRepository.ItemCheckFullNameEmptyReplaceByDeviceName(); // 檢查device_item內FullName為空的值,以points取代 - await niagaraDataSynchronizeRepository.CheckItemIsShowHistory(); + //// save to history + //await niagaraDataSynchronizeRepository.InsertItemFromNiagara_History(ds, building); // insert 暫存table import_niagara_item_history + //if (!string.IsNullOrEmpty(isDome) && isDome.Contains("ibms_dome")) + // await niagaraDataSynchronizeRepository.RecoverSysTag("import_niagara_item_history"); // recover missing deivce_system_tag + //#endregion - #region 歷史資料處理 - ds.Clear(); - var isDome = await backendRepository.GetOneAsync("select system_value from variable where deleted = 0 and system_type = 'project_name';"); - var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; - var variableObix = backendRepository.GetAllAsync(sqlObix).Result; - var obixApiConfig = new Backend.Models.ObixApiConfig(); - EDFunction ed = new EDFunction(); - obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); - obixApiConfig.UserName = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault(); - obixApiConfig.Password = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault(); - //obixApiConfig.UrlSlot = variableObix.Where(x => x.Name == "url_slot").Select(x => x.Value).FirstOrDefault(); - webRequestService svc = new webRequestService(); - var data = svc.obixHisQuery_v2(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", "", - obixApiConfig.UserName, obixApiConfig.Password); - ds.AddRange(data); - // save to history - await niagaraDataSynchronizeRepository.InsertItemFromNiagara_History(ds, building); // insert 暫存table import_niagara_item_history - if (!string.IsNullOrEmpty(isDome) && isDome.Contains("ibms_dome")) - await niagaraDataSynchronizeRepository.RecoverSysTag("import_niagara_item_history"); // recover missing deivce_system_tag - #endregion + //await niagaraDataSynchronizeRepository.InsertItemFromNiagara(oldDs, building); // insert 暫存table import_niagara_item + //await niagaraDataSynchronizeRepository.DeviceItemComparison(); //insert device_item + //await niagaraDataSynchronizeRepository.CheckItemDiffFullNameAndCover(); // update device_item.fullname + //await niagaraDataSynchronizeRepository.ItemCheckFullNameEmptyReplaceByDeviceName(); // 檢查device_item內FullName為空的值,以points取代 + //await niagaraDataSynchronizeRepository.CheckItemIsShowHistory(); result = true; diff --git a/Backend/Controllers/SystemCategoryController.cs b/Backend/Controllers/SystemCategoryController.cs index 1c3bac6..3361f66 100644 --- a/Backend/Controllers/SystemCategoryController.cs +++ b/Backend/Controllers/SystemCategoryController.cs @@ -5,6 +5,7 @@ using Repository.BackendRepository.Interface; using System; using System.Collections.Generic; using System.Linq; +using System.Text; using System.Threading.Tasks; namespace Backend.Controllers @@ -354,6 +355,19 @@ namespace Backend.Controllers }; await backendRepository.AddOneByCustomTable(systemSubDic, "variable"); + var systemId = await backendRepository.GetOneAsync($@"select id from variable where system_value = '{post.system_value}' and deleted = 0 and system_parent_id = '{post.system_parent_id}' and system_type = '{sub_system_type}'"); + var buildings = await backendRepository.GetAllAsync($@"select building_tag from building where deleted = 0"); + var authCode = await backendRepository.GetOneAsync($@"select max(cast(SUBSTRING(authcode, 2) AS UNSIGNED)) from auth_page where authcode like 'F%'"); + var parentSystemName = await backendRepository.GetOneAsync($@"select system_key from variable where id = {post.system_parent_id}"); + StringBuilder sb = new StringBuilder(); + foreach (var b in buildings) + { + sb.Append($@" insert into auth_page(AuthCode, AuthType, MainName, SubName, building_tag, ShowView, created_at) + values ('F{++authCode}', '1', '{parentSystemName}', '{post.System_key}', '{b}', '{systemId}', Now());"); + } + + await backendRepository.ExecuteSql(sb.ToString()); + apiResult.Code = "0000"; apiResult.Msg = "新增成功"; } @@ -477,6 +491,7 @@ namespace Backend.Controllers await backendRepository.DeleteOne(id, "variable", "id"); + await backendRepository.ExecuteSql($@"delete from auth_page where AuthCode like 'F%' and AuthType = 1 and ShowView = '{id}'"); apiResult.Code = "0000"; apiResult.Msg = "刪除成功"; } diff --git a/Backend/Services/Implement/webRequestService.cs b/Backend/Services/Implement/webRequestService.cs index 2386ec1..c7c96d7 100644 --- a/Backend/Services/Implement/webRequestService.cs +++ b/Backend/Services/Implement/webRequestService.cs @@ -150,6 +150,7 @@ namespace Backend.Services.Implement streamWriter.Write(json); } + cp_Postrequest.Timeout = System.Threading.Timeout.Infinite; HttpWebResponse cp_response = (HttpWebResponse)cp_Postrequest.GetResponse(); var cp_responseString = new StreamReader(cp_response.GetResponseStream()).ReadToEnd(); @@ -175,101 +176,106 @@ namespace Backend.Services.Implement } #endregion - #region main program List result = new List(); - String API_Url = urlString; + #region main program (deleted) + //String API_Url = urlString; - HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url); - Postrequest.Method = "GET"; - Postrequest.Headers.Add("Authorization", "Basic " + encoded); - Postrequest.PreAuthenticate = true; + //HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url); + //Postrequest.Method = "GET"; + //Postrequest.Headers.Add("Authorization", "Basic " + encoded); + //Postrequest.PreAuthenticate = true; + //Postrequest.Timeout = System.Threading.Timeout.Infinite; - HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse(); - var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); + //HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse(); + //var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(responseString); + //XmlDocument xmlDoc = new XmlDocument(); + //xmlDoc.LoadXml(responseString); - //ref https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c - foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) - { - var stationName = node.Attributes["name"].InnerText; // WSP_Supervisor - oneStationName = oneStationName ?? stationName; - String API_Url2 = urlString + "/" + stationName; // http://192.168.0.136:8081/obix/histories/WSP_Supervisor + ////ref https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c + //foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) + //{ + // var stationName = node.Attributes["name"].InnerText; // WSP_Supervisor + // if (stationName.Split("_").Length > 1 && stationName.Split("_")[1] == building_tag.Split("_")[0]) + // { + // oneStationName = oneStationName ?? stationName; + // String API_Url2 = urlString + "/" + stationName; // http://192.168.0.136:8081/obix/histories/WSP_Supervisor - HttpWebRequest Postrequest2 = (HttpWebRequest)WebRequest.Create(API_Url2); - Postrequest2.Method = "GET"; - Postrequest2.Headers.Add("Authorization", "Basic " + encoded); - Postrequest2.PreAuthenticate = true; + // HttpWebRequest Postrequest2 = (HttpWebRequest)WebRequest.Create(API_Url2); + // Postrequest2.Method = "GET"; + // Postrequest2.Headers.Add("Authorization", "Basic " + encoded); + // Postrequest2.PreAuthenticate = true; + // Postrequest2.Timeout = System.Threading.Timeout.Infinite; - HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse(); - var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd(); + // HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse(); + // var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd(); - XmlDocument xmlDoc2 = new XmlDocument(); - xmlDoc2.LoadXml(responseString2); - // Create a namespace manager to handle the XML namespace - XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc2.NameTable); - string xmlns = xmlDoc2.DocumentElement.GetAttribute("xmlns") ?? "http://obix.org/ns/schema/1.0"; - namespaceManager.AddNamespace("obix", xmlns); + // XmlDocument xmlDoc2 = new XmlDocument(); + // xmlDoc2.LoadXml(responseString2); + // // Create a namespace manager to handle the XML namespace + // XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlDoc2.NameTable); + // string xmlns = xmlDoc2.DocumentElement.GetAttribute("xmlns") ?? "http://obix.org/ns/schema/1.0"; + // namespaceManager.AddNamespace("obix", xmlns); - // Select all "ref" nodes using an XPath expression - XmlNodeList refNodes = xmlDoc2.SelectNodes($"//obix:ref[starts-with(@name, '{AreaTag ?? building_tag}')]", namespaceManager); - foreach (XmlNode node2 in refNodes) - { - string tagName = node2.Attributes["name"].InnerText; - if (tagName.Split('_').Length == 9) - { - ImpNiaItem row = new ImpNiaItem(); - row.device_area_tag = tagName.Split('_')[0]; - row.device_building_tag = tagName.Split('_')[1]; - row.device_system_tag = tagName.Split('_')[2]; - row.device_name_tag = tagName.Split('_')[3]; - row.device_point_name = tagName.Split('_')[8]; - row.parent_path = stationName; + // // Select all "ref" nodes using an XPath expression + // XmlNodeList refNodes = xmlDoc2.SelectNodes($"//obix:ref[starts-with(@name, '{AreaTag ?? building_tag}')]", namespaceManager); + // foreach (XmlNode node2 in refNodes) + // { + // string tagName = node2.Attributes["name"].InnerText; + // if (tagName.Split('_').Length == 9) + // { + // ImpNiaItem row = new ImpNiaItem(); + // row.device_area_tag = tagName.Split('_')[0]; + // row.device_building_tag = tagName.Split('_')[1]; + // row.device_system_tag = tagName.Split('_')[2]; + // row.device_name_tag = tagName.Split('_')[3]; + // row.device_point_name = tagName.Split('_')[8]; + // row.parent_path = stationName; - //full_name 其實是點位名稱 point_name - row.full_name = conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).Select(x => x.displayName).FirstOrDefault(); - if (conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).FirstOrDefault() != null) - conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).FirstOrDefault().isHistory = true; - row.isHistory = true; + // //full_name 其實是點位名稱 point_name + // row.full_name = conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).Select(x => x.displayName).FirstOrDefault(); + // if (conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).FirstOrDefault() != null) + // conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).FirstOrDefault().isHistory = true; + // row.isHistory = true; - result.Add(row); - } - else if (tagName.Split('_').Length == 7) - { //巨蛋 tag 5 段版本 - ImpNiaItem row = new ImpNiaItem(); - if (tagName.Split('_')[2] == "S" || tagName.Split('_')[2] == "B" || tagName.Split('_')[2] == "CWB") //for security system and parking system - { - row.device_building_tag = tagName.Split('_')[1]; - row.device_system_tag = tagName.Split('_')[2]; - row.device_floor_tag = tagName.Split('_')[3]; - row.device_name_tag = tagName.Split('_')[4]; - row.device_point_name = tagName.Split('_')[6]; - } - else //for normal - { - row.device_building_tag = tagName.Split('_')[1]; - row.device_floor_tag = tagName.Split('_')[3]; - row.device_name_tag = tagName.Split('_')[2]; - row.device_point_name = tagName.Split('_')[6]; - } + // result.Add(row); + // } + // else if (tagName.Split('_').Length == 6) + // { //巨蛋 tag 5 段版本 + // ImpNiaItem row = new ImpNiaItem(); + // if (tagName.Split('_')[1] == "S" || tagName.Split('_')[1] == "B" || tagName.Split('_')[1] == "CWB") //for security system and parking system + // { + // row.device_building_tag = tagName.Split('_')[0]; + // row.device_system_tag = tagName.Split('_')[1]; + // row.device_floor_tag = tagName.Split('_')[2]; + // row.device_name_tag = tagName.Split('_')[3]; + // row.device_point_name = tagName.Split('_')[5]; + // } + // else //for normal + // { + // row.device_building_tag = tagName.Split('_')[0]; + // row.device_floor_tag = tagName.Split('_')[2]; + // row.device_name_tag = tagName.Split('_')[1]; + // row.device_point_name = tagName.Split('_')[5]; + // } - row.parent_path = stationName; - //full_name 其實是點位名稱 point_name - var deviceNumber = tagName.Substring(0, tagName.LastIndexOf(tagName.Split("_")[5]) - 1); - var point = tagName.Split("_")[5]; - conPoint = conPoint.Where(x => x.name.Split("/").Length > 6).ToList(); - row.full_name = conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).Select(x => x.displayName).FirstOrDefault(); - if (conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).FirstOrDefault() != null) - conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).FirstOrDefault().isHistory = true; - row.isHistory = true; - result.Add(row); - } - } - } + // row.parent_path = stationName; + // //full_name 其實是點位名稱 point_name + // var deviceNumber = tagName.Substring(0, tagName.LastIndexOf(tagName.Split("_")[5]) - 1); + // var point = tagName.Split("_")[5]; + // conPoint = conPoint.Where(x => x.name.Split("/").Length > 6).ToList(); + // row.full_name = conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).Select(x => x.displayName).FirstOrDefault(); + // if (conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).FirstOrDefault() != null) + // conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).FirstOrDefault().isHistory = true; + // row.isHistory = true; + // result.Add(row); + // } + // } + // } + //} #endregion - var newConPoint = conPoint.Where(x => !x.isHistory).ToArray(); - foreach(var n in newConPoint) + + foreach (var n in conPoint) { if (n.name.Split('/').Length == 9) { @@ -280,9 +286,7 @@ namespace Backend.Services.Implement device_system_tag = n.name.Split('/')[2], device_name_tag = n.name.Split('/')[3], device_point_name = n.name.Split('/')[8], - full_name = n.displayName, - parent_path = oneStationName, - isHistory = n.isHistory + full_name = n.displayName }); } else if (n.name.Split('/').Length == 7) // Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/Summery @@ -295,9 +299,7 @@ namespace Backend.Services.Implement device_floor_tag = n.name.Split('/')[3], device_name_tag = n.name.Split('/')[4], device_point_name = n.name.Split('/')[6], - full_name = n.displayName, - parent_path = oneStationName, - isHistory = n.isHistory + full_name = n.displayName }); } else //for normal @@ -309,9 +311,7 @@ namespace Backend.Services.Implement device_floor_tag = n.name.Split('/')[3], device_name_tag = n.name.Split('/')[2], device_point_name = n.name.Split('/')[6], - full_name = n.displayName, - parent_path = oneStationName, - isHistory = n.isHistory + full_name = n.displayName }); } } @@ -498,6 +498,7 @@ namespace Backend.Services.Implement Postrequest.Method = "GET"; Postrequest.Headers.Add("Authorization", "Basic " + encoded); Postrequest.PreAuthenticate = true; + Postrequest.Timeout = System.Threading.Timeout.Infinite; HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); @@ -517,6 +518,7 @@ namespace Backend.Services.Implement Postrequest2.Method = "GET"; Postrequest2.Headers.Add("Authorization", "Basic " + encoded); Postrequest2.PreAuthenticate = true; + Postrequest2.Timeout = System.Threading.Timeout.Infinite; HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse(); var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd(); @@ -727,5 +729,111 @@ namespace Backend.Services.Implement // } // } //} + + /// + /// 獲取 niagara history 中的點位 + /// + /// + /// + /// + /// + public List obixAllDevicePoint(string bqlUrlString, string urlString, string slot, string acc, string pass, string AreaTag) + { + String username = acc; + String password = pass; + String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); + + #region get control point data + List conPoint = new List(); + String cp_API_Url = bqlUrlString; + String building_tag = slot.Split("/")[2].Replace("|", "_").Trim(); //Ex: D2_, M_ + + HttpWebRequest cp_Postrequest = (HttpWebRequest)WebRequest.Create(cp_API_Url); + cp_Postrequest.Method = "POST"; + cp_Postrequest.Headers.Add("Authorization", "Basic " + encoded); + cp_Postrequest.PreAuthenticate = true; + + using (var streamWriter = new StreamWriter(cp_Postrequest.GetRequestStream())) + { + string json = ""; + + streamWriter.Write(json); + } + cp_Postrequest.Timeout = System.Threading.Timeout.Infinite; + HttpWebResponse cp_response = (HttpWebResponse)cp_Postrequest.GetResponse(); + var cp_responseString = new StreamReader(cp_response.GetResponseStream()).ReadToEnd(); + + XmlDocument cp_xmlDoc = new XmlDocument(); + cp_xmlDoc.LoadXml(cp_responseString); + + string cp_jsonText = JsonConvert.SerializeXmlNode(cp_xmlDoc); + var cp_data = Welcome.FromJson(cp_jsonText); + + foreach (var item in cp_data.Obj.Str) + { + control_point row = new control_point(); + string[] s1 = item.Val.Split(','); + + string[] s2 = s1[0].Split('/'); + var displayName = s1[1].Split('=')[1]; + + row.name = s1[0].Remove(s1[0].Length - 1, 1).Remove(0, 1); + row.displayName = displayName; + row.isHistory = false; + + conPoint.Add(row); + } + #endregion + + var result = new List(); + foreach (var n in conPoint) + { + if (n.name.Split('/').Length == 9) + { + result.Add(new DeviceControlPoint + { + name = n.name, + displayName = n.displayName, + device_area_tag = n.name.Split('/')[0], + device_building_tag = n.name.Split('/')[1], + device_system_tag = n.name.Split('/')[2], + device_name_tag = n.name.Split('/')[3], + device_point_name = n.name.Split('/')[8], + }); + } + else if (n.name.Split('/').Length == 7) // Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/Summery + { + if (n.name.Split('/')[2] == "S" || n.name.Split('/')[2] == "B" || n.name.Split('/')[2] == "CWB") //for security system and CWB system + { + result.Add(new DeviceControlPoint + { + name = n.name, + displayName = n.displayName, + device_building_tag = n.name.Split('/')[1], + device_system_tag = n.name.Split('/')[2], + device_floor_tag = n.name.Split('/')[3], + device_name_tag = n.name.Split('/')[4], + device_point_name = n.name.Split('/')[6], + device_number = n.name.Split('/')[5] + }); + } + else //for normal + { + result.Add(new DeviceControlPoint + { + name = n.name, + displayName = n.displayName, + device_building_tag = n.name.Split('/')[1], + //device_system_tag = n.name.Split('/')[1], + device_floor_tag = n.name.Split('/')[3], + device_name_tag = n.name.Split('/')[2], + device_point_name = n.name.Split('/')[6], + device_number = n.name.Split('/')[5] + }); + } + } + } + return result.ToList(); + } } } diff --git a/BackendWorkerService/Program.cs b/BackendWorkerService/Program.cs index e293df7..bb7f330 100644 --- a/BackendWorkerService/Program.cs +++ b/BackendWorkerService/Program.cs @@ -121,19 +121,19 @@ namespace BackendWorkerService //); //#endregion - //#region ޲z(]wC 5 @) - //services.AddSingleton(); - //services.AddSingleton( - //new JobSchedule(jobType: typeof(ParkingJob), cronExpression: configuration.GetValue("BackgroundServiceCron:ParkingJob")) - //); - //#endregion + #region ޲z(]wC 5 @) + services.AddSingleton(); + services.AddSingleton( + new JobSchedule(jobType: typeof(ParkingJob), cronExpression: configuration.GetValue("BackgroundServiceCron:ParkingJob")) + ); + #endregion - //#region qk(]wC p @) - //services.AddSingleton(); - //services.AddSingleton( - //new JobSchedule(jobType: typeof(ArchiveElectricMeterHourJob), cronExpression: configuration.GetValue("BackgroundServiceCron:ArchiveElectricMeterHourJob")) - //); - //#endregion + #region qk(]wC p @) + services.AddSingleton(); + services.AddSingleton( + new JobSchedule(jobType: typeof(ArchiveElectricMeterHourJob), cronExpression: configuration.GetValue("BackgroundServiceCron:ArchiveElectricMeterHourJob")) + ); + #endregion #region qk(]wC @) services.AddSingleton(); @@ -143,10 +143,10 @@ namespace BackendWorkerService #endregion #region wɨoHAPI - services.AddSingleton(); - services.AddSingleton( - new JobSchedule(jobType: typeof(Quartz.Jobs.WeatherAPIJob), cronExpression: configuration.GetValue("BackgroundServiceCron:WeatherAPIJob")) - ); + //services.AddSingleton(); + //services.AddSingleton( + //new JobSchedule(jobType: typeof(Quartz.Jobs.WeatherAPIJob), cronExpression: configuration.GetValue("BackgroundServiceCron:WeatherAPIJob")) + //); #endregion }).ConfigureLogging((hostContext, logFactory) => { diff --git a/BackendWorkerService/Quartz/Jobs/ParkingJob.cs b/BackendWorkerService/Quartz/Jobs/ParkingJob.cs index 4391508..12df07e 100644 --- a/BackendWorkerService/Quartz/Jobs/ParkingJob.cs +++ b/BackendWorkerService/Quartz/Jobs/ParkingJob.cs @@ -69,6 +69,8 @@ namespace BackendWorkerService.Quartz.Jobs spaceRequest.Method = "GET"; //request.Headers.Add("Authorization", "Basic " + encoded); spaceRequest.PreAuthenticate = true; + spaceRequest.Timeout = System.Threading.Timeout.Infinite; + spaceRequest.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; //Stopwatch stopWatch = new Stopwatch(); //stopWatch.Start(); @@ -95,7 +97,7 @@ namespace BackendWorkerService.Quartz.Jobs { var tagName = selectedMapping.system_value; var apiFormat = @"{0}obix/config/Arena/{1}/{2}/{3}/{4}/{5}/CV/set"; - + var tagNameSplit = tagName.Split("_"); var parames = new List(); @@ -104,18 +106,19 @@ namespace BackendWorkerService.Quartz.Jobs { if (i != tagNameSplit.Length - 1) { - parames.Add(tagNameSplit[i]); + parames.Add(tagNameSplit[i]); // tag 前 4段 } else { - parames.Add(tagName); + parames.Add(tagName); // 第五段 完整 tag } } - + logger.LogError(@$"【ParkingJob】【停車場剩餘車位】{apiFormat}"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(apiFormat, parames.ToArray())); request.Method = "POST"; request.Headers.Add("Authorization", "Basic " + encoded); request.PreAuthenticate = true; + request.Timeout = System.Threading.Timeout.Infinite; var real = $@""; byte[] realByteArray = Encoding.UTF8.GetBytes(real); @@ -123,7 +126,6 @@ namespace BackendWorkerService.Quartz.Jobs { reqStream.Write(realByteArray, 0, realByteArray.Length); } - HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var responseContent = new StreamReader(response.GetResponseStream()).ReadToEnd(); @@ -180,7 +182,7 @@ namespace BackendWorkerService.Quartz.Jobs #endregion #region 取得設備資訊 - if (await task_Detail.GetNeedWorkTask("ParkingJob", "Device")) + if (await task_Detail.GetNeedWorkTask("ParkingJob", "Device")) { try { @@ -191,6 +193,7 @@ namespace BackendWorkerService.Quartz.Jobs equipmentRequest.Method = "GET"; //request.Headers.Add("Authorization", "Basic " + encoded); equipmentRequest.PreAuthenticate = true; + equipmentRequest.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; HttpWebResponse equipmentResponse = (HttpWebResponse)equipmentRequest.GetResponse(); var equipmentResponseContent = new StreamReader(equipmentResponse.GetResponseStream()).ReadToEnd(); diff --git a/BackendWorkerService/appsettings.Development.json b/BackendWorkerService/appsettings.Development.json index b4569f6..e822289 100644 --- a/BackendWorkerService/appsettings.Development.json +++ b/BackendWorkerService/appsettings.Development.json @@ -12,7 +12,7 @@ "MessageNotificationJob": "0 0 2 * * ?", "DataDeliveryJob": "0 0 2 * * ?", "RegularUpdateDBTableJob": "0 0 2 * * ?", - "ParkingJob": "0 0 2 * * ?", + "ParkingJob": "0/5 * * * * ?", "ArchiveElectricMeterHourJob": "0 0 2 * * ?", "ArchiveElectricMeterDayJob": "0/5 * * * * ?", "WeatherAPIJob": "0 0 2 * * ?" @@ -25,7 +25,8 @@ //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp //"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome //"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel - "Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut + //"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut + "Database": "+5RAiFLJVU+LRyDxF1K/pcLZaoZa4k/thZqF6xKoCag=", //dome_online_0821 "Root": "SzdxEgaJJ7tcTCrUl2zKsA==", "Password": "FVAPxztxpY4gJJKQ/se4bQ==" }, diff --git a/BackendWorkerService/appsettings.json b/BackendWorkerService/appsettings.json index b4569f6..8c853d2 100644 --- a/BackendWorkerService/appsettings.json +++ b/BackendWorkerService/appsettings.json @@ -25,7 +25,8 @@ //"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp //"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome //"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel - "Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut + //"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut + "Database": "+5RAiFLJVU+LRyDxF1K/pcLZaoZa4k/thZqF6xKoCag=", //dome_online_0821 "Root": "SzdxEgaJJ7tcTCrUl2zKsA==", "Password": "FVAPxztxpY4gJJKQ/se4bQ==" }, diff --git a/FrontendWebApi/ApiControllers/BuildController.cs b/FrontendWebApi/ApiControllers/BuildController.cs index 8f8fa12..aa5a779 100644 --- a/FrontendWebApi/ApiControllers/BuildController.cs +++ b/FrontendWebApi/ApiControllers/BuildController.cs @@ -180,8 +180,8 @@ namespace FrontendWebApi.ApiControllers v2.system_key subfull_name, v2.system_priority subpriority from building_menu me - left join variable v1 on me.main_system_tag = v1.system_value and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2' - left join variable v2 on me.sub_system_tag = v2.system_value and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' + join variable v1 on me.main_system_tag = v1.system_value and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2' + join variable v2 on me.sub_system_tag = v2.system_value and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' inner join ( SELECT ap.building_tag, @@ -192,7 +192,7 @@ namespace FrontendWebApi.ApiControllers FROM role_auth ra WHERE ra.role_guid = (SELECT ui.role_guid from userinfo ui where account = @Account) ) ra - left join auth_page ap on ra.AuthCode = ap.AuthCode + join auth_page ap on ra.AuthCode = ap.AuthCode where ap.AuthType = 1 ) shower on shower.building_tag = me.building_tag and shower.ShowView = v2.id join building b on b.building_tag = me.building_tag and b.deleted = 0 and shower.building_tag = b.building_tag @@ -200,8 +200,8 @@ namespace FrontendWebApi.ApiControllers order by b.priority, v1.system_priority, me.priority, v2.system_priority, v2.created_at DESC", new { Account = account }); var floorsql = await backendRepository.GetAllAsync(@" - select * from (select * from sub_system_floor ssf where ssf.deleted = 0 and ssf.status = 0) a - left join floor on floor.full_name = a.floor_tag order by floor.priority;"); + select * from (select * from sub_system_floor ssf where ssf.deleted = 0 and ssf.status = 0 and ssf.is_link = 1) a + join floor on floor.full_name = a.floor_tag order by floor.priority;"); var common = await backendRepository.GetAllAsync($@"select ap.building_tag Name,ap.ShowView Value from auth_page ap left join role_auth ra on ra.AuthCode = ap.AuthCode @@ -329,7 +329,7 @@ namespace FrontendWebApi.ApiControllers List Floors = new List(); var floorsql = await backendRepository.GetAllAsync($@" - select * from (select * from sub_system_floor ssf where ssf.deleted = 0 and ssf.status = 0 and ssf.building_tag = '{get.building_tag}' and ssf.main_system_tag = '{get.main_system_tag}' and ssf.sub_system_tag = '{get.sub_system_tag}') a + select * from (select * from sub_system_floor ssf where ssf.deleted = 0 and ssf.status = 0 and ssf.building_tag = '{get.building_tag}' and ssf.main_system_tag = '{get.main_system_tag}' and ssf.sub_system_tag = '{get.sub_system_tag}' and ssf.is_link = 1) a left join floor on floor.full_name = a.floor_tag and a.building_tag = floor.building_tag where floor.deleted = 0 order by floor.priority"); diff --git a/FrontendWebApi/ApiControllers/HistoryController.cs b/FrontendWebApi/ApiControllers/HistoryController.cs index 8a80b3f..347e94d 100644 --- a/FrontendWebApi/ApiControllers/HistoryController.cs +++ b/FrontendWebApi/ApiControllers/HistoryController.cs @@ -343,9 +343,12 @@ namespace FrontendWebApi.ApiControllers join userinfo c on c.role_guid = a.role_guid join variable v2 on b.ShowView = v2.id and v2.system_type = @sub_system_type join variable v1 on v1.id = v2.system_parent_id and v1.system_type = @main_system_type - join device d on v1.system_value = d.device_system_tag and v2.system_value = d.device_name_tag and d.deleted = 0 and d.visible = 1 and d.is_link = 1 - join device_item di on d.device_system_tag=di.device_system_tag and d.device_name_tag=di.device_name_tag - and di.is_link = 1 and di.is_show_history = 1 + join ( + select distinct device_system_tag, device_name_tag, device_serial_tag, device_number, full_name from device d where d.deleted = 0 and d.visible = 1 and d.is_link = 1 limit 1000000 + ) d on v1.system_value = d.device_system_tag and v2.system_value = d.device_name_tag + join ( + select distinct device_system_tag, device_name_tag, is_show_history from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 + ) di on d.device_system_tag=di.device_system_tag and d.device_name_tag=di.device_name_tag where c.account = @account order by v1.system_priority, v2.system_priority", new { @account = myUser.account, @sub_system_type = sub_system_type, @main_system_type = main_system_type }); var dbbuilding = await frontendRepository.GetAllAsync( @@ -567,7 +570,7 @@ namespace FrontendWebApi.ApiControllers join variable v1 on v1.system_value = b.device_system_tag and v1.deleted = 0 and v1.system_type = 'device_system_category_layer2' join variable v2 on v2.system_value = b.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' where a.deleted = 0 and b.deleted = 0 and v2.deleted = 0 and v1.deleted = 0 - and a.unit is not null and b.device_number in @Device_number + and a.unit is not null and b.device_number in @Device_number and a.is_link = 1 order by c.priority,b.priority;" , new { Device_number = postDevice.select_data.Select(a => a.device_number).ToList() } ); diff --git a/FrontendWebApi/ApiControllers/LightScheduleController.cs b/FrontendWebApi/ApiControllers/LightScheduleController.cs index 61d2241..30aae51 100644 --- a/FrontendWebApi/ApiControllers/LightScheduleController.cs +++ b/FrontendWebApi/ApiControllers/LightScheduleController.cs @@ -1,7 +1,9 @@ using FrontendWebApi.Models; using Microsoft.AspNetCore.Mvc; +using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Extensions.Logging; using Newtonsoft.Json; +using Repository.BackendRepository.Implement; using Repository.BackendRepository.Interface; using Repository.FrontendRepository.Interface; using System; @@ -46,7 +48,7 @@ namespace FrontendWebApi.ApiControllers ",new { floor_guid = post.floor_guid}); lightDevices = await backendRepository.GetAllAsync($@" - select * from device where device_building_tag = '{post.building_tag}' and device_name_tag = '{post.sub_system_tag}' and device_floor_tag = '{floor_tag}' and deleted = 0 and status = 0 order by priority + select * from device where device_building_tag = '{post.building_tag}' and device_name_tag = '{post.sub_system_tag}' and device_floor_tag = '{floor_tag}' and deleted = 0 order by priority "); if(!String.IsNullOrEmpty(post.schedule_guid)) @@ -326,13 +328,18 @@ namespace FrontendWebApi.ApiControllers } var deviceNumList = await backendRepository.GetAllAsync(@$"select d.device_number from schedule_device sd left join device d on sd.device_guid = d.device_guid - where light_schedule_guid = '{guid}'"); + where light_schedule_guid = ' + {guid}'"); - foreach(var deviceNum in deviceNumList) + var variableObix = await backendRepository.GetAllAsync("SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"); + string url = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); + string account = variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault(); + string pass = variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault(); + foreach (var deviceNum in deviceNumList) { var d = deviceNum.Split("_"); - var html = "http://greencloud.fic.com.tw:8080/obix/config/Arena/"+$"{d[0]}/{d[1]}/{d[2]}/{d[3]}/{deviceNum}/SSC/set"; - string authInfo = "AR_Light" + ":" + "Light12345"; + var html = $"{url}/obix/config/Arena/" + $"{d[0]}/{d[1]}/{d[2]}/{d[3]}/{deviceNum}/SSC/set"; + string authInfo = account + ":" + pass; authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo)); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(html); request.Method = "POST"; diff --git a/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs b/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs index 9e68d8d..57f40ab 100644 --- a/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs +++ b/Repository/BackendRepository/Implement/NiagaraDataSynchronizeRepository.cs @@ -15,6 +15,7 @@ using System.Web; using Org.BouncyCastle.Utilities.Collections; using System.Reflection; using System.Drawing; +using Org.BouncyCastle.Asn1.Mozilla; namespace Repository.BackendRepository.Implement { @@ -156,9 +157,10 @@ namespace Repository.BackendRepository.Implement where (device_system_tag <> 'S' and device_system_tag <> 'CWB' and device_system_tag <> 'B' and (device_system_tag <> 'FM' or device_system_tag <> 'APS' or device_system_tag <> 'VICL')); - update import_niagara_tag a join dic_system b - on a.device_name_tag COLLATE utf8mb4_general_ci = b.s2_code - set device_system_tag = b.s1_code -- tag 第二碼為小類(除了安全系統之外) + update import_niagara_tag a + join variable b on a.device_name_tag COLLATE utf8mb4_general_ci = b.system_value and b.deleted = 0 and b.system_type = 'device_system_category_layer3' + join variable v1 on b.system_parent_id = v1.id + set device_system_tag = v1.system_value -- tag 第二碼為小類(除了安全系統之外) where (device_system_tag <> 'S' and device_system_tag <> 'CWB' and device_system_tag <> 'B' and (device_system_tag <> 'FM' or device_system_tag <> 'APS' or device_system_tag <> 'VICL')); -- 安全系統 第二段大類 第四段小類"); using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) @@ -242,9 +244,7 @@ namespace Repository.BackendRepository.Implement device_system_tag = x.device_system_tag, device_name_tag = x.device_name_tag, device_point_name = x.device_point_name, - full_name = x.full_name, - parent_path = x.parent_path, - isHistory = x.isHistory + full_name = x.full_name }) .Select(x => new ImpNiaItem { @@ -253,9 +253,7 @@ namespace Repository.BackendRepository.Implement device_system_tag = x.Key.device_system_tag, device_name_tag = x.Key.device_name_tag, device_point_name = x.Key.device_point_name, - full_name = x.Key.full_name, - parent_path = x.Key.parent_path, - isHistory = x.Key.isHistory + full_name = x.Key.full_name }).ToList(); StringBuilder sb = new StringBuilder(); @@ -269,9 +267,9 @@ namespace Repository.BackendRepository.Implement row.device_system_tag + "', '" + row.device_name_tag + "', '" + row.device_point_name + "', '" + - row.parent_path + "', '" + + "" + "', '" + row.full_name + "'," + - row.isHistory + + "0" + ");"); } @@ -280,9 +278,10 @@ namespace Repository.BackendRepository.Implement { if (isDome.Contains("ibms_dome")) { - sb.Append($@" update import_niagara_item a join dic_system b - on a.device_name_tag COLLATE utf8mb4_0900_ai_ci = b.s2_code COLLATE utf8mb4_0900_ai_ci - set device_system_tag = b.s1_code + sb.Append($@" update import_niagara_item a + join variable b on a.device_name_tag COLLATE utf8mb4_0900_ai_ci = b.system_value COLLATE utf8mb4_0900_ai_ci and b.deleted = 0 and b.system_type = 'device_system_category_layer3' + join variable v1 on b.system_parent_id = v1.id + set device_system_tag = v1.system_value where (device_system_tag <> 'S' and device_system_tag <> 'CWB' and device_system_tag <> 'B');"); } @@ -292,6 +291,34 @@ namespace Repository.BackendRepository.Implement await conn.ExecuteAsync(sb.ToString()); } sb.Clear(); + + sb.Append($@"SET SQL_SAFE_UPDATES = 0; + update import_niagara_item ini + join ( + select device_building_tag, device_system_tag, device_name_tag, device_point_name + from import_niagara_item_history + group by device_building_tag, device_system_tag, device_name_tag, device_point_name + ) as inih on ini.device_building_tag = inih.device_building_tag and ini.device_system_tag = inih.device_system_tag and ini.device_name_tag = inih.device_name_tag + and ini.device_point_name = inih.device_point_name + set ini.is_history = 1"); + + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await conn.ExecuteAsync(sb.ToString()); + } + sb.Clear(); + + sb.Append($@"SET SQL_SAFE_UPDATES = 0; + update import_niagara_item ini + join ( + select distinct device_building_tag, parent_path from import_niagara_item_history + ) inih on ini.device_building_tag = inih.device_building_tag + set ini.parent_path = inih.parent_path"); + + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await conn.ExecuteAsync(sb.ToString()); + } } #endregion } @@ -565,7 +592,7 @@ namespace Repository.BackendRepository.Implement 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 and m.device_building_tag collate utf8mb4_0900_ai_ci = d.device_building_tag - WHERE d.points IS NULL;"); + WHERE d.points IS NULL and d.deleted = 0;"); result = (await conn.QueryAsync(sb.ToString())).ToList(); sb.Clear(); @@ -623,16 +650,15 @@ namespace Repository.BackendRepository.Implement sb.Append($@" SET SQL_SAFE_UPDATES = 0; UPDATE device_item d LEFT JOIN ( - SELECT device_system_tag, device_name_tag, device_point_name, full_name + SELECT device_system_tag, device_name_tag, device_point_name, full_name, device_building_tag FROM import_niagara_item LIMIT 100000 -- Specify your desired limit here ) 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 = CASE WHEN m.device_point_name IS NULL THEN 0 ELSE 1 END; - - "); + AND d.device_building_tag = m.device_building_tag + SET d.is_link = CASE WHEN m.device_point_name IS NULL THEN 0 ELSE 1 END;"); using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { @@ -643,7 +669,7 @@ namespace Repository.BackendRepository.Implement sb.Append($@" SET SQL_SAFE_UPDATES = 0; UPDATE device_item d LEFT JOIN ( - SELECT m.device_system_tag, m.device_name_tag, m.device_point_name, m.full_name + SELECT m.device_system_tag, m.device_name_tag, m.device_point_name, m.full_name, device_building_tag FROM import_niagara_item m WHERE (m.is_history = 1) LIMIT 100000 -- Specify your desired limit here @@ -651,8 +677,8 @@ namespace Repository.BackendRepository.Implement ON d.device_system_tag = subquery.device_system_tag AND d.device_name_tag = subquery.device_name_tag AND d.points = subquery.device_point_name - SET d.is_show_history = CASE WHEN subquery.device_point_name IS NULL THEN 0 ELSE 1 END - WHERE (d.is_show_history);"); + AND d.device_building_tag = subquery.device_building_tag + SET d.is_show_history = CASE WHEN subquery.device_point_name IS NULL THEN 0 ELSE 1 END;"); using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { @@ -741,6 +767,22 @@ namespace Repository.BackendRepository.Implement { await conn.ExecuteAsync(sb.ToString()); } + + sb.Clear(); + 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.building_tag COLLATE utf8mb4_0900_ai_ci = a.device_building_tag COLLATE utf8mb4_0900_ai_ci + and a.device_system_tag COLLATE utf8mb4_0900_ai_ci = b.main_system_tag COLLATE utf8mb4_0900_ai_ci and a.device_name_tag COLLATE utf8mb4_0900_ai_ci = b.sub_system_tag COLLATE utf8mb4_0900_ai_ci + SET b.is_link = 1 + WHERE a.device_building_tag IS NOT NULL and b.is_link < 2"); + + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await conn.ExecuteAsync(sb.ToString()); + } } catch (Exception exception) { @@ -817,7 +859,26 @@ namespace Repository.BackendRepository.Implement and b.sub_system_tag COLLATE utf8mb4_0900_ai_ci = a.device_name_tag COLLATE utf8mb4_0900_ai_ci and b.floor_tag COLLATE utf8mb4_0900_ai_ci = a.device_floor_tag COLLATE utf8mb4_0900_ai_ci SET b.is_link = 0 - WHERE b.building_tag IS NULL"); + WHERE a.device_building_tag IS NULL"); + + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await conn.ExecuteAsync(sb.ToString()); + } + + sb.Clear(); + + 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 COLLATE utf8mb4_0900_ai_ci = a.device_building_tag COLLATE utf8mb4_0900_ai_ci + and b.main_system_tag COLLATE utf8mb4_0900_ai_ci = a.device_system_tag COLLATE utf8mb4_0900_ai_ci + and b.sub_system_tag COLLATE utf8mb4_0900_ai_ci = a.device_name_tag COLLATE utf8mb4_0900_ai_ci + and b.floor_tag COLLATE utf8mb4_0900_ai_ci = a.device_floor_tag COLLATE utf8mb4_0900_ai_ci + SET b.is_link = 1 + WHERE a.device_building_tag IS NOT NULL"); using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { @@ -1320,8 +1381,9 @@ device_floor_tag, device_master_tag, device_last_name_tag, device_serial_tag, d StringBuilder sb = new StringBuilder(); sb.Append($@"SET SQL_SAFE_UPDATES = 0; update {tableName} a - join dic_system ds on ds.s2_code = a.device_name_tag - set a.device_system_tag = ds.s1_code + join variable v2 on v2.system_value = a.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3' + join variable v1 on v1.id = v2.system_parent_id + set a.device_system_tag = v1.system_value where a.device_system_tag is null or a.device_system_tag = '';"); await conn.ExecuteAsync(sb.ToString()); } @@ -1336,5 +1398,74 @@ device_floor_tag, device_master_tag, device_last_name_tag, device_serial_tag, d } } } + + /// + /// record all device control point + /// + /// + /// + public async Task DeviceControlPoint (List dcp) + { + using (IDbConnection conn = GetDbConnection()) + { + try + { + string sql = @"CREATE TABLE IF NOT EXISTS `import_niagara_device_control_point` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(1000) DEFAULT NULL, + `displayName` 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_number` varchar(50) DEFAULT NULL, + `device_point_name` varchar(50) DEFAULT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;"; + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await conn.ExecuteAsync(sql); + } + + sql = @"truncate table import_niagara_device_control_point"; + using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) + { + await conn.ExecuteAsync(sql); + } + + StringBuilder sb = new StringBuilder(); + int count = 0; + foreach (var data in dcp) + { + sql = $@" insert into import_niagara_device_control_point(name, displayName, device_area_tag, device_building_tag, device_system_tag, device_name_tag, device_floor_tag, + device_number, device_point_name) + values ('{data.name}', '{data.displayName}', '{data.device_area_tag}', '{data.device_building_tag}', '{data.device_system_tag}', '{data.device_name_tag}', + '{data.device_floor_tag}', '{data.device_number}', '{data.device_point_name}');"; + sb.Append(sql); + count++; + if (count.Equals(100)) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + count = 0; + } + } + if (sb.Length > 0) + { + await conn.ExecuteAsync(sb.ToString()); + sb.Clear(); + } + } + catch (Exception e) + { + throw e; + } + finally + { + conn.Close(); + } + } + } } } diff --git a/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs b/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs index b14f12a..351047c 100644 --- a/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs +++ b/Repository/BackendRepository/Interface/INiagaraDataSynchronizeRepository.cs @@ -82,5 +82,12 @@ namespace Repository.BackendRepository.Interface /// /// Task RecoverSysTag(string tableName); + + /// + /// record all device control point + /// + /// + /// + Task DeviceControlPoint(List dcp); } } diff --git a/Repository/Models/BackgroundServiceTask.cs b/Repository/Models/BackgroundServiceTask.cs index c206285..fbfc179 100644 --- a/Repository/Models/BackgroundServiceTask.cs +++ b/Repository/Models/BackgroundServiceTask.cs @@ -164,4 +164,17 @@ namespace Repository.Models public string area_tag { get; set; } public string obixSlot { get; set; } } + + public class DeviceControlPoint + { + public string name { get; set; } + public string displayName { 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_number { get; set; } + public string device_point_name { get; set; } + } }