[後端] 修改niagara 同步 設備防災錯誤, 修改水電表判斷表格錯誤

This commit is contained in:
dev02 2023-06-09 15:33:33 +08:00
parent 985aaed080
commit 8ce6316200
8 changed files with 224 additions and 94 deletions

View File

@ -113,13 +113,13 @@ namespace Backend.Controllers
building = data.GroupBy(x => x.tag_name.Split("_")[1]).Select(x => x.Key).ToList();
}
string LightSwitchLevel = await niagaraDataSynchronizeRepository.getLightSwitchLevel(); //獲取照明開關 是否在 device or device_node
await niagaraDataSynchronizeRepository.InsertNiagaraTagList(ds, building, tag_quantity); // 匯入 MySQL table: import_niagara_tag
await niagaraDataSynchronizeRepository.DeviceComparison(LightSwitchLevel);
await niagaraDataSynchronizeRepository.CheckDiffFullNameAndCover();
await niagaraDataSynchronizeRepository.CheckFullNameEmptyReplaceByDeviceName();
await niagaraDataSynchronizeRepository.InsertBuildingMenu();
await niagaraDataSynchronizeRepository.InsertSubSystemFloor();
//string LightSwitchLevel = await niagaraDataSynchronizeRepository.getLightSwitchLevel(); //獲取照明開關 是否在 device or device_node
//await niagaraDataSynchronizeRepository.InsertNiagaraTagList(ds, building, tag_quantity); // 匯入 MySQL table: import_niagara_tag
//await niagaraDataSynchronizeRepository.DeviceComparison(LightSwitchLevel);
//await niagaraDataSynchronizeRepository.CheckDiffFullNameAndCover();
//await niagaraDataSynchronizeRepository.CheckFullNameEmptyReplaceByDeviceName();
//await niagaraDataSynchronizeRepository.InsertBuildingMenu();
//await niagaraDataSynchronizeRepository.InsertSubSystemFloor();
await this.DeviceDisasterAsync();
result = true;

View File

@ -331,62 +331,113 @@ namespace Backend.Services.Implement
public List<Device_value_disaster> obixDevDisaster(string urlString, string bql, string tag_quantity, string acc, string pass, string dt)
{
List<Device_value_disaster> result = new List<Device_value_disaster>();
//String username = "obixUser";
//String password = "Admin123456";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(acc + ":" + pass));
String API_Url = urlString;
HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url);
Postrequest.Method = "POST";
Postrequest.Headers.Add("Authorization", "Basic " + encoded);
Postrequest.PreAuthenticate = true;
using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream()))
try
{
string json = "<str val='" + bql + "'/>";
//String username = "obixUser";
//String password = "Admin123456";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(acc + ":" + pass));
String API_Url = urlString;
streamWriter.Write(json);
}
HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url);
Postrequest.Method = "POST";
Postrequest.Headers.Add("Authorization", "Basic " + encoded);
Postrequest.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseString);
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc);
var data = Welcome.FromJson(jsonText);
if (data.Obj.Str != null)
{
foreach (var item in data.Obj.Str)
{
Device_value_disaster row = new Device_value_disaster();
row.value = item.Val;
string[] s1 = item.Val.Split(',');
string[] s2 = s1[0].Split('/');
row.tag_name = "";
row.disasterValue = dt;
for (int i = 0; i < s2.Length; i++)
using (var streamWriter = new StreamWriter(Postrequest.GetRequestStream()))
{
if (i == s2.Length - 2)
string json = "<str val='" + bql + "'/>";
streamWriter.Write(json);
}
HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseString);
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc);
bool welcome = false;
try
{
Welcome.FromJson(jsonText);
welcome = true;
}
catch
{
}
if (welcome)
{
var data = Welcome.FromJson(jsonText);
if (data.Obj.Str != null)
{
row.point_name = s2[i];
}
else if (i == 1)
{
row.tag_name += s2[i];
}
else if (i > 1 && i < s2.Length - 2)
{
row.tag_name += "_" + s2[i].Replace("$3", "");
foreach (var item in data.Obj.Str)
{
Device_value_disaster row = new Device_value_disaster();
row.value = item.Val;
string[] s1 = item.Val.Split(',');
string[] s2 = s1[0].Split('/');
row.tag_name = "";
row.disasterValue = dt;
for (int i = 0; i < s2.Length; i++)
{
if (i == s2.Length - 2)
{
row.point_name = s2[i];
}
else if (i == 1)
{
row.tag_name += s2[i];
}
else if (i > 1 && i < s2.Length - 2)
{
row.tag_name += "_" + s2[i].Replace("$3", "");
}
}
result.Add(row);
}
}
}
result.Add(row);
}
}
else
{
var data = WelcomeSingle.FromJson(jsonText);
if (data.Obj.Str != null)
{
var item = data.Obj.Str;
Device_value_disaster row = new Device_value_disaster();
row.value = item.Val;
string[] s1 = item.Val.Split(',');
string[] s2 = s1[0].Split('/');
row.tag_name = "";
row.disasterValue = dt;
for (int i = 0; i < s2.Length; i++)
{
if (i == s2.Length - 2)
{
row.point_name = s2[i];
}
else if (i == 1)
{
row.tag_name += s2[i];
}
else if (i > 1 && i < s2.Length - 2)
{
row.tag_name += "_" + s2[i].Replace("$3", "");
}
}
result.Add(row);
}
}
}
catch(Exception e)
{
var a = e;
}
return result;
}

