同步 明志後台同步流程, 排程同步流程

This commit is contained in:
dev02 2023-08-09 12:15:39 +08:00
parent e8cc2c9525
commit dad69be031
7 changed files with 390 additions and 69 deletions

View File

@ -205,7 +205,26 @@ namespace Backend.Controllers
await niagaraDataSynchronizeRepository.DeviceItemComparison(); //insert device_item
await niagaraDataSynchronizeRepository.CheckItemDiffFullNameAndCover(); // update device_item.fullname
await niagaraDataSynchronizeRepository.ItemCheckFullNameEmptyReplaceByDeviceName(); // 檢查device_item內FullName為空的值以points取代
await niagaraDataSynchronizeRepository.CheckItemIsShowHistory();
await niagaraDataSynchronizeRepository.CheckItemIsShowHistory();
#region
ds.Clear();
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 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
#endregion
result = true;
apiResult.Code = "0000";

View File

@ -434,6 +434,149 @@ namespace Backend.Services.Implement
return result;
}
/// <summary>
/// 獲取 niagara history 中的點位
/// </summary>
/// <param name="bqlUrlString"></param>
/// <param name="urlString"></param>
/// <param name="slot"></param>
/// <returns></returns>
public List<ImpNiaItem> obixHisQuery_v2(string bqlUrlString, string urlString, string slot, string acc, string pass)
{
//String username = "obixUser";
//String password = "Admin123456";
//String username = "stanGG";
//String password = "St12345678";
String username = acc;
String password = pass;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
String oneStationName = null;
#region get control point data
List<control_point> conPoint = new List<control_point>();
String cp_API_Url = bqlUrlString;
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);
//}
//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
#region main program
List<ImpNiaItem> result = new List<ImpNiaItem>();
String API_Url = urlString;
HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url);
Postrequest.Method = "GET";
Postrequest.Headers.Add("Authorization", "Basic " + encoded);
Postrequest.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseString);
// 1.循環所有的 station
//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
HttpWebRequest Postrequest2 = (HttpWebRequest)WebRequest.Create(API_Url2);
Postrequest2.Method = "GET";
Postrequest2.Headers.Add("Authorization", "Basic " + encoded);
Postrequest2.PreAuthenticate = true;
HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse();
var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(responseString2);
// 2.獲取 station 中全部的設備+點位
foreach (XmlNode node2 in xmlDoc2.DocumentElement.ChildNodes)
{
string tagName = node2.Attributes["name"].InnerText;
if (tagName.Split('_').Length == 9)
{
if (tagName.Split('_')[1].IndexOf("8F5") != -1)
{
string ss = tagName.Split('_')[1];
}
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_floor_tag = tagName.Split('_')[4];
row.device_master_tag = tagName.Split('_')[5];
row.device_last_name_tag = tagName.Split('_')[6];
row.device_serial_tag = tagName.Split('_')[7];
row.device_point_name = tagName.Split('_')[8];
row.parent_path = stationName;
result.Add(row);
}
else if (tagName.Split('_').Length == 6)
{ //巨蛋 tag 5 段版本
ImpNiaItem row = new ImpNiaItem();
if (tagName.Split('_')[1] == "S") //for security 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_system_tag = tagName.Split('_')[1];
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;
result.Add(row);
}
}
}
#endregion
return result.ToList();
//return result.Where(x => x.full_name != null).ToList();
}
//private static void getRefData(string urlString, string encoded, List<control_point> conPoint, List<ImpNiaItem> result, Welcome data ) //obixHistory data
//{
// foreach (var item in data.Obj.Ref)

View File

