This commit is contained in:
dev01 2023-07-25 12:19:04 +08:00
commit a79a896641
15 changed files with 776 additions and 321 deletions

View File

@ -162,12 +162,12 @@ namespace Backend.Controllers
//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<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)
{ //{
var data = svc.obixHisQuery(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", us, var data = svc.obixHisQuery(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);
} // }
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";
@ -207,6 +207,25 @@ namespace Backend.Controllers
await niagaraDataSynchronizeRepository.CheckItemDiffFullNameAndCover(); // update device_item.fullname await niagaraDataSynchronizeRepository.CheckItemDiffFullNameAndCover(); // update device_item.fullname
await niagaraDataSynchronizeRepository.ItemCheckFullNameEmptyReplaceByDeviceName(); // 檢查device_item內FullName為空的值以points取代 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; result = true;
apiResult.Code = "0000"; apiResult.Code = "0000";

View File

@ -131,6 +131,149 @@ namespace Backend.Services.Implement
return result; 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();
}
/// <summary> /// <summary>
/// 獲取 niagara history 中的點位 /// 獲取 niagara history 中的點位
/// </summary> /// </summary>
@ -204,7 +347,7 @@ namespace Backend.Services.Implement
xmlDoc.LoadXml(responseString); xmlDoc.LoadXml(responseString);
//ref https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c //ref https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) //循環所有的 station
{ {
var stationName = node.Attributes["name"].InnerText; // WSP_Supervisor var stationName = node.Attributes["name"].InnerText; // WSP_Supervisor
oneStationName = oneStationName ?? stationName; oneStationName = oneStationName ?? stationName;
@ -328,6 +471,8 @@ namespace Backend.Services.Implement
return result.Where(x => x.full_name != null).ToList(); return result.Where(x => x.full_name != null).ToList();
} }
public List<Device_value_disaster> obixDevDisaster(string urlString, string bql, string tag_quantity, string acc, string pass, string dt) public List<Device_value_disaster> obixDevDisaster(string urlString, string bql, string tag_quantity, string acc, string pass, string dt)
{ {
List<Device_value_disaster> result = new List<Device_value_disaster>(); List<Device_value_disaster> result = new List<Device_value_disaster>();

View File

@ -7,6 +7,7 @@ using Microsoft.Extensions.Options;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using Quartz; using Quartz;
using Repository.BackendRepository.Implement;
using Repository.BackendRepository.Interface; using Repository.BackendRepository.Interface;
using Repository.Helper; using Repository.Helper;
using System; using System;
@ -47,6 +48,7 @@ namespace BackendWorkerService.Quartz.Jobs
public async Task Execute(IJobExecutionContext context) public async Task Execute(IJobExecutionContext context)
{ {
Task_Detail task_Detail = new Task_Detail(loggers, backgroundServiceRepository); Task_Detail task_Detail = new Task_Detail(loggers, backgroundServiceRepository);
string device_number = string.Empty;
try try
{ {
if(await task_Detail.GetNeedWorkTask("ArchiveElectricMeterDayJob", "All")) if(await task_Detail.GetNeedWorkTask("ArchiveElectricMeterDayJob", "All"))
@ -159,8 +161,17 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints) foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{ {
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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;
if (string.IsNullOrEmpty(station))
{
continue;
}
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/"); //HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -216,8 +227,13 @@ namespace BackendWorkerService.Quartz.Jobs
} }
foreach (var deviceNumberPoint in waterDeviceNumberPoints) foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{ {
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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/"); //HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -628,8 +644,17 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints) foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{ {
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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;
if (string.IsNullOrEmpty(station))
{
continue;
}
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/"); //HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -686,8 +711,13 @@ namespace BackendWorkerService.Quartz.Jobs
} }
foreach (var deviceNumberPoint in waterDeviceNumberPoints) foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{ {
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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/"); //HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -995,8 +1025,17 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveMonthRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> waterArchiveMonthRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints) foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{ {
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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;
if (string.IsNullOrEmpty(station))
{
continue;
}
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/"); //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -1052,8 +1091,13 @@ namespace BackendWorkerService.Quartz.Jobs
} }
foreach (var deviceNumberPoint in waterDeviceNumberPoints) foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{ {
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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/"); //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -1354,13 +1398,15 @@ namespace BackendWorkerService.Quartz.Jobs
{ {
await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "All", exception.ToString()); await task_Detail.WorkFail("ArchiveElectricMeterDayJob", "All", exception.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】"); logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】");
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[Exception]{0}", exception.ToString()); logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[Exception]{0} {1}", exception.ToString());
} }
} }
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult) private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{ {
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>(); List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
try
{
var histories = jsonResult["obj"]["list"]; var histories = jsonResult["obj"]["list"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString()); var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
@ -1415,19 +1461,19 @@ namespace BackendWorkerService.Quartz.Jobs
switch (name) switch (name)
{ {
case "min": case "min":
var min = Convert.ToDecimal(real["@val"].ToString()); var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": case "max":
var max = Convert.ToDecimal(real["@val"].ToString()); var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString()); var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); var sum = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum); arrangeRawData.Add("@sum_rawdata", sum);
break; break;
} }
@ -1483,19 +1529,19 @@ namespace BackendWorkerService.Quartz.Jobs
switch (name) switch (name)
{ {
case "min": case "min":
var min = Convert.ToDecimal(real["@val"].ToString()); var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": case "max":
var max = Convert.ToDecimal(real["@val"].ToString()); var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString()); var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); var sum = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum); arrangeRawData.Add("@sum_rawdata", sum);
break; break;
} }
@ -1512,5 +1558,14 @@ namespace BackendWorkerService.Quartz.Jobs
return arrangeRawDatas; return arrangeRawDatas;
} }
catch (Exception exception)
{
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】");
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[Exception]{0}", exception.ToString());
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[device_number]{0}", deviceNumberPoint.FullDeviceNumberPoint);
logger.LogError("【ArchiveElectricMeterDayJob】【任務失敗】[JsonString]{0}", jsonResult.ToString());
return arrangeRawDatas;
}
}
} }
} }

