[後端] 修改後台同步流程, 新增寫入所有control point 設備

This commit is contained in:
dev02 2023-10-04 14:41:52 +08:00
parent af876d7e77
commit 3b19c94246
6 changed files with 250 additions and 41 deletions

View File

@ -62,7 +62,7 @@ namespace Backend.Controllers
string top100 = "";//" top 100 "; string top100 = "";//" top 100 ";
webRequestService svc = new webRequestService(); webRequestService svc = new webRequestService();
var urlSlots = backendRepository.GetAllAsync<string>("select obixSlot from building where deleted = 0").Result; var urlSlots = backendRepository.GetAllAsync<string>("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 "; 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); //ds = svc.obixQuery("http://192.168.0.136:8080/obix/config/Arena/Program/ObixQuery/query/", bql);
@ -161,15 +161,24 @@ namespace Backend.Controllers
obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); 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.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.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<BuildingDetail>("select obixSlot, area_tag from building where deleted = 0").Result; var urlSlots = backendRepository.GetAllAsync<BuildingDetail>("select obixSlot, area_tag from building where deleted = 0").Result;
foreach(var us in urlSlots) var data2 = new List<DeviceControlPoint>();
foreach (var us in urlSlots)
{ {
var data = svc.obixHisQuery(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", us.obixSlot, var data = svc.obixHisQuery(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", us.obixSlot,
obixApiConfig.UserName, obixApiConfig.Password, us.area_tag); 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); ds.AddRange(data);
} }
if (data2.Any())
{
niagaraDataSynchronizeRepository.DeviceControlPoint(data2);
}
var buildings = backendRepository.GetAllAsync<string>("select building_tag from building where deleted = 0").Result; var buildings = backendRepository.GetAllAsync<string>("select building_tag from building where deleted = 0").Result;
apiResult.Code = "0000"; apiResult.Code = "0000";
apiResult.Data = ds.Where(x => buildings.Contains(x.device_building_tag)).ToList(); apiResult.Data = ds.Where(x => buildings.Contains(x.device_building_tag)).ToList();
@ -201,33 +210,34 @@ namespace Backend.Controllers
{ {
//string ss = ds.Where(x => x.tag_name != "").FirstOrDefault().tag_name; //string ss = ds.Where(x => x.tag_name != "").FirstOrDefault().tag_name;
//var building = ss.Split("_")[0]; //var building = ss.Split("_")[0];
var building = ds.GroupBy(x => x.device_building_tag).Select(x => x.Key).ToList(); //var building = ds.GroupBy(x => x.device_building_tag).Select(x => x.Key).ToList();
#region //#region 歷史資料處理
ds.Clear(); //ds.Clear();
var isDome = await backendRepository.GetOneAsync<string>("select system_value from variable where deleted = 0 and system_type = 'project_name';"); //var isDome = await backendRepository.GetOneAsync<string>("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 sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
var variableObix = backendRepository.GetAllAsync<Backend.Models.KeyValue>(sqlObix).Result; //var variableObix = backendRepository.GetAllAsync<Backend.Models.KeyValue>(sqlObix).Result;
var obixApiConfig = new Backend.Models.ObixApiConfig(); //var obixApiConfig = new Backend.Models.ObixApiConfig();
EDFunction ed = new EDFunction(); //EDFunction ed = new EDFunction();
obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault(); //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.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.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();
webRequestService svc = new webRequestService(); //webRequestService svc = new webRequestService();
var data = svc.obixHisQuery_v2(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", "", //var data = svc.obixHisQuery_v2(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", "",
obixApiConfig.UserName, obixApiConfig.Password); // obixApiConfig.UserName, obixApiConfig.Password);
ds.AddRange(data); //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 //// save to history
await niagaraDataSynchronizeRepository.DeviceItemComparison(); //insert device_item //await niagaraDataSynchronizeRepository.InsertItemFromNiagara_History(ds, building); // insert 暫存table import_niagara_item_history
await niagaraDataSynchronizeRepository.CheckItemDiffFullNameAndCover(); // update device_item.fullname //if (!string.IsNullOrEmpty(isDome) && isDome.Contains("ibms_dome"))
await niagaraDataSynchronizeRepository.ItemCheckFullNameEmptyReplaceByDeviceName(); // 檢查device_item內FullName為空的值以points取代 // await niagaraDataSynchronizeRepository.RecoverSysTag("import_niagara_item_history"); // recover missing deivce_system_tag
await niagaraDataSynchronizeRepository.CheckItemIsShowHistory(); //#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; result = true;

View File

@ -729,5 +729,111 @@ namespace Backend.Services.Implement
// } // }
// } // }
//} //}
/// <summary>
/// 獲取 niagara history 中的點位
/// </summary>
/// <param name="bqlUrlString"></param>
/// <param name="urlString"></param>
/// <param name="slot"></param>
/// <returns></returns>
public List<DeviceControlPoint> 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<control_point> conPoint = new List<control_point>();
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 = "<str val='" + slot + "bql: select * from control:ControlPoint'/>";
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<DeviceControlPoint>();
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();
}
} }
} }