@ -128,7 +128,6 @@ namespace BackendWorkerService.Quartz.Jobs
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());
var station = await backgroundServiceRepository.GetOneAsync<string>($@"select system_value from variable where system_type = 'obixStatus' and deleted = 0");
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password));
#endregion obix
@ -161,6 +160,11 @@ namespace BackendWorkerService.Quartz.Jobs
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
device_number = deviceNumberPoint.FullDeviceNumberPoint;
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
@ -218,6 +222,11 @@ namespace BackendWorkerService.Quartz.Jobs
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
device_number = deviceNumberPoint.FullDeviceNumberPoint;
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
@ -629,6 +638,11 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
device_number = deviceNumberPoint.FullDeviceNumberPoint;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
@ -688,6 +702,11 @@ namespace BackendWorkerService.Quartz.Jobs
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
device_number = deviceNumberPoint.FullDeviceNumberPoint;
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
@ -997,6 +1016,11 @@ namespace BackendWorkerService.Quartz.Jobs
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
device_number = deviceNumberPoint.FullDeviceNumberPoint;
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";
@ -1054,6 +1078,11 @@ namespace BackendWorkerService.Quartz.Jobs
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
device_number = deviceNumberPoint.FullDeviceNumberPoint;
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST";

View File

@ -63,7 +63,6 @@ namespace BackendWorkerService.Services.Implement
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();
var station = await backgroundServiceRepository.GetOneAsync<string>($@"select system_value from variable where system_type = 'obixStatus' and deleted = 0");
encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password));
#endregion obix
@ -280,6 +279,12 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT1D' />
</obj>";
string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveDayRequest.Method = "POST";
@ -354,84 +359,90 @@ namespace BackendWorkerService.Services.Implement
var water_error_days = await backgroundServiceRepository.GetAllAsync<ArchiveElectricMeter>(sql_error_day, new { RepeatTimes = repeatTimes });
List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>();
if (water_error_days.Count() > 0)
{
foreach (var error_day in water_error_days)
{
DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint();
deviceNumberPoint.DeviceNumber = error_day.Device_number;
deviceNumberPoint.Point = error_day.Point;
deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", error_day.Device_number, error_day.Point);
var startTimestamp = string.Format("{0}+08:00", error_day.Start_timestamp.Replace(" ", "T"));
var endTimestamp = string.Format("{0}+08:00", error_day.End_timestamp.Replace(" ", "T"));
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name='start' val='{startTimestamp}' />
<abstime name='end' val='{endTimestamp}' />
<reltime name='interval' val = 'PT1D' />
</obj>";
HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveDayRequest.Method = "POST";
archiveDayRequest.Headers.Add("Authorization", "Basic " + encoded);
archiveDayRequest.PreAuthenticate = true;
byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter);
using (Stream reqStream = archiveDayRequest.GetRequestStream())
foreach (var error_day in water_error_days)
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint();
deviceNumberPoint.DeviceNumber = error_day.Device_number;
deviceNumberPoint.Point = error_day.Point;
deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", error_day.Device_number, error_day.Point);
HttpWebResponse archiveDayResponse = (HttpWebResponse)archiveDayRequest.GetResponse();
var archiveDayResponseContent = new StreamReader(archiveDayResponse.GetResponseStream()).ReadToEnd();
string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
var startTimestamp = string.Format("{0}+08:00", error_day.Start_timestamp.Replace(" ", "T"));
var endTimestamp = string.Format("{0}+08:00", error_day.End_timestamp.Replace(" ", "T"));
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name='start' val='{startTimestamp}' />
<abstime name='end' val='{endTimestamp}' />
<reltime name='interval' val = 'PT1D' />
</obj>";
xmlDocument.LoadXml(archiveDayResponseContent);
string archiveDayJson = JsonConvert.SerializeXmlNode(xmlDocument);
JObject archiveDayJsonResult = (JObject)JsonConvert.DeserializeObject(archiveDayJson);
HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveDayRequest.Method = "POST";
archiveDayRequest.Headers.Add("Authorization", "Basic " + encoded);
archiveDayRequest.PreAuthenticate = true;
if (archiveDayJsonResult.ContainsKey("err")) //抓取錯誤
{
Dictionary<string, object> archiveDayRawData = new Dictionary<string, object>();
archiveDayRawData.Add("@device_number", error_day.Device_number);
archiveDayRawData.Add("@point", error_day.Point);
archiveDayRawData.Add("@start_timestamp", DateTime.Parse(error_day.Start_timestamp, System.Globalization.CultureInfo.CurrentCulture));
archiveDayRawData.Add("@end_timestamp", DateTime.Parse(error_day.End_timestamp, System.Globalization.CultureInfo.CurrentCulture));
archiveDayRawData.Add("@is_complete", 0);
archiveDayRawData.Add("@repeat_times", ++error_day.Repeat_times);
archiveDayRawData.Add("@fail_reason", archiveDayJson);
archiveDayRawData.Add("@count_rawdata", 0);
archiveDayRawData.Add("@min_rawdata", 0);
archiveDayRawData.Add("@max_rawdata", 0);
archiveDayRawData.Add("@avg_rawdata", 0);
archiveDayRawData.Add("@sum_rawdata", 0);
archiveDayRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
waterArchiveDayRawDatas.Add(archiveDayRawData);
}
if (archiveDayJsonResult.ContainsKey("obj")) //表示可以讀取到內容
{
var ArrangeRawDatas = ArrangeRawData(deviceNumberPoint, archiveDayJsonResult);
if (ArrangeRawDatas != null && ArrangeRawDatas.Count() > 0)
byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter);
using (Stream reqStream = archiveDayRequest.GetRequestStream())
{
waterArchiveDayRawDatas.AddRange(ArrangeRawDatas);
reqStream.Write(byteArray, 0, byteArray.Length);
}
HttpWebResponse archiveDayResponse = (HttpWebResponse)archiveDayRequest.GetResponse();
var archiveDayResponseContent = new StreamReader(archiveDayResponse.GetResponseStream()).ReadToEnd();
xmlDocument.LoadXml(archiveDayResponseContent);
string archiveDayJson = JsonConvert.SerializeXmlNode(xmlDocument);
JObject archiveDayJsonResult = (JObject)JsonConvert.DeserializeObject(archiveDayJson);
if (archiveDayJsonResult.ContainsKey("err")) //抓取錯誤
{
Dictionary<string, object> archiveDayRawData = new Dictionary<string, object>();
archiveDayRawData.Add("@device_number", error_day.Device_number);
archiveDayRawData.Add("@point", error_day.Point);
archiveDayRawData.Add("@start_timestamp", DateTime.Parse(error_day.Start_timestamp, System.Globalization.CultureInfo.CurrentCulture));
archiveDayRawData.Add("@end_timestamp", DateTime.Parse(error_day.End_timestamp, System.Globalization.CultureInfo.CurrentCulture));
archiveDayRawData.Add("@is_complete", 0);
archiveDayRawData.Add("@repeat_times", ++error_day.Repeat_times);
archiveDayRawData.Add("@fail_reason", archiveDayJson);
archiveDayRawData.Add("@count_rawdata", 0);
archiveDayRawData.Add("@min_rawdata", 0);
archiveDayRawData.Add("@max_rawdata", 0);
archiveDayRawData.Add("@avg_rawdata", 0);
archiveDayRawData.Add("@sum_rawdata", 0);
archiveDayRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
waterArchiveDayRawDatas.Add(archiveDayRawData);
}
if (archiveDayJsonResult.ContainsKey("obj")) //表示可以讀取到內容
{
var ArrangeRawDatas = ArrangeRawData(deviceNumberPoint, archiveDayJsonResult);
if (ArrangeRawDatas != null && ArrangeRawDatas.Count() > 0)
{
waterArchiveDayRawDatas.AddRange(ArrangeRawDatas);
}
}
}
}
if (waterArchiveDayRawDatas.Count() > 0)
{
var Mysql_error_update = string.Format(MYsql_update_format, targetTable);
var sql_error_update = string.Format(sql_update_format, targetTable);
if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1")
if (waterArchiveDayRawDatas.Count() > 0)
{
await backgroundServiceMsSqlRepository.ExecuteSql(sql_error_update, waterArchiveDayRawDatas);
var Mysql_error_update = string.Format(MYsql_update_format, targetTable);
var sql_error_update = string.Format(sql_update_format, targetTable);
if (!string.IsNullOrEmpty(saveToMSDB) && saveToMSDB == "1")
{
await backgroundServiceMsSqlRepository.ExecuteSql(sql_error_update, waterArchiveDayRawDatas);
}
await backgroundServiceRepository.ExecuteSql(Mysql_error_update, waterArchiveDayRawDatas);
}
await backgroundServiceRepository.ExecuteSql(Mysql_error_update, waterArchiveDayRawDatas);
}
}
}
#endregion
#region
@ -458,6 +469,12 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT7D' />
</obj>";
string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveWeekRequest.Method = "POST";
@ -542,6 +559,12 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT7D' />
</obj>";
string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveWeekRequest.Method = "POST";
@ -632,6 +655,12 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT{dayInMonth}D' />
</obj>";
string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveMonthRequest.Method = "POST";
@ -719,6 +748,12 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT{dayInMonth}D' />
</obj>";
string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
var station = backgroundServiceRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{device_number.Split("_")[1].Replace("$3", "")}' and
device_system_tag = '{device_number.Split("_")[2]}' and device_name_tag = '{device_number.Split("_")[3]}'
and device_floor_tag = '{device_number.Split("_")[4]}' and device_master_tag = '{device_number.Split("_")[5]}'
and device_last_name_tag = '{device_number.Split("_")[6]}' and device_serial_tag = '{device_number.Split("_")[7]}'
and device_point_name = '{device_number.Split("_")[8]}'").Result;
HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveMonthRequest.Method = "POST";