View File

@ -189,7 +189,7 @@ namespace BackendWorkerService.Services.Implement
// <reltime name='interval' val = 'PT1H' /> // <reltime name='interval' val = 'PT1H' />
// </obj>"; // </obj>";
// HttpWebRequest archiveHourRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); // HttpWebRequest archiveHourRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
// //HttpWebRequest archiveHourRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); // //HttpWebRequest archiveHourRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
// archiveHourRequest.Method = "POST"; // archiveHourRequest.Method = "POST";
// archiveHourRequest.Headers.Add("Authorization", "Basic " + encoded); // archiveHourRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -280,8 +280,13 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT1D' /> <reltime name='interval' val = 'PT1D' />
</obj>"; </obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); //HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveDayRequest.Method = "POST"; archiveDayRequest.Method = "POST";
archiveDayRequest.Headers.Add("Authorization", "Basic " + encoded); archiveDayRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -371,8 +376,13 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT1D' /> <reltime name='interval' val = 'PT1D' />
</obj>"; </obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); //HttpWebRequest archiveDayRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveDayRequest.Method = "POST"; archiveDayRequest.Method = "POST";
archiveDayRequest.Headers.Add("Authorization", "Basic " + encoded); archiveDayRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -460,8 +470,13 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT7D' /> <reltime name='interval' val = 'PT7D' />
</obj>"; </obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); //HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveWeekRequest.Method = "POST"; archiveWeekRequest.Method = "POST";
archiveWeekRequest.Headers.Add("Authorization", "Basic " + encoded); archiveWeekRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -545,8 +560,13 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT7D' /> <reltime name='interval' val = 'PT7D' />
</obj>"; </obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); //HttpWebRequest archiveWeekRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveWeekRequest.Method = "POST"; archiveWeekRequest.Method = "POST";
archiveWeekRequest.Headers.Add("Authorization", "Basic " + encoded); archiveWeekRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -636,8 +656,13 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT{dayInMonth}D' /> <reltime name='interval' val = 'PT{dayInMonth}D' />
</obj>"; </obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveMonthRequest.Method = "POST"; archiveMonthRequest.Method = "POST";
archiveMonthRequest.Headers.Add("Authorization", "Basic " + encoded); archiveMonthRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -724,8 +749,13 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT{dayInMonth}D' /> <reltime name='interval' val = 'PT{dayInMonth}D' />
</obj>"; </obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault(); string device_number = deviceNumberPoint.FullDeviceNumberPoint.Replace("$3", "");
HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/"); 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.Replace("$3", "")}/~historyRollup/");
//HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/"); //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
archiveMonthRequest.Method = "POST"; archiveMonthRequest.Method = "POST";
archiveMonthRequest.Headers.Add("Authorization", "Basic " + encoded); archiveMonthRequest.Headers.Add("Authorization", "Basic " + encoded);
@ -855,15 +885,15 @@ namespace BackendWorkerService.Services.Implement
switch (name) switch (name)
{ {
case "min": case "min":
var min = Convert.ToDecimal(real["@val"].ToString()); var min = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": case "max":
var max = Convert.ToDecimal(real["@val"].ToString()); var max = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString()); var avg = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
@ -923,15 +953,15 @@ namespace BackendWorkerService.Services.Implement
switch (name) switch (name)
{ {
case "min": case "min":
var min = Convert.ToDecimal(real["@val"].ToString()); var min = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": case "max":
var max = Convert.ToDecimal(real["@val"].ToString()); var max = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString()); var avg = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":

View File

@ -283,8 +283,7 @@
$('#devPointsList').html(strHtml); $('#devPointsList').html(strHtml);
if (!hisFirst) if (!hisFirst) {
{
let start = new Date($('#his_startdate').val()); let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1)); let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
@ -309,7 +308,16 @@
var edt = new Date(new Date().setDate(sdt.getDate() + 1)); var edt = new Date(new Date().setDate(sdt.getDate() + 1));
start = start ?? sdt.toLocaleDateString(); start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString(); end = end ?? edt.toLocaleDateString();
// callBackFromHistory();
let sendData = {
device_number: pageAct.deviceNumber,
device_point: pageAct.deviceItem
}
objSendData.Data = sendData;
let url = baseApiUrl + "/api/DevGetWay";
ytAjax = new YourTeam.Ajax(url, objSendData, function (res) {
if (res && res.code == "0000") {
pageAct.hisBuiName = res.data;
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem, getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(), new Date(start).getTime(),
new Date(end).getTime(), new Date(end).getTime(),
@ -317,6 +325,11 @@
pageAct.hisBuiName, pageAct.hisBuiName,
callBackFromHistory); callBackFromHistory);
} }
else {
$(loadEle).Loading("close");
}
}, function (res) { $(loadEle).Loading("close"); }, "POST", true).send();
}
function callBackFromHistory(res = '{"count":0,"data":[]}') { function callBackFromHistory(res = '{"count":0,"data":[]}') {
res = JSON.parse(res); res = JSON.parse(res);
@ -496,6 +509,7 @@
v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val())); v.starttime = (pageAct.dateType == "month" ? new Date($('#getmonth').val()) : new Date($('#his_startdate').val()));
v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val()); v.endtime = $('#his_enddate input').val() === "" ? null : new Date($('#his_enddate input').val());
v.dateType = pageAct.dateType; v.dateType = pageAct.dateType;
v.device_number = pageAct.deviceNumber;
objSendData.Data = v; objSendData.Data = v;
$.ajax({ $.ajax({

View File

@ -1,4 +1,5 @@
using FrontendWebApi.Models; using FrontendWebApi.Models;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
@ -58,10 +59,13 @@ namespace FrontendWebApi.ApiControllers
// apiResult.Msg = "沒有資料匯入"; // apiResult.Msg = "沒有資料匯入";
// return apiResult; // return apiResult;
//} //}
var fileDateName = lhe.dateType == "today" ? lhe.starttime.ToString("yyyy-MM-dd") string fileDateName = lhe.dateType == "today" ? lhe.starttime.ToString("yyyy-MM-dd")
: lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM") : lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM")
: lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd"); : lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_" + fileDateName + ".xlsx"; string fileName = "歷史資料_" + fileDateName + ".xlsx";
lhe.device_number = char.IsDigit(lhe.device_number.Split("_")[1][0])
? lhe.device_number.Replace(lhe.device_number.Split("_")[1], "$3" + lhe.device_number.Split("_")[1])
: lhe.device_number;
XSSFWorkbook workbook = new XSSFWorkbook(); XSSFWorkbook workbook = new XSSFWorkbook();
try try
{ {
@ -79,25 +83,22 @@ namespace FrontendWebApi.ApiControllers
var buildStation = backendRepository.GetAllAsync<BuildStation>("select SUBSTRING_INDEX(system_value, '/', 1) system_value, system_key from variable where system_type = 'dashboard_total_elec' and deleted = 0 and (SUBSTRING_INDEX(system_value, '/', 1) != '' and SUBSTRING_INDEX(system_value, '/', 1) is not null)").Result; var buildStation = backendRepository.GetAllAsync<BuildStation>("select SUBSTRING_INDEX(system_value, '/', 1) system_value, system_key from variable where system_type = 'dashboard_total_elec' and deleted = 0 and (SUBSTRING_INDEX(system_value, '/', 1) != '' and SUBSTRING_INDEX(system_value, '/', 1) is not null)").Result;
#region get device and device_item(point) #region get device and device_item(point)
var device = backendRepository.GetAllAsync<Device>($"select * from device where deleted = 0 and is_link = 1 and device_building_tag in ('{string.Join("','", building.Select(x => x.building_tag))}')").Result; var device = backendRepository.GetAllAsync<Device>($"select * from device where deleted = 0 and is_link = 1 and device_number = '{lhe.device_number}'").Result;
var devicePoint = backendRepository.GetAllAsync<Device_item>($"select * from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 and device_building_tag in ('{string.Join("','", building.Select(x => x.building_tag))}')").Result; var devicePoint = backendRepository.GetAllAsync<Device_item>($"select * from device_item where deleted = 0 and is_link = 1 and is_show_history = 1 and device_building_tag = '{lhe.device_number.Split("_")[1]}' and device_system_tag = '{lhe.device_number.Split("_")[2]}' and device_name_tag = '{lhe.device_number.Split("_")[3]}'").Result;
#endregion #endregion
List<DeviceNumberPoint> listDevicePoint = new List<DeviceNumberPoint>(); List<DeviceNumberPoint> listDevicePoint = new List<DeviceNumberPoint>();
#region combine device and point #region combine device and point
foreach (var d in device) var dp = devicePoint.Where(x => x.device_building_tag == lhe.device_number.Split("_")[1]).ToList();
{
var dp = devicePoint.Where(x => x.device_building_tag == d.device_building_tag).ToList();
foreach (var point in dp) foreach (var point in dp)
{ {
DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint(); DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint();
deviceNumberPoint.DeviceNumber = d.device_number; deviceNumberPoint.DeviceNumber = lhe.device_number;
deviceNumberPoint.Point = point.points; deviceNumberPoint.Point = point.points;
deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", d.device_number, point.points); deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", lhe.device_number, point.points);
listDevicePoint.Add(deviceNumberPoint); listDevicePoint.Add(deviceNumberPoint);
} }
}
#endregion #endregion
#region get data from niagara #region get data from niagara
@ -117,8 +118,15 @@ namespace FrontendWebApi.ApiControllers
foreach (var d in listDevicePoint) foreach (var d in listDevicePoint)
{ {
string buildingTag = d.DeviceNumber.Split("_")[1]; string buildingTag = d.DeviceNumber.Split("_")[1];
var station = buildStation.Where(x => x.system_key == buildingTag).Select(x => x.system_value).FirstOrDefault(); var station = backendRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{d.FullDeviceNumberPoint.Split("_")[1].Replace("$3", "")}' and
var archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint}/~historyRollup/"); device_system_tag = '{d.FullDeviceNumberPoint.Split("_")[2]}' and device_name_tag = '{d.FullDeviceNumberPoint.Split("_")[3]}'
and device_floor_tag = '{d.FullDeviceNumberPoint.Split("_")[4]}' and device_master_tag = '{d.FullDeviceNumberPoint.Split("_")[5]}'
and device_last_name_tag = '{d.FullDeviceNumberPoint.Split("_")[6]}' and device_serial_tag = '{d.FullDeviceNumberPoint.Split("_")[7]}'
and device_point_name = '{d.FullDeviceNumberPoint.Split("_")[8]}'").Result;
if (!string.IsNullOrEmpty(station))
{
var archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint.Replace("$3", "")}/~historyRollup/");
archiveRequest.Method = "POST"; archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded); archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
archiveRequest.PreAuthenticate = true; archiveRequest.PreAuthenticate = true;
@ -148,6 +156,11 @@ namespace FrontendWebApi.ApiControllers
jd.Add(jsonDevice); jd.Add(jsonDevice);
} }
} }
else
{
Logger.LogError("【Device GetWay Error】, device_number: " + d.FullDeviceNumberPoint);
}
}
} }
if (jd != null && jd.Count > 0) if (jd != null && jd.Count > 0)
@ -162,7 +175,7 @@ namespace FrontendWebApi.ApiControllers
HistoryExport hed = new HistoryExport(); HistoryExport hed = new HistoryExport();
hed.type = devicePoint.Where(x => x.device_building_tag == d.building_tag && x.points == ard["@point"].ToString()).Select(x => x.full_name).FirstOrDefault(); hed.type = devicePoint.Where(x => x.device_building_tag == d.building_tag && x.points == ard["@point"].ToString()).Select(x => x.full_name).FirstOrDefault();
hed.deviceName = device.Where(x => x.device_number == ard["@device_number"].ToString()).Select(x => x.full_name).FirstOrDefault(); hed.deviceName = device.Where(x => x.device_number == ard["@device_number"].ToString()).Select(x => x.full_name).FirstOrDefault();
hed.value = (double)((decimal)ard["@avg_rawdata"]); hed.value = ard["@avg_rawdata"].ToString() == "-1" ? "NaN" : Math.Round((decimal.Parse(ard["@avg_rawdata"].ToString(), System.Globalization.NumberStyles.Float)), 2).ToString();
hed.timestamp = Convert.ToDateTime(ard["@start_timestamp"].ToString()); hed.timestamp = Convert.ToDateTime(ard["@start_timestamp"].ToString());
hed.building_tag = d.building_tag; hed.building_tag = d.building_tag;
he.Add(hed); he.Add(hed);
@ -173,12 +186,6 @@ namespace FrontendWebApi.ApiControllers
#endregion #endregion
#region export file progress #region export file progress
//var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
//if (!System.IO.Directory.Exists(filePath))
// System.IO.Directory.CreateDirectory(filePath);
#region excel設定 #region excel設定
IFont font12 = workbook.CreateFont(); IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體"; font12.FontName = "新細明體";
@ -220,14 +227,16 @@ namespace FrontendWebApi.ApiControllers
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true; stylein12.WrapText = true;
#endregion #endregion
var data = he.ToList();
foreach (var b in building) if (data.Count > 0)
{ {
var data = he.Where(x => x.building_tag == b.building_tag).ToList(); string lastDeviceItem = string.Empty;
ISheet sheet = workbook.CreateSheet($"{b.full_name}歷史資料");
int RowPosition = 0; int RowPosition = 0;
IRow row;
ISheet sheet;
#region set cell #region set cell
IRow row = sheet.CreateRow(RowPosition); sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == lhe.device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + data[0].type}");
row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12); sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12); sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12); sheet.SetColumnWidth(2, 4 * 160 * 12);
@ -245,11 +254,40 @@ namespace FrontendWebApi.ApiControllers
cell.CellStyle = styleLine12; cell.CellStyle = styleLine12;
#endregion #endregion
if (data.Count > 0)
{
foreach (var d in data) foreach (var d in data)
{ {
if (RowPosition == 0 && lastDeviceItem == "")
{
lastDeviceItem = d.type; //第一次不用建立 sheet;
}
if (d.type != lastDeviceItem)
{
lastDeviceItem = d.type;
sheet = workbook.CreateSheet($"{building.Where(x => x.building_tag == lhe.device_number.Split("_")[1]).Select(x => x.full_name).FirstOrDefault()}{"_" + d.type}");
#region set cell
row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);
sheet.SetColumnWidth(1, 4 * 160 * 12);
sheet.SetColumnWidth(2, 4 * 160 * 12);
sheet.SetColumnWidth(3, 4 * 160 * 12);
cell = row.CreateCell(0);
cell.SetCellValue("類型");
cell.CellStyle = styleLine12;
cell = row.CreateCell(1);
cell.SetCellValue("設備名稱");
cell.CellStyle = styleLine12;
cell = row.CreateCell(2);
cell.SetCellValue("數值");
cell = row.CreateCell(3);
cell.SetCellValue("記錄時間");
cell.CellStyle = styleLine12;
#endregion
RowPosition = 0;
}
else {
RowPosition += 1; RowPosition += 1;
}
row = sheet.CreateRow(RowPosition); row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++) for (var i = 0; i < 4; i++)
{ {
@ -275,20 +313,7 @@ namespace FrontendWebApi.ApiControllers
} }
} }
} }
}
//using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write))
//{
//workbook.Write(fs);
//}
#endregion #endregion
//apiResult.Code = "0000";
//apiResult.Data = "history/" + fileName;
} }
catch (Exception exception) catch (Exception exception)
{ {
@ -451,7 +476,7 @@ namespace FrontendWebApi.ApiControllers
List<DeviceItem> deviceItems = new List<DeviceItem>(); List<DeviceItem> deviceItems = new List<DeviceItem>();
var main_system_value = hf.device_number.Split('_')[2]; var main_system_value = hf.device_number.Split('_')[2];
var sub_system_value = hf.device_number.Split('_')[3]; var sub_system_value = hf.device_number.Split('_')[3];
var building_tag = hf.device_number.Split('_')[1]; var building_tag = char.IsDigit(hf.device_number.Split('_')[1][0]) ? "$3" + hf.device_number.Split('_')[1] : hf.device_number.Split('_')[1];
var sqlString = $@"select * from device_item where deleted = 0 and device_system_tag = @main_system_value and device_name_tag = @sub_system_value and is_show_history = 1 and device_building_tag = @building_tag"; var sqlString = $@"select * from device_item where deleted = 0 and device_system_tag = @main_system_value and device_name_tag = @sub_system_value and is_show_history = 1 and device_building_tag = @building_tag";
deviceItems = await frontendRepository.GetAllAsync<DeviceItem>(sqlString, new { @main_system_value = main_system_value, @sub_system_value = sub_system_value, building_tag = building_tag }); deviceItems = await frontendRepository.GetAllAsync<DeviceItem>(sqlString, new { @main_system_value = main_system_value, @sub_system_value = sub_system_value, building_tag = building_tag });
@ -1391,19 +1416,19 @@ namespace FrontendWebApi.ApiControllers
switch (name) switch (name)
{ {
case "min": case "min":
var min = Convert.ToDecimal(real["@val"].ToString()); var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": case "max":
var max = Convert.ToDecimal(real["@val"].ToString()); var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString()); var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); var sum = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum); arrangeRawData.Add("@sum_rawdata", sum);
break; break;
} }
@ -1459,19 +1484,19 @@ namespace FrontendWebApi.ApiControllers
switch (name) switch (name)
{ {
case "min": case "min":
var min = Convert.ToDecimal(real["@val"].ToString()); var min = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@min_rawdata", min); arrangeRawData.Add("@min_rawdata", min);
break; break;
case "max": case "max":
var max = Convert.ToDecimal(real["@val"].ToString()); var max = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@max_rawdata", max); arrangeRawData.Add("@max_rawdata", max);
break; break;
case "avg": case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString()); var avg = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@avg_rawdata", avg); arrangeRawData.Add("@avg_rawdata", avg);
break; break;
case "sum": case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float); var sum = real["@val"].ToString() == "NaN" ? -1 : Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum); arrangeRawData.Add("@sum_rawdata", sum);
break; break;
} }