View File

@ -22,8 +22,8 @@
//"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel //"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel
//"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office //"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office
//"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut //"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut
//"Database": "+5RAiFLJVU+LRyDxF1K/pcLZaoZa4k/thZqF6xKoCag=", //dome_online_0821 "Database": "+5RAiFLJVU+LRyDxF1K/pcLZaoZa4k/thZqF6xKoCag=", //dome_online_0821
"Database": "2U+9jYGy0dCbMzLaguBXow==", //tpe_dome_mall //"Database": "2U+9jYGy0dCbMzLaguBXow==", //tpe_dome_mall
//"Database": "FbHCCU4CapG9UryANXC1W+iMe403Bd82RnA7bCNVbL0=", //ibms_dome_cinema, //"Database": "FbHCCU4CapG9UryANXC1W+iMe403Bd82RnA7bCNVbL0=", //ibms_dome_cinema,
"Root": "SzdxEgaJJ7tcTCrUl2zKsA==", "Root": "SzdxEgaJJ7tcTCrUl2zKsA==",
"Password": "FVAPxztxpY4gJJKQ/se4bQ==" "Password": "FVAPxztxpY4gJJKQ/se4bQ=="

View File

@ -15,6 +15,7 @@ using System.Web;
using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.Collections;
using System.Reflection; using System.Reflection;
using System.Drawing; using System.Drawing;
using Org.BouncyCastle.Asn1.Mozilla;
namespace Repository.BackendRepository.Implement 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 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')); (device_system_tag <> 'FM' or device_system_tag <> 'APS' or device_system_tag <> 'VICL'));
update import_niagara_tag a join dic_system b update import_niagara_tag a
on a.device_name_tag COLLATE utf8mb4_general_ci = b.s2_code 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'
set device_system_tag = b.s1_code -- tag () 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 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')); -- "); (device_system_tag <> 'FM' or device_system_tag <> 'APS' or device_system_tag <> 'VICL')); -- ");
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
@ -276,9 +278,10 @@ namespace Repository.BackendRepository.Implement
{ {
if (isDome.Contains("ibms_dome")) if (isDome.Contains("ibms_dome"))
{ {
sb.Append($@" update import_niagara_item a join dic_system b sb.Append($@" update import_niagara_item a
on a.device_name_tag COLLATE utf8mb4_0900_ai_ci = b.s2_code COLLATE utf8mb4_0900_ai_ci 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'
set device_system_tag = b.s1_code 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');"); where (device_system_tag <> 'S' and device_system_tag <> 'CWB' and device_system_tag <> 'B');");
} }
@ -1378,8 +1381,9 @@ device_floor_tag, device_master_tag, device_last_name_tag, device_serial_tag, d
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.Append($@"SET SQL_SAFE_UPDATES = 0; sb.Append($@"SET SQL_SAFE_UPDATES = 0;
update {tableName} a update {tableName} a
join dic_system ds on ds.s2_code = a.device_name_tag join variable v2 on v2.system_value = a.device_name_tag and v2.deleted = 0 and v2.system_type = 'device_system_category_layer3'
set a.device_system_tag = ds.s1_code 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 = '';"); where a.device_system_tag is null or a.device_system_tag = '';");
await conn.ExecuteAsync(sb.ToString()); await conn.ExecuteAsync(sb.ToString());
} }
@ -1394,5 +1398,74 @@ device_floor_tag, device_master_tag, device_last_name_tag, device_serial_tag, d
} }
} }
} }
/// <summary>
/// record all device control point
/// </summary>
/// <param name="dcp"></param>
/// <returns></returns>
public async Task DeviceControlPoint (List<DeviceControlPoint> 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();
}
}
}
} }
} }

View File

@ -82,5 +82,12 @@ namespace Repository.BackendRepository.Interface
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
Task RecoverSysTag(string tableName); Task RecoverSysTag(string tableName);
/// <summary>
/// record all device control point
/// </summary>
/// <param name="dcp"></param>
/// <returns></returns>
Task DeviceControlPoint(List<DeviceControlPoint> dcp);
} }
} }

View File

@ -164,4 +164,17 @@ namespace Repository.Models
public string area_tag { get; set; } public string area_tag { get; set; }
public string obixSlot { 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; }
}
} }