View File

@ -18,10 +18,10 @@
"Port": "js2LutKe+rdjzdxMPQUrvQ==",
//"Database": "VJB2XC+lAtzuHObDGMVOAA==", //30
//"Database": "IgYBsgG2VLKKxFb64j7LOA==", //wsp
//"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
"Database": "7gWfmZ28HGIJZbxEbK+0yg==", //tpe_dome_dome
//"Database": "siTUcDaC/g2yGTMFWD72Kg==", //tpe_dome_hotel
//"Database": "iuaY0h0+TWkir44/eZLDqw==", //tpe_dome_office
"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut
//"Database": "Rq7Gn4x6LwBvVtl7GY8LbA==", //mcut
"Root": "SzdxEgaJJ7tcTCrUl2zKsA==",
"Password": "FVAPxztxpY4gJJKQ/se4bQ=="
},

View File

@ -1,6 +1,7 @@
using FrontendWebApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MySqlX.XDevAPI;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Repository.BackendRepository.Interface;
@ -100,6 +101,15 @@ namespace FrontendWebApi.ApiControllers
sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp ";
var table = input.tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + input.tableType + (input.tableType == "day" ? "_" + dbDateName : "");
var schema = await backendRepository.GetOneAsync<string>($"select system_value from variable where system_type = 'project_name'");
var isTable = await backendRepository.GetOneAsync<string>($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'");
if (string.IsNullOrEmpty(isTable)) //check for has table or not
{
apiResult.Code = "0000";
apiResult.Data = new List<HydroMeterOutput>() { };
return Ok(apiResult);
}
var dateFormat = input.tableType == "day" || input.tableType == "week" ? "%Y-%m-%d" : input.tableType == "month" ? "%Y-%m" : input.tableType == "year" ? "%Y" : null;
var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})";
var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
@ -262,7 +272,18 @@ namespace FrontendWebApi.ApiControllers
sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp ";
var table = input.tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + input.tableType + (input.tableType == "day" ? "_" + dbDateName : "");
var schema = await backendRepository.GetOneAsync<string>($"select system_value from variable where system_type = 'project_name'");
var isTable = await backendRepository.GetOneAsync<string>($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'");
if (string.IsNullOrEmpty(isTable)) //check for has table or not
{
apiResult.Code = "0000";
apiResult.Data = new List<HydroMeterOutput>() { };
return Ok(apiResult);
}
var dateFormat = input.tableType == "day" || input.tableType == "week" ? "%Y-%m-%d" : input.tableType == "month" ? "%Y-%m" : input.tableType == "year" ? "%Y" : null;
var aemmEndDate = input.tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {input.tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {input.tableType})";
var aemmStaDate = input.tableType == "year" ? "year(fd.date)" : "fd.date";
var sql = $@"set @i = -1;
select fd.device_number, aemm.avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp
from (
@ -285,7 +306,7 @@ namespace FrontendWebApi.ApiControllers
left join (
select device_number, {sqlAvgRawData}
from {table}
where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'RCV' {buildingSql}
where start_timestamp >= {aemmStaDate} and end_timestamp < {aemmEndDate} and point = 'RCV' {buildingSql}
{sqlWhere} {sqlGroup}
) aemm on aemm.start_timestamp >= fd.date and aemm.end_timestamp < DATE_ADD(fd.date, INTERVAL +1 {input.tableType}) and aemm.device_number = fd.device_number
order by fd.device_number, fd.date";

View File

@ -12,6 +12,7 @@ using Repository.Models;
using System.Data.SqlTypes;
using Microsoft.Extensions.Primitives;
using System.Web;
using Org.BouncyCastle.Utilities.Collections;
namespace Repository.BackendRepository.Implement
{
@ -864,26 +865,28 @@ namespace Repository.BackendRepository.Implement
using (IDbConnection conn = GetDbConnection())
{
conn.Open();
using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
using (TransactionScope scope = new TransactionScope((TransactionScopeOption)TransactionScopeAsyncFlowOption.Enabled, new TimeSpan(0, 5, 0)))
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("select * from device_disaster");
sb.Append("select * from device_disaster;");
var deviceDisaster = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
sb.Clear();
sb.Append("select * from device where deleted = 0");
sb.Append("select * from device where deleted = 0;");
var device = (await conn.QueryAsync<DeviceDisasterOutput>(sb.ToString())).ToList();
dv = dv.Where(x => device.Any(d => d.device_number == x.value.Split('/')[6])).ToList();
sb.Clear();
foreach (var d in dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6])))
var updateList = dv.Where(x => deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6] && dd.device_system_value != x.disasterValue));
foreach (var d in updateList)
{
string device_number = d.value.Split('/')[6];
sb.Append($"update device_disaster set device_system_value = '{d.disasterValue}' where device_number = '{device_number}'; ");
}
foreach (var d in dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6])))
var insertList = dv.Where(x => !deviceDisaster.Any(dd => dd.device_number == x.value.Split('/')[6]));
foreach (var d in insertList)
{
string device_number = d.value.Split('/')[6];
string device_guid = device.Where(x => x.device_number == device_number).Select(x => x.device_guid).FirstOrDefault();
@ -892,8 +895,8 @@ namespace Repository.BackendRepository.Implement
sb.Append($@"
insert into device_disaster
(device_guid, device_system_value, device_building_tag, device_system_tag, device_name_tag, device_floor_tag, device_serial_tag, device_number)
values ({device_guid}, {d.disasterValue}, {device_number.Split('_')[0]}, {device_number.Split('_')[1]}, {device_system_tag}, {device_name_tag},
{device_number.Split('_')[2]}, {device_number.Split('_')[4]}, {device_number}); ");
values ('{device_guid}', '{d.disasterValue}', '{device_number.Split('_')[0]}', '{device_system_tag}', '{device_name_tag}', '{device_number.Split('_')[2]}',
'{device_number.Split('_')[4]}', '{device_number}'); ");
}
if (!string.IsNullOrEmpty(sb.ToString()))

View File

@ -141,6 +141,7 @@ namespace Repository.Models
public string device_floor_tag { get; set; }
public string device_serial_tag { get; set; }
public string device_number { get; set; }
public string device_system_value { get; set; }
}
public class Device_value_disaster