View File

@ -117,7 +117,7 @@ namespace FrontendWebApi.ApiControllers
var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})"; var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})";
var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date"; var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1; var sql = $@"set @i = -1;
select fd.device_number, aemm.avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp select fd.device_number, case when aemm.avg_rawdata = -1 then 'NaN' when aemm.avg_rawdata is null then 0.00 else aemm.avg_rawdata end as avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
from ( from (
select * select *
from ( from (
@ -164,7 +164,7 @@ namespace FrontendWebApi.ApiControllers
foreach (var l in list) foreach (var l in list)
{ {
l.rawData = new List<HydroMeterRawDataOutput>(); l.rawData = new List<HydroMeterRawDataOutput>();
l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}' and deleted = 0"); l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}'");
if (tag_quantity == "5") if (tag_quantity == "5")
{ {
l.rawData.AddRange( l.rawData.AddRange(
@ -179,7 +179,7 @@ namespace FrontendWebApi.ApiControllers
} }
l.building_name = await backendRepository.GetOneAsync<string>("select full_name from building where building_tag = @building_tag and deleted = 0", l.building_name = await backendRepository.GetOneAsync<string>("select full_name from building where building_tag = @building_tag and deleted = 0",
new { building_tag = l.building_tag }); new { building_tag = l.building_tag });
l.total = l.rawData.Sum(x => x.avg_rawdata).ToString(); l.total = l.rawData.Where(x => x.avg_rawdata != "NaN").Sum(x => decimal.Parse(x.avg_rawdata ?? "0", System.Globalization.NumberStyles.Float)).ToString();
l.price = input.price.HasValue l.price = input.price.HasValue
? (Math.Round(input.price.Value, 2)).ToString() ? (Math.Round(input.price.Value, 2)).ToString()
: Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'ElectricPrice' and deleted = 0")), 2).ToString(); : Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'ElectricPrice' and deleted = 0")), 2).ToString();
@ -289,7 +289,7 @@ namespace FrontendWebApi.ApiControllers
var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})"; var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})";
var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date"; var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1; var sql = $@"set @i = -1;
select fd.device_number, aemm.avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp select fd.device_number, case when aemm.avg_rawdata = -1 then 'NaN' when aemm.avg_rawdata is null then 0.00 else aemm.avg_rawdata end as avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
from ( from (
select * select *
from ( from (
@ -337,7 +337,7 @@ namespace FrontendWebApi.ApiControllers
foreach (var l in list) foreach (var l in list)
{ {
l.rawData = new List<HydroMeterRawDataOutput>(); l.rawData = new List<HydroMeterRawDataOutput>();
l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}' and deleted = 0"); l.device_full_name = await backendRepository.GetOneAsync<string>($"select full_name from device where device_number = '{l.device_number}'");
if (tag_quantity == "5") if (tag_quantity == "5")
{ {
l.rawData.AddRange( l.rawData.AddRange(
@ -352,7 +352,7 @@ namespace FrontendWebApi.ApiControllers
} }
l.building_name = await backendRepository.GetOneAsync<string>("select full_name from building where building_tag = @building_tag and deleted = 0", l.building_name = await backendRepository.GetOneAsync<string>("select full_name from building where building_tag = @building_tag and deleted = 0",
new { building_tag = l.building_tag }); new { building_tag = l.building_tag });
l.total = l.rawData.Sum(x => x.avg_rawdata).ToString(); l.total = l.rawData.Where(x => x.avg_rawdata != "NaN").Sum(x => decimal.Parse(x.avg_rawdata, System.Globalization.NumberStyles.Float)).ToString();
l.price = input.price.HasValue l.price = input.price.HasValue
? (Math.Round(input.price.Value, 2)).ToString() ? (Math.Round(input.price.Value, 2)).ToString()
: Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'WaterPrice' and deleted = 0")), 2).ToString(); : Math.Round((await backendRepository.GetOneAsync<decimal>("select system_value from variable where system_type = 'WaterPrice' and deleted = 0")), 2).ToString();

View File

@ -175,5 +175,47 @@ namespace FrontendWebApi.ApiControllers
} }
return Ok(apiResult); return Ok(apiResult);
} }
[HttpPost]
[Route("api/DevGetWay")]
public async Task<ActionResult<ApiResult<string>>> GetDevGetWay([FromBody] DeviceGetWayInput input)
{
ApiResult<string> apiResult = new ApiResult<string>(jwt_str);
//check input
if (input == null || string.IsNullOrEmpty(input.device_number) || string.IsNullOrEmpty(input.device_point))
{
apiResult.Code = "9998";
apiResult.Msg = "資料輸入錯誤。";
return Ok(apiResult);
}
try
{
var getWayStr = await backendRepository.GetOneAsync<string>($@"select parent_path from import_niagara_item_history where device_building_tag = '{input.device_number.Split("_")[1]}'
and device_system_tag = '{input.device_number.Split("_")[2]}' and device_name_tag = '{input.device_number.Split("_")[3]}'
and device_floor_tag = '{input.device_number.Split("_")[4]}' and device_master_tag = '{input.device_number.Split("_")[5]}'
and device_last_name_tag = '{input.device_number.Split("_")[6]}' and device_serial_tag = '{input.device_number.Split("_")[7]}'
and device_point_name = '{input.device_point}'");
//check string
if (string.IsNullOrEmpty(getWayStr))
{
apiResult.Code = "9997";
apiResult.Msg = "資料獲取錯誤。";
return Ok(apiResult);
}
apiResult.Data = getWayStr;
apiResult.Code = "0000";
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。";
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
}
return Ok(apiResult);
}
} }
} }

View File

@ -195,5 +195,9 @@ namespace FrontendWebApi.Models
} }
public class DeviceGetWayInput
{
public string device_number { get; set; }
public string device_point { get; set; }
}
} }

