[後端] 修改歷史資料匯出, 後台同步station更換

[前端] 增加loading界面, 修改送出niagara building_tag
This commit is contained in:
dev02 2023-06-29 11:21:36 +08:00
parent 8d03f7994e
commit 803d74d645
7 changed files with 481 additions and 153 deletions

View File

@ -88,4 +88,10 @@ namespace Backend.Models
public int Value { get; set; } //通常放id
public string Name { get; set; }
}
public class BuildStation
{
public string system_value { get; set; }
public string system_key { get; set; }
}
}

View File

@ -61,6 +61,7 @@ namespace BackendWorkerService.Quartz.Jobs
var variableArchive = await backgroundServiceRepository.GetAllAsync<KeyValue>(sqlArchive);
var electricMeterGuid = variableArchive.Where(x => x.Name == "ElectricMeterGuid").Select(x => x.Value).FirstOrDefault();
var waterMeterGuid = variableArchive.Where(x => x.Name == "WaterMeterGuid").Select(x => x.Value).FirstOrDefault();
var buildingStation = await backgroundServiceRepository.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)");
#region http variable
HttpWebRequest archiveRequest = null;
@ -127,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
@ -159,7 +159,7 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveDayRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
archiveRequest = (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/");
archiveRequest.Method = "POST";
@ -216,7 +216,7 @@ namespace BackendWorkerService.Quartz.Jobs
}
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
archiveRequest = (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/");
archiveRequest.Method = "POST";
@ -628,6 +628,7 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveWeekRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
archiveRequest = (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/");
archiveRequest.Method = "POST";
@ -685,6 +686,7 @@ namespace BackendWorkerService.Quartz.Jobs
}
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
archiveRequest = (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/");
archiveRequest.Method = "POST";
@ -993,6 +995,7 @@ namespace BackendWorkerService.Quartz.Jobs
List<Dictionary<string, object>> waterArchiveMonthRawDatas = new List<Dictionary<string, object>>();
foreach (var deviceNumberPoint in electricDeviceNumberPoints)
{
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
archiveRequest = (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/");
archiveRequest.Method = "POST";
@ -1049,6 +1052,7 @@ namespace BackendWorkerService.Quartz.Jobs
}
foreach (var deviceNumberPoint in waterDeviceNumberPoints)
{
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
archiveRequest = (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/");
archiveRequest.Method = "POST";

View File

@ -55,6 +55,7 @@ namespace BackendWorkerService.Services.Implement
var variableArchive = await backgroundServiceRepository.GetAllAsync<KeyValue>(sqlArchive);
repeatTimes = Convert.ToInt32(variableArchive.Where(x => x.Name == "RepeatTimes").Select(x => x.Value).FirstOrDefault());
var saveToMSDB = await backgroundServiceRepository.GetOneAsync<string>("select system_value from variable where system_type = 'save_to_ms_db' and deleted = 0");
var buildingStation = await backgroundServiceRepository.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)");
#region obix
var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
@ -63,7 +64,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 +280,7 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT1D' />
</obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
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 +355,85 @@ 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();
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);
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
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 +460,7 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT7D' />
</obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
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 +545,7 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT7D' />
</obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
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 +636,7 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT{dayInMonth}D' />
</obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
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 +724,7 @@ namespace BackendWorkerService.Services.Implement
<reltime name='interval' val = 'PT{dayInMonth}D' />
</obj>";
var station = buildingStation.Where(x => x.system_key == deviceNumberPoint.DeviceNumber.Split("_")[1]).Select(x => x.system_value).FirstOrDefault();
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

@ -19,10 +19,8 @@
<div class="row bg-dark p-2">
<div>
<div class="py-2 col-12" id="his_building">
<div
class="item btn-group btn-group-toggle"
data-toggle="buttons"
></div>
<div class="item btn-group btn-group-toggle"
data-toggle="buttons"></div>
</div>
</div>
</div>
@ -81,11 +79,14 @@
<script>
var historyTable = null;
var buildingTag = null;
pageAct.hisBuiName = "";
hisFirst = true;
$(function () {
console.log(1);
let html = "";
for (let building of pageAct.buildList) {
html += `<label class="btn btn-secondary">
<input type="radio" name="buildingRadio" id="radio_${building.building_tag}" value="${building.building_tag}" onChange="SelectBuild(this,'${building.building_tag}')"> ${building.full_name}
<input type="radio" name="buildingRadio" id="radio-${building.getway}" value="${building.building_tag}" onChange="SelectBuild(this,'${building.building_tag}')"> ${building.full_name}
</label>`;
}
$("#his_building").find(".item").empty();
@ -182,11 +183,10 @@
}
}
});
});
function initList() {
$(loadEle).Loading("start");
let sendData = {
building_tag: buildingTag
}
@ -203,7 +203,7 @@
<span class="nav-link-text">${val.full_name}</span>
</a>
<ul style="${index == 0 ? `display:block;` : ``}">`;
i1 = (val.history_Sub_systems != null && i1 == null) ? index : null;
}
@ -273,14 +273,15 @@
strHtml += `<button onClick="setValue(null, null, '${val.points}', this)" type="button" class="btn btn-info waves-effect waves-themed">${val.full_name || val.points}</button>`;
pageAct.deviceItem = val.points;
pageAct.devicePoiName = val.full_name + ' ' + val.points;
pageAct.deviceComName = val.parent_path;
getData();
} else {
strHtml += `<button onClick="setValue(null, null, '${val.points}', this)" type="button" class="btn btn-secondary waves-effect waves-themed">${val.full_name || val.points}</button>`;
}
});
$('#devPointsList').html(strHtml);
if (!hisFirst)
getData();
}
ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send();
}
@ -290,12 +291,12 @@
var edt = new Date(new Date().setDate(sdt.getDate() + 1));
start = start ?? sdt.toLocaleDateString();
end = end ?? edt.toLocaleDateString();
callBackFromHistory()
callBackFromHistory();
getHistoryDataByBaja(pageAct.deviceNumber + "_" + pageAct.deviceItem,
new Date(start).getTime(),
new Date(end).getTime(),
pageAct.deviceName,
pageAct.deviceComName,
pageAct.hisBuiName,
callBackFromHistory);
}
@ -304,14 +305,15 @@
loadTable(res.data);
if (historyTable != null) {
let t = $('#historyTable').dataTable();
t.fnClearTable();
if (res.data.length > 0)
t.fnAddData(res.data);
}
}
function setValue(deviceNumber, deviceName, deviceItem, elem) {
hisFirst = false;
btnSelCss(elem);
if ((deviceNumber != null && deviceNumber != undefined) && (deviceName != null && deviceName != undefined)) {
@ -408,9 +410,8 @@
}
function loadTable(data) {
$(loadEle).Loading("start");
if (data) {
$.each(data, function (i, v) {
v.type = pageAct.devicePoiName.split(" ")[0];
});
@ -453,27 +454,30 @@
historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi");
}
$(loadEle).Loading("close");
}
function exportExcel() {
$(loadEle).Loading("start");
let url = baseApiUrl + "/History/OpeExportExcel";
objSendData.Data = $('#historyTable').dataTable().fnGetData();
$.each(objSendData.Data, function (i, v) {
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.dateType = pageAct.dateType;
});
let v = {};
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.dateType = pageAct.dateType;
objSendData.Data = v;
ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
if (rel.code == "0000")
location.href = baseApiUrl + "/api/df?path=" + rel.data.split('/')[0] + "&fileName=" + rel.data.split('/')[1] + "&token=" + cookies.get("JWT-Authorization");
}, null, "POST").send();
$(loadEle).Loading("close");
}, () => {
$(loadEle).Loading("close");
}, "POST",true).send();
}
//選擇棟別
function SelectBuild(e, building_tag) {
$(loadEle).Loading("start");
checkIsSelectedBuilding();
}
@ -486,10 +490,10 @@
$("[name=buildingRadio]").parent().addClass("btn-secondary");
$("[name=buildingRadio]:checked").parent().removeClass("btn-secondary");
$("[name=buildingRadio]:checked").parent().addClass("btn-info");
buildingTag = buildingRadios.prop("id").split("_")[1]; //building tag
buildingTag = buildingRadios.val(); //building tag
pageAct.hisBuiName = buildingRadios.prop('id').split("-")[1];
initList();
result = true;
} else {
}
return result;
}

View File

@ -4,6 +4,8 @@ using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
@ -14,12 +16,8 @@ using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.StaticFiles;
using NPOI.HPSF;
using Google.Protobuf.WellKnownTypes;
using Decimal = System.Decimal;
namespace FrontendWebApi.ApiControllers
{
@ -47,7 +45,7 @@ namespace FrontendWebApi.ApiControllers
/// <param name="lhe"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult<ApiResult<string>>> OpeExportExcel([FromBody] List<HistoryExport> lhe)
public async Task<ActionResult<ApiResult<string>>> OpeExportExcel([FromBody] HistoryExport lhe)
{
ApiResult<string> apiResult = new ApiResult<string>();
@ -60,8 +58,118 @@ namespace FrontendWebApi.ApiControllers
try
{
var fileDateName = lhe.FirstOrDefault().dateType == "month" ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM") : lhe.FirstOrDefault().endtime == null ? lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") : lhe.FirstOrDefault().starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.FirstOrDefault().endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_"+fileDateName+".xlsx";
#region obix
EDFunction ed = new EDFunction();
var obixApiConfig = new ObixApiConfig();
var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
var variableObix = await backendRepository.GetAllAsync<KeyValue>(sqlObix);
obixApiConfig.ApiBase = variableObix.Where(x => x.Name == "ApiBase").Select(x => x.Value).FirstOrDefault();
obixApiConfig.UserName = ed.AESDecrypt(variableObix.Where(x => x.Name == "UserName").Select(x => x.Value).FirstOrDefault());
obixApiConfig.Password = ed.AESDecrypt(variableObix.Where(x => x.Name == "Password").Select(x => x.Value).FirstOrDefault());
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(obixApiConfig.UserName + ":" + obixApiConfig.Password));
#endregion obix
var building = await backendRepository.GetAllAsync<BuildList>("select * from building where deleted = 0");
var buildStation = await 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)");
#region get device and device_item(point)
var device = await 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))}')");
var devicePoint = await 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))}')");
#endregion
List<DeviceNumberPoint> listDevicePoint = new List<DeviceNumberPoint>();
#region combine device and point
foreach (var d in device)
{
var dp = devicePoint.Where(x => x.device_building_tag == d.device_building_tag).ToList();
foreach (var point in dp)
{
DeviceNumberPoint deviceNumberPoint = new DeviceNumberPoint();
deviceNumberPoint.DeviceNumber = d.device_number;
deviceNumberPoint.Point = point.points;
deviceNumberPoint.FullDeviceNumberPoint = string.Format("{0}_{1}", d.device_number, point.points);
listDevicePoint.Add(deviceNumberPoint);
}
}
#endregion
#region get data from niagara
lhe.endtime = lhe.dateType == "today" ? lhe.starttime : lhe.dateType == "month" ? lhe.starttime.AddMonths(1) : lhe.endtime;
var startTimestamp = string.Format("{0}T00:00:00.000+08:00", lhe.starttime.ToString("yyyy-MM-dd"));
var endTimestamp = string.Format("{0}T23:59:59.000+08:00", lhe.endtime?.ToString("yyyy-MM-dd"));
var historyQueryFilter = $@"<obj is='obix: HistoryFilter'>
<abstime name='start' val='{startTimestamp}' />
<abstime name='end' val='{endTimestamp}' />
<reltime name='interval' val='PT1M' />
</obj>";
List<HistoryExport> he = new List<HistoryExport>();
List<JsonDevice> jd = new List<JsonDevice>();
if (listDevicePoint.Count > 0)
{
foreach (var d in listDevicePoint)
{
string buildingTag = d.DeviceNumber.Split("_")[1];
var station = buildStation.Where(x => x.system_key == buildingTag).Select(x => x.system_value).FirstOrDefault();
var archiveRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/{station}/{d.FullDeviceNumberPoint}/~historyRollup/");
archiveRequest.Method = "POST";
archiveRequest.Headers.Add("Authorization", "Basic " + encoded);
archiveRequest.PreAuthenticate = true;
byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter);
using (Stream reqStream = archiveRequest.GetRequestStream())
{
reqStream.Write(byteArray, 0, byteArray.Length);
}
var archiveResponse = (HttpWebResponse)archiveRequest.GetResponse();
var archiveResponseContent = new StreamReader(archiveResponse.GetResponseStream()).ReadToEnd();
archiveResponse.Dispose();
archiveResponse.Close();
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(archiveResponseContent);
var archiveJson = JsonConvert.SerializeXmlNode(xmlDocument);
var archiveJsonResult = (JObject)JsonConvert.DeserializeObject(archiveJson);
if (!archiveJsonResult.ContainsKey("err"))
{
var jsonDevice = new JsonDevice();
jsonDevice.deviceNumberPoint = d;
jsonDevice.json = archiveJsonResult;
jsonDevice.building_tag = buildingTag;
jd.Add(jsonDevice);
}
}
}
if (jd != null && jd.Count > 0)
{
foreach (var d in jd)
{
var ArrangeRawDatas = ArrangeRawData(d.deviceNumberPoint, d.json);
if (ArrangeRawDatas != null && ArrangeRawDatas.Count > 0)
{
foreach (var ard in ArrangeRawDatas)
{
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.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.timestamp = Convert.ToDateTime(ard["@end_timestamp"].ToString());
hed.building_tag = d.building_tag;
he.Add(hed);
}
}
}
}
#endregion
#region export file progress
var fileDateName = lhe.dateType == "today" ? lhe.starttime.ToString("yyyy-MM-dd")
: lhe.dateType == "month" ? lhe.starttime.ToString("yyyy-MM")
: lhe.starttime.ToString("yyyy-MM-dd") + "_" + ((DateTime)lhe.endtime).ToString("yyyy-MM-dd");
var fileName = "歷史資料_" + fileDateName + ".xlsx";
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
if (!System.IO.Directory.Exists(filePath))
@ -112,61 +220,65 @@ namespace FrontendWebApi.ApiControllers
stylein12.WrapText = true;
#endregion
ISheet sheet = workbook.CreateSheet("歷史資料");
int RowPosition = 0;
#region set cell
IRow 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);
ICell 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
if (lhe.Count > 0)
foreach (var b in building)
{
foreach (var he in lhe)
{
RowPosition += 1;
row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++)
{
cell = row.CreateCell(i);
if (i == 0)
{
cell.SetCellValue(he.type);
}
if (i == 1)
{
cell.SetCellValue(he.deviceName);
}
if (i == 2)
{
cell.SetCellValue(he.value);
}
if (i == 3)
{
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
var data = he.Where(x => x.building_tag == b.building_tag).ToList();
ISheet sheet = workbook.CreateSheet($"{b.full_name}歷史資料");
int RowPosition = 0;
#region set cell
IRow 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);
ICell 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
cell.CellStyle = style12;
if (data.Count > 0)
{
foreach (var d in data)
{
RowPosition += 1;
row = sheet.CreateRow(RowPosition);
for (var i = 0; i < 4; i++)
{
cell = row.CreateCell(i);
if (i == 0)
{
cell.SetCellValue(d.type);
}
if (i == 1)
{
cell.SetCellValue(d.deviceName);
}
if (i == 2)
{
cell.SetCellValue(d.value);
}
if (i == 3)
{
cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
}
}
}
}
workbook.Write(fs);
}
#endregion
apiResult.Code = "0000";
apiResult.Data = "history/" + fileName;
}
@ -1204,5 +1316,160 @@ namespace FrontendWebApi.ApiControllers
}
return Ok(apiResult);
}
private List<Dictionary<string, object>> ArrangeRawData(DeviceNumberPoint deviceNumberPoint, JObject jsonResult)
{
List<Dictionary<string, object>> arrangeRawDatas = new List<Dictionary<string, object>>();
var histories = jsonResult["obj"]["list"]["obj"];
var rawdateCount = Convert.ToInt32(jsonResult["obj"]["int"]["@val"].ToString());
if (rawdateCount == 0)
{
return null;
}
if (histories != null && histories.HasValues)
{
if (rawdateCount > 1)
{ //多筆資料
foreach (var history in histories)
{
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (history["abstime"] != null && history["abstime"].HasValues)
{
foreach (var abstime in history["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (history["int"] != null && history["int"].HasValues)
{
var count = Convert.ToInt32(history["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (history["real"] != null && history["real"].HasValues)
{
foreach (var real in history["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
else
{ //單筆資料
Dictionary<string, object> arrangeRawData = new Dictionary<string, object>();
arrangeRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
arrangeRawData.Add("@point", deviceNumberPoint.Point);
//時間
if (histories["obj"]["abstime"] != null && histories["obj"]["abstime"].HasValues)
{
foreach (var abstime in histories["obj"]["abstime"])
{
var name = abstime["@name"].ToString();
switch (name)
{
case "start":
var startTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@start_timestamp", startTimstamp);
break;
case "end":
var endTimstamp = Convert.ToDateTime(abstime["@val"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
arrangeRawData.Add("@end_timestamp", endTimstamp);
break;
}
}
}
//區間內資料筆數
if (histories["obj"]["int"] != null && histories["obj"]["int"].HasValues)
{
var count = Convert.ToInt32(histories["obj"]["int"]["@val"].ToString());
arrangeRawData.Add("@count_rawdata", count);
}
//整合數值(最大、最小、平均、總和)
if (histories["obj"]["real"] != null && histories["obj"]["real"].HasValues)
{
foreach (var real in histories["obj"]["real"])
{
var name = real["@name"].ToString();
switch (name)
{
case "min":
var min = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@min_rawdata", min);
break;
case "max":
var max = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@max_rawdata", max);
break;
case "avg":
var avg = Convert.ToDecimal(real["@val"].ToString());
arrangeRawData.Add("@avg_rawdata", avg);
break;
case "sum":
var sum = Decimal.Parse(real["@val"].ToString(), System.Globalization.NumberStyles.Float);
arrangeRawData.Add("@sum_rawdata", sum);
break;
}
}
}
arrangeRawData.Add("@is_complete", 1);
arrangeRawData.Add("@repeat_times", 0);
arrangeRawData.Add("@fail_reason", null);
arrangeRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
arrangeRawDatas.Add(arrangeRawData);
}
}
return arrangeRawDatas;
}
}
}

View File

@ -1,4 +1,5 @@
using System;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
@ -297,6 +298,7 @@ namespace FrontendWebApi.Models
public DateTime? endtime { get; set; }
public string dateType { get; set; }
public string type { get; set; }
public string building_tag { get; set; }
}
public class History_Building
@ -305,4 +307,43 @@ namespace FrontendWebApi.Models
public string building_name { get; set; }
public List<History_Main_system> history_Main_Systems { get; set; }
}
public class DeviceNumberPoint
{
public string DeviceNumber { get; set; }
public string Point { get; set; }
public string FullDeviceNumberPoint { get; set; }
}
public class BuildStation
{
public string system_value { get; set; }
public string system_key { get; set; }
}
public class Device_item : Actor
{
public int id { get; set; }
public string device_item_guid { get; set; }
public string device_area_tag { get; set; }
public string device_building_tag { get; set; }
public string device_system_tag { get; set; }
public string device_name_tag { get; set; }
public string full_name { get; set; }
public string points { get; set; }
public string unit { get; set; }
public byte is_show { get; set; }
public byte is_show_riserDiagram { get; set; }
public byte is_controll { get; set; }
public byte is_bool { get; set; }
public byte is_link { get; set; }
public int is_show_history { get; set; }
}
public class JsonDevice
{
public DeviceNumberPoint deviceNumberPoint { get; set; }
public JObject json { get; set; }
public string building_tag { get; set; }
}
}