This commit is contained in:
dev01 2023-07-06 15:33:34 +08:00
commit d2f6005fcc
18 changed files with 726 additions and 275 deletions

View File

@ -468,7 +468,7 @@ namespace Backend.Controllers
if (!string.IsNullOrEmpty(buildFloor.InitMapName))
{
buildFloor.MapUrl = "/upload/floor_map/" + buildFloor.Floor_guid + ".svg";
buildFloor.MapUrl = baseURL + "upload/floor_map/" + buildFloor.Floor_map_name + ".svg";
}
apiResult.Code = "0000";

View File

@ -531,24 +531,33 @@ namespace Backend.Controllers
if (device_Item.id == 0)
{
var building = await backendRepository.GetAllAsync<string>("select building_tag from building where deleted = 0;");
var parentPath = await backendRepository.GetOneAsync<string>("select system_value from variable where deleted = 0 and system_type = 'obixStatus'");
List<Dictionary<string, object>> device_iteDic = new List<Dictionary<string, object>>();
//新增
Dictionary<string, object> Device_itemDic = new Dictionary<string, object>()
foreach (var b in building)
{
{ "@device_system_tag", main_tag},
{ "@device_name_tag", sub_tag},
{ "@full_name", device_Item.full_name},
{ "@points", device_Item.points},
{ "@unit", device_Item.unit},
{ "@is_show", device_Item.is_show},
{ "@is_show_riserDiagram", device_Item.is_show_riserDiagram},
{ "@is_controll", device_Item.is_controll},
{ "@is_bool", device_Item.is_bool},
{ "@is_show_history", device_Item.is_show_history},
{ "@created_by", myUserInfo.Userinfo_guid},
};
await backendRepository.AddOneByCustomTable(Device_itemDic, "device_item");
Dictionary<string, object> Device_itemDic = new Dictionary<string, object>()
{
{ "@device_system_tag", main_tag},
{ "@device_name_tag", sub_tag},
{ "@full_name", device_Item.full_name},
{ "@points", device_Item.points},
{ "@unit", device_Item.unit},
{ "@device_building_tag", b},
{ "@parent_path", parentPath},
{ "@is_link", 1},
{ "@is_show", device_Item.is_show},
{ "@is_show_riserDiagram", device_Item.is_show_riserDiagram},
{ "@is_controll", device_Item.is_controll},
{ "@is_bool", device_Item.is_bool},
{ "@is_show_history", device_Item.is_show_history},
{ "@created_by", myUserInfo.Userinfo_guid},
};
device_iteDic.Add(Device_itemDic);
}
await backendRepository.AddMutiByCustomTable(device_iteDic, "device_item");
apiResult.Code = "0000";
apiResult.Msg = "新增成功";
}

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