View File

@ -1060,5 +1060,95 @@ namespace Repository.BackendRepository.Implement
}
}
}
public async Task InsertItemFromNiagara_History(List<ImpNiaItem> ds, List<string> building)
{
using (IDbConnection conn = GetDbConnection())
{
conn.Open();
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
try
{
//改成每次都新增
string sql = @"SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for import_niagara_item_history
-- ----------------------------
DROP TABLE IF EXISTS `import_niagara_item_history`;
CREATE TABLE `import_niagara_item_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`device_area_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_building_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_system_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_name_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_floor_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_master_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_last_name_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_serial_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_point_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`parent_path` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`is_history` bit(1) NULL DEFAULT b'0',
`full_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`check_status` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 271 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;";
await conn.ExecuteAsync(sql);
#region import_niagara_item資料表中選取的棟別
//foreach (var b in building)
//{
// sql = "delete from import_niagara_item_history where device_building_tag = '" + b + "'";
// await conn.ExecuteAsync(sql);
//}
#endregion
StringBuilder sb = new StringBuilder();
#region import_niagara_item資料表
foreach (var row in ds)
{
string ss = $@" insert import_niagara_item_history(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, device_point_name, parent_path, full_name, is_history, created_at)
values('" +
row.device_area_tag + "', '" +
row.device_building_tag + "', '" +
row.device_system_tag + "', '" +
row.device_name_tag + "', '" +
row.device_floor_tag + "', '" +
row.device_master_tag + "', '" +
row.device_last_name_tag + "', '" +
row.device_serial_tag + "', '" +
row.device_point_name + "', '" +
row.parent_path + "', '" +
row.full_name + "'," +
row.isHistory + ", now() " +
");";
sb.Append(ss);
}
if (sb.Length > 0)
{
await conn.ExecuteAsync(sb.ToString());
sb.Clear();
}
#endregion
}
catch (Exception exception)
{
throw exception;
}
finally
{
conn.Close();
}
}
}
}
}
}

View File

@ -41,7 +41,7 @@ namespace Repository.BackendRepository.Interface
Task CheckItemIsShowHistory();
Task InsertItemFromNiagara_History(List<ImpNiaItem> ds, List<string> building);
/// <summary>
/// 比對 device的FullName若為空則以DeviceName取代
/// </summary>

View File

@ -123,6 +123,11 @@ namespace Repository.Models
public string check_status { get; set; }
public string full_name { get; set; }
public bool isHistory { get; set; }
public string device_master_tag { get; set; } //add by jiahao 2023-07-23
public string device_last_name_tag { get; set; }//add by jiahao 2023-07-23
public string device_serial_tag { get; set; }//add by jiahao 2023-07-23
}
public class control_point