View File

@ -292,13 +292,14 @@ namespace FrontendWebApi.Models
public class HistoryExport public class HistoryExport
{ {
public string deviceName { get; set; } public string deviceName { get; set; }
public double value { get; set; } public string value { get; set; }
public DateTime timestamp { get; set; } public DateTime timestamp { get; set; }
public DateTime starttime { get; set; } public DateTime starttime { get; set; }
public DateTime? endtime { get; set; } public DateTime? endtime { get; set; }
public string dateType { get; set; } public string dateType { get; set; }
public string type { get; set; } public string type { get; set; }
public string building_tag { get; set; } public string building_tag { get; set; }
public string device_number { get; set; }
} }
public class History_Building public class History_Building

View File

@ -37,7 +37,7 @@ namespace FrontendWebApi.Models
{ {
public string timeStamp { get; set; } public string timeStamp { get; set; }
public string device_number { get; set; } public string device_number { get; set; }
public decimal avg_rawdata { get; set; } public string avg_rawdata { get; set; }
} }
public class HydroMeterPriceInput public class HydroMeterPriceInput

View File

@ -183,27 +183,39 @@ namespace Repository.BackendRepository.Implement
{ {
try try
{ {
#region import_niagara_item資料表中選取的棟別 string sql = @"
foreach(var b in building) DROP TABLE IF EXISTS `import_niagara_item`;
{ CREATE TABLE `import_niagara_item` (
string sql = @"CREATE TABLE IF NOT EXISTS `import_niagara_item` (
`id` int(11) NOT NULL AUTO_INCREMENT, `id` int(11) NOT NULL AUTO_INCREMENT,
`device_area_tag` varchar(50) DEFAULT NULL, `device_area_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_building_tag` varchar(50) DEFAULT NULL, `device_building_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_system_tag` varchar(50) DEFAULT NULL, `device_system_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_name_tag` varchar(50) DEFAULT NULL, `device_name_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`device_point_name` varchar(50) DEFAULT NULL, `device_floor_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`check_status` varchar(50) DEFAULT NULL, `device_master_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`parent_path` varchar(50) DEFAULT NULL, `device_last_name_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`full_name` varchar(50) DEFAULT NULL, `device_serial_tag` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
PRIMARY KEY (`id`) `device_point_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;"; `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;
";
await conn.ExecuteAsync(sql); await conn.ExecuteAsync(sql);
sql = "delete from import_niagara_item where device_building_tag = '" + b + "'";
await conn.ExecuteAsync(sql); #region import_niagara_item資料表中選取的棟別
} //foreach(var b in building)
//{
// sql = "delete from import_niagara_item where device_building_tag = '" + b + "'";
// await conn.ExecuteAsync(sql);
//}
#endregion #endregion
ds = ds.GroupBy(x => new { ds = ds.GroupBy(x => new
{
device_area_tag = x.device_area_tag, device_area_tag = x.device_area_tag,
device_building_tag = x.device_building_tag, device_building_tag = x.device_building_tag,
device_system_tag = x.device_system_tag, device_system_tag = x.device_system_tag,
@ -229,17 +241,22 @@ namespace Repository.BackendRepository.Implement
#region import_niagara_item資料表 #region import_niagara_item資料表
foreach (var row in ds) foreach (var row in ds)
{ {
sb.Append($@" insert import_niagara_item(device_area_tag, device_building_tag, device_system_tag, device_name_tag, device_point_name, parent_path, full_name, is_history) string ss = $@" insert import_niagara_item(device_area_tag, device_building_tag, device_system_tag, device_name_tag,
device_point_name, parent_path, full_name, is_history, created_at)
values('" + values('" +
row.device_area_tag + "', '" + row.device_area_tag + "', '" +
row.device_building_tag + "', '" + row.device_building_tag + "', '" +
row.device_system_tag + "', '" + row.device_system_tag + "', '" +
row.device_name_tag + "', '" + row.device_name_tag + "', '" +
//row.device_floor_tag + "', '" +
//row.device_master_tag + "', '" +
//row.device_last_name_tag + "', '" +
row.device_point_name + "', '" + row.device_point_name + "', '" +
row.parent_path + "', '" + row.parent_path + "', '" +
row.full_name + "'," + row.full_name + "'," +
row.isHistory + row.isHistory + ", now() " +
");"); ");";
sb.Append(ss);
} }
var isDome = await GetOneAsync<string>("select system_value from variable where deleted = 0 and system_type = 'project_name';"); var isDome = await GetOneAsync<string>("select system_value from variable where deleted = 0 and system_type = 'project_name';");
@ -270,6 +287,96 @@ 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();
}
}
}
}
/// <summary> /// <summary>
/// 比對 device /// 比對 device
/// </summary> /// </summary>

View File

@ -28,6 +28,14 @@ namespace Repository.BackendRepository.Interface
/// <param name="building"></param> /// <param name="building"></param>
/// <returns></returns> /// <returns></returns>
Task InsertItemFromNiagara(List<ImpNiaItem> ds, List<string> building); Task InsertItemFromNiagara(List<ImpNiaItem> ds, List<string> building);
/// <summary>
/// 同步N4至資料表 import_niagara_item_History
/// </summary>
/// <param name="ds"></param>
/// <param name="building"></param>
/// <returns></returns>
Task InsertItemFromNiagara_History(List<ImpNiaItem> ds, List<string> building);
/// <summary> /// <summary>
/// 比對 device /// 比對 device
/// </summary> /// </summary>

View File

@ -117,7 +117,12 @@ namespace Repository.Models
public string device_system_tag { get; set; } public string device_system_tag { get; set; }
public string device_name_tag { get; set; } public string device_name_tag { get; set; }
public string device_point_name { get; set; } public string device_point_name { get; set; }
public string device_floor_tag { get; set; } public string device_floor_tag { get; set; } //add by jiahao 2023-07-23
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 string parent_path { get; set; } public string parent_path { get; set; }
public string check_status { get; set; } public string check_status { get; set; }

View File

@ -18,8 +18,8 @@ namespace tpDomeWinAPP
Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
// Application.Run(new fmCheckTagName()); Application.Run(new fmCheckTagName());
Application.Run(new fmDecrypt()); //Application.Run(new fmDecrypt());
} }
} }
} }