View File

@ -20,11 +20,6 @@ namespace Repository.Models
public partial class Obj
{
[JsonProperty("@href")]
public string? href { get; set; }
[JsonProperty("@icon")]
public string? icon { get; set; }
[JsonProperty("@display")]
public string Display { get; set; }
@ -38,11 +33,7 @@ namespace Repository.Models
public Uri XmlnsXsi { get; set; }
[JsonProperty("str")]
public Str[] Str { get; set; }
[JsonProperty("ref")]
public Str[] Ref { get; set; }
//public Ref Ref { get; set; }
public List<Str> Str { get; set; }
}
public partial class Str
@ -55,25 +46,6 @@ namespace Repository.Models
[JsonProperty("@href")]
public string Href { get; set; }
[JsonProperty("@display")]
public string display { get; set; }
[JsonProperty("@_icon")]
public string _icon { get; set; }
}
public class Ref
{
[JsonProperty("_name")]
public string Name { get; set; }
[JsonProperty("_href")]
public string Href { get; set; }
[JsonProperty("_display")]
public string Display { get; set; }
[JsonProperty("_icon")]
public string Icon { get; set; }
}
public partial class Xml

View File

@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Repository.Models
{
public partial class WelcomeSingle
{
[JsonProperty("?xml")]
public XmlSingle Xml { get; set; }
[JsonProperty("?xml-stylesheet")]
public string XmlStylesheet { get; set; }
[JsonProperty("obj")]
public ObjSingle Obj { get; set; }
}
public partial class ObjSingle
{
[JsonProperty("@display")]
public string Display { get; set; }
[JsonProperty("@xmlns")]
public Uri Xmlns { get; set; }
[JsonProperty("@xsi:schemaLocation")]
public Uri XsiSchemaLocation { get; set; }
[JsonProperty("@xmlns:xsi")]
public Uri XmlnsXsi { get; set; }
[JsonProperty("str")]
public Str Str { get; set; }
}
public partial class StrSingle
{
[JsonProperty("@name")]
public string Name { get; set; }
[JsonProperty("@val")]
public string Val { get; set; }
[JsonProperty("@href")]
public string Href { get; set; }
}
public partial class XmlSingle
{
[JsonProperty("@version")]
public string Version { get; set; }
[JsonProperty("@encoding")]
public string Encoding { get; set; }
}
public partial class WelcomeSingle
{
public static WelcomeSingle FromJson(string json) => JsonConvert.DeserializeObject<WelcomeSingle>(json, Models.ConverterSingle.Settings);
}
public static class SerializeSingle
{
public static string ToJson(this WelcomeSingle self) => JsonConvert.SerializeObject(self, Models.ConverterSingle.Settings);
}
internal static class ConverterSingle
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters =
{
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}