@ -108,6 +108,9 @@
//樓層設定上方選單
$("#BuildList").empty();
$.each(data, function (key, value) {
if (value.building_tag.includes("$3"))
value.building_tag = value.building_tag.replace("$3", "");
$("#BuildList").append(`<button type="button" class="btn btn-outline-success waves-effect waves-themed ml-2 mb-2 btn-station" id="${value.building_tag}" onclick="clickBuilding('${value.building_tag}')">${value.full_name}</button>`);
@*if (key == 0) {
selected_build_guid_top_name = value.full_name;
@ -454,7 +457,7 @@
var file = input3Dfile;
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', "zo4zguyalhjrl5o81va39pkdgr82wamq-202305_bim");//forge上傳平台-資料夾
formData.append('bucketKey', "zo4zguyalhjrl5o81va39pkdgr82wamq-202305_bim");//forge上傳平台-資料夾
$.ajax({
url: '/api/forge/oss/objects',
@ -530,7 +533,10 @@
var url = "/BuildInfo/EditBuildInfo";
var formData = new FormData();
formData.append("building_tag", selected_build_guid);
if ($.isNumeric(selected_build_guid[0]))
formData.append("building_tag", "$3" + selected_build_guid);
else
formData.append("building_tag", selected_build_guid);
formData.append("Full_name", $('#build_name_modal').val());
formData.append("Ip_address", $('#ip_address_modal').val());
formData.append("Ip_port", $('#ip_port_modal').val());
@ -682,7 +688,10 @@
"url": "/BuildInfo/BuildFloorList",
"type": "POST",
"data": function (d) {
d.build_tag = selected_build_guid_top;
if ($.isNumeric(selected_build_guid_top[0]))
d.build_tag = selected_build_guid_top = "$3" + selected_build_guid_top;
else
d.build_tag = selected_build_guid_top;
},
"dataSrc": function (rel) {
if (rel.code == "9999") {
@ -762,11 +771,14 @@
return;
}
else {
$('#floor-modal').modal();
$("#BuildName").html(selected_build_guid_top_name);
$("#floor_name_modal").val(rel.data.full_name);
@*$("#map_file_preview_modal").attr("data-original", rel.data.mapUrl);*@
$('#floor-modal').modal();
if (rel.data.mapUrl)
loadURLToInputFiled(rel.data.mapUrl, rel.data.initMapName + ".svg");
else
$('#floor_map_file_modal')[0].value = "";
}
}, 'json');
});
@ -962,7 +974,7 @@
function translateObject(urn) {
$("#forgeViewer").empty();
//if (node == null) node = $('#appBuckets').jstree(true).get_selected(true)[0];
var bucketKey = "zo4zguyalhjrl5o81va39pkdgr82wamq-202305_bim";//forge上傳平台-資料夾
var bucketKey = "zo4zguyalhjrl5o81va39pkdgr82wamq-202305_bim";//forge上傳平台-資料夾
var objectKey = urn;
jQuery.post({
@ -977,6 +989,26 @@
}
//#endregion
function loadURLToInputFiled(url, filesName){
getImgURL(url, (imgBlob)=>{
// Load img blob to input
// WIP: UTF8 character error
let fileName = filesName
let file = new File([imgBlob], fileName,{type:"image/svg+xml", lastModified:new Date().getTime()}, 'utf-8');
let container = new DataTransfer();
container.items.add(file);
$('#floor_map_file_modal')[0].files = container.files;
})
}
// xmlHTTP return blob respond
function getImgURL(url, callback){
var xhr = new XMLHttpRequest();
xhr.onload = function() {
callback(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
</script>
}

View File

@ -111,8 +111,17 @@
}
var data = rel.data;
ds = data;
console.log(ds)
ds = $.extend(true, [], data);
$.each(data, function (i, v)
{
if (v.value.includes("$3"))
{
v.value = v.value.replace("$3", "");
v.tag_name = v.tag_name.replace("$3", "");
v.point_name = v.point_name.replace("$3", "");
}
})
//console.log(ds)
if (data == null || data.length == 0) {
this.data = [];
document.getElementById('loadDataText').innerText = "";

View File

@ -594,13 +594,13 @@
//#endregion
//#region 新增設備項目
function Adddevice_item() {
//SubDeviceItemValidate.resetForm();
selected_system_device_item_guid = "";
$("#device-sub-modal .modal-title").html("設備項目 - 新增");
$("#device-item-sub-form").trigger("reset");
$("#device-sub-modal").modal();
}
//function Adddevice_item() {
// //SubDeviceItemValidate.resetForm();
// selected_system_device_item_guid = "";
// $("#device-sub-modal .modal-title").html("設備項目 - 新增");
// $("#device-item-sub-form").trigger("reset");
// $("#device-sub-modal").modal();
//}
//#endregion
$('#system_sub_table').on("click", "tbody>tr", function () {

View File

@ -32,11 +32,11 @@
<div class="card border mb-g w-100 mb-5" id="submenucard">
<div class="card-header bg-fusion-25 py-2 pr-3 d-flex align-items-center flex-wrap justify-content-end">
@*<div class="card-header bg-fusion-25 py-2 pr-3 d-flex align-items-center flex-wrap justify-content-end">
<div class="text-right ">
<a href="javascript:;" class="btn btn-success waves-effect waves-themed" id="adddevice_item-btn" onclick="Adddevice_item()"><span class="fal fa-plus mr-1"></span>新增</a>
</div>
</div>
</div>*@
<div class="card-body">
<div class="w-100">
<div class="col-12">

View File

@ -142,12 +142,12 @@ namespace BackendWorkerService
);
#endregion
#region API
services.AddSingleton<Quartz.Jobs.WeatherAPIJob>();
services.AddSingleton(
new JobSchedule(jobType: typeof(Quartz.Jobs.WeatherAPIJob), cronExpression: configuration.GetValue<string>("BackgroundServiceCron:WeatherAPIJob"))
);
#endregion
//#region 定時取得氣象API
//services.AddSingleton<Quartz.Jobs.WeatherAPIJob>();
//services.AddSingleton(
//new JobSchedule(jobType: typeof(Quartz.Jobs.WeatherAPIJob), cronExpression: configuration.GetValue<string>("BackgroundServiceCron:WeatherAPIJob"))
//);
//#endregion
}).ConfigureLogging((hostContext, logFactory) => {
IConfiguration configuration = hostContext.Configuration;

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

@ -875,7 +875,7 @@
}
function setAuthPage() {
$(`#accAuthPageTable input[type=checkbox]`).prop('disabled', false);
$(`#accAuthPageTable input[type=checkbox]`).removeClass();
$.each($(`#accAuthPageTable input[type=checkbox]:checked`), function (i, v) {
$(v).click();
});
@ -886,7 +886,7 @@
$.each(pageAct.authCode, function (i, v) {
$(`#accAuthPageTable input[id=${v}]`).click();
$(`#accAuthPageTable input[id=${v}]`).attr('disabled', true);
$(`#accAuthPageTable input[id=${v}]`).addClass("disabledBox");
});
}

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,29 +273,44 @@
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) {
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
}
ytAjax = new YourTeam.Ajax(url, objSendData, success, null, "POST").send();
}
function getData(start = null, end = null) {
$(loadEle).Loading("start");
var sdt = new Date();
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 +319,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)) {
@ -322,7 +338,20 @@
else if (deviceItem != null && deviceItem != undefined) {
pageAct.devicePoiName = $(elem).text();
pageAct.deviceItem = deviceItem;
getData();
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
getData(formatDate(start, "date", true), formatDate(end, "date", true));
}
}
@ -383,11 +412,11 @@
let start = new Date($('#his_startdate').val());
let end = new Date(new Date().setDate(new Date($('#his_enddate input').val()).getDate() + 1));
if (pageAct.dateType == "day")
end = new Date(new Date().setDate(start.getDate() + 1));
if (pageAct.dateType == "today" || pageAct.dateType == "day" || pageAct.dateType == "ytd")
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 1));
else if (pageAct.dateType == "month") {
start = new Date($('#getmonth').val());
end = new Date(new Date().setDate(start.getDate() + 30));
end = new Date(new Date(start.valueOf()).setDate(start.getDate() + 30));
}
else if (pageAct.dateType != "range")
return;
@ -408,89 +437,118 @@
}
function loadTable(data) {
$(loadEle).Loading("start");
if (data) {
$.each(data, function (i, v) {
v.type = pageAct.devicePoiName.split(" ")[0];
});
let tag = "#historyTable";
let tag = "#historyTable";
let column_defs = [
{ "targets": [0], "width": "20%", "sortable": true },
{ "targets": [1], "width": "20%", "sortable": true },
{ "targets": [2], "width": "20%", "sortable": true }
];
let column_defs = [
{ "targets": [0], "width": "20%", "sortable": true },
{ "targets": [1], "width": "20%", "sortable": true },
{ "targets": [2], "width": "20%", "sortable": true }
];
let columns = [
{
"title": "類別",
"data": "type"
},
{
"title": "設備名稱",
"data": "deviceName",
},
{
"title": "數值",
"data": "value",
"render": function (data) {
if (isNaN(data.toString())) {
return data
}
return data.roundDecimal(2);
}
},
{
"title": "紀錄時間",
"data": "timestamp",
"render": function (data) {
return displayDate(data, "datetime");
}
}
];
let columns = [
{
"title": "類別",
"data": "type"
},
{
"title": "設備名稱",
"data": "deviceName",
},
{
"title": "數值",
"data": "value",
"render": function (data) {
if (isNaN(data.toString())) {
return data
}
return data.roundDecimal(2);
}
},
{
"title": "紀錄時間",
"data": "timestamp",
"render": function (data) {
return displayDate(data, "datetime");
}
}
];
historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi");
historyTable = new YourTeam.JqDataTables.getTableByStatic(tag, data, columns, column_defs, null, null, null, null, "tpi");
}
$(loadEle).Loading("close");
}
function exportExcel() {
let url = baseApiUrl + "/History/OpeExportExcel";
objSendData.Data = $('#historyTable').dataTable().fnGetData();
$(loadEle).Loading("start");
let token = cookies.get("JWT-Authorization");
let url = baseApiUrl + "/api/ExportHistory";
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;
$.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;
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(objSendData.Data),
aysnc: true,
headers: {
Authorization: "Bearer " + token,
},
contentType: "application/json; charset=utf-8",
xhrFields: {
responseType: "blob", // to avoid binary data being mangled on charset conversion
},
success: function (rel, text, xhr) {
if (rel) {
downloadByBlob(xhr, rel);
}
$(loadEle).Loading("close");
},
error: function () {
$(loadEle).Loading("close");
},
complete: (xhr) => {
setLoading(false);
},
});
// ytAjax = new YourTeam.Ajax(url, objSendData, function (rel) {
// $(loadEle).Loading("close");
// }, function (rel) {
// if (rel) {
// downloadByBlob(xhr, rel);
// }
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");
// }, "POST",true).send();
}
//選擇棟別
function SelectBuild(e, building_tag) {
checkIsSelectedBuilding();
}
function checkIsSelectedBuilding() {
let result = false;
let buildingRadios = $("[name=buildingRadio]:checked");
buildingTag = null;
if (buildingRadios && buildingRadios.length > 0) {
$("[name=buildingRadio]").parent().removeClass("btn-info");
$("[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
initList();
result = true;
} else {
function SelectBuild(e, building_tag) {
$(loadEle).Loading("start");
checkIsSelectedBuilding();
}
function checkIsSelectedBuilding() {
let result = false;
let buildingRadios = $("[name=buildingRadio]:checked");
buildingTag = null;
if (buildingRadios && buildingRadios.length > 0) {
$("[name=buildingRadio]").parent().removeClass("btn-info");
$("[name=buildingRadio]").parent().addClass("btn-secondary");
$("[name=buildingRadio]:checked").parent().removeClass("btn-secondary");
$("[name=buildingRadio]:checked").parent().addClass("btn-info");
buildingTag = buildingRadios.val(); //building tag
pageAct.hisBuiName = buildingRadios.prop('id').split("-")[1];
initList();
result = true;
}
return result;
}
return result;
}
</script>

View File

@ -45,6 +45,8 @@ input.toggle:checked { background: #97c193; }
.lds-ring div:nth-child(3) { animation-delay: -0.15s; }
input.disabledBox { pointer-events: none; }
/* js-tree */
.jstree-node { padding-bottom: 3px; }
.jstree-default-dark { background-color: transparent; }

View File

@ -1,9 +1,13 @@
using FrontendWebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Interface;
using Repository.FrontendRepository.Interface;
using System;
@ -14,12 +18,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,72 +47,184 @@ namespace FrontendWebApi.ApiControllers
/// <param name="lhe"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult<ApiResult<string>>> OpeExportExcel([FromBody] List<HistoryExport> lhe)
[Route("api/ExportHistory")]
public FileResult OpeExportExcel([FromBody] HistoryExport lhe)
{
ApiResult<string> apiResult = new ApiResult<string>();
if (lhe == null)
{
apiResult.Code = "0001";
apiResult.Msg = "沒有資料匯入";
return apiResult;
}
//if (lhe == null)
//{
// apiResult.Code = "0001";
// apiResult.Msg = "沒有資料匯入";
// return apiResult;
//}
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";
XSSFWorkbook workbook = new XSSFWorkbook();
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";
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "excel", "history");
#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 = backendRepository.GetAllAsync<KeyValue>(sqlObix).Result;
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 = backendRepository.GetAllAsync<BuildList>("select * from building where deleted = 0").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;
if (!System.IO.Directory.Exists(filePath))
System.IO.Directory.CreateDirectory(filePath);
#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 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;
#endregion
List<DeviceNumberPoint> listDevicePoint = new List<DeviceNumberPoint>();
using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write))
#region combine device and point
foreach (var d in device)
{
IWorkbook workbook = new XSSFWorkbook();
#region excel設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
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);
ISheet sheet = workbook.CreateSheet("歷史資料");
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["@start_timestamp"].ToString());
hed.building_tag = d.building_tag;
he.Add(hed);
}
}
}
}
#endregion
#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設定
IFont font12 = workbook.CreateFont();
font12.FontName = "新細明體";
font12.FontHeightInPoints = 12;
ICellStyle style12 = workbook.CreateCellStyle();
style12.SetFont(font12);
style12.Alignment = HorizontalAlignment.Center;
style12.VerticalAlignment = VerticalAlignment.Center;
IFont font12Times = workbook.CreateFont();
font12Times.FontName = "Times New Roman";
font12Times.FontHeightInPoints = 12;
IFont font18 = workbook.CreateFont();
font18.FontName = "新細明體";
font18.FontHeightInPoints = 18;
font18.IsBold = true;
ICellStyle styleTitle18 = workbook.CreateCellStyle();
styleTitle18.SetFont(font18);
styleTitle18.Alignment = HorizontalAlignment.Center;
styleTitle18.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLeft12 = workbook.CreateCellStyle();
styleLeft12.SetFont(font12);
styleLeft12.Alignment = HorizontalAlignment.Left;
styleLeft12.VerticalAlignment = VerticalAlignment.Center;
ICellStyle styleLine12 = workbook.CreateCellStyle();
styleLine12.SetFont(font12);
styleLine12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
styleLine12.VerticalAlignment = VerticalAlignment.Center;
styleLine12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
styleLine12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
ICellStyle stylein12 = workbook.CreateCellStyle();
stylein12.SetFont(font12Times);
stylein12.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
stylein12.VerticalAlignment = VerticalAlignment.Center;
stylein12.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
stylein12.WrapText = true;
#endregion
foreach (var b in building)
{
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);
@ -133,9 +245,9 @@ namespace FrontendWebApi.ApiControllers
cell.CellStyle = styleLine12;
#endregion
if (lhe.Count > 0)
if (data.Count > 0)
{
foreach (var he in lhe)
foreach (var d in data)
{
RowPosition += 1;
row = sheet.CreateRow(RowPosition);
@ -144,40 +256,57 @@ namespace FrontendWebApi.ApiControllers
cell = row.CreateCell(i);
if (i == 0)
{
cell.SetCellValue(he.type);
cell.SetCellValue(d.type);
}
if (i == 1)
{
cell.SetCellValue(he.deviceName);
cell.SetCellValue(d.deviceName);
}
if (i == 2)
{
cell.SetCellValue(he.value);
cell.SetCellValue(d.value);
}
if (i == 3)
{
cell.SetCellValue(he.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
cell.SetCellValue(d.timestamp.ToString("yyyy-MM-dd HH:mm") + ":00");//
}
cell.CellStyle = style12;
}
}
}
workbook.Write(fs);
}
apiResult.Code = "0000";
apiResult.Data = "history/" + fileName;
//using (var fs = new FileStream(Path.Combine(filePath, fileName), FileMode.Create, FileAccess.Write))
//{
//workbook.Write(fs);
//}
#endregion
//apiResult.Code = "0000";
//apiResult.Data = "history/" + fileName;
}
catch (Exception exception)
{
apiResult.Code = "9999";
apiResult.Msg = "系統內部錯誤,請聯絡管理者。 Msg: " + exception.Message;
Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message);
return Ok(apiResult);
throw exception;
}
return Ok(apiResult);
var ms = new NpoiMemoryStream
{
AllowClose = false
};
workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
return File(ms, "application/vnd.ms-excel", fileName);
}
/// <summary>
@ -1204,5 +1333,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

@ -462,11 +462,11 @@ namespace FrontendWebApi.ApiControllers
#endregion
foreach (var r in result)
{
string buildingName = r.Select(x => x.building_name).FirstOrDefault();
var sheet = workbook.CreateSheet($"{buildingName}電表報表");
int RowPosition = 0;
if (result.Count > 0)
if (r.Count > 0)
{
string buildingName = r.Select(x => x.building_name).FirstOrDefault();
var sheet = workbook.CreateSheet($"{buildingName}電表報表");
int RowPosition = 0;
#region set cell
IRow row = sheet.CreateRow(RowPosition);
sheet.SetColumnWidth(0, 4 * 160 * 12);

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; }
}
}