ibms-dome/Backend/Services/Implement/webRequestService.cs

546 lines
25 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Newtonsoft.Json;
using Repository.Models;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;
using Repository.BackendRepository.Implement;
using Repository.BackendRepository;
using Ubiety.Dns.Core;
2023-01-13 17:28:23 +08:00
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
2023-03-07 15:02:29 +08:00
using Repository.Models.CodeBeautify;
using NPOI.SS.Formula.Functions;
2023-04-26 17:43:55 +08:00
using Microsoft.AspNetCore.Localization;
using MySqlX.XDevAPI.Relational;
using Backend.Models;
2023-05-19 10:06:18 +08:00
using NPOI.OpenXmlFormats.Dml;
namespace Backend.Services.Implement
{
public class webRequestService
{
2023-04-26 17:43:55 +08:00
public List<Device_value> obixQuery(string urlString, string bql, string tag_quantity, string acc, string pass)
{
List<Device_value> result = new List<Device_value>();
2023-04-26 17:43:55 +08:00
//String username = "obixUser";
//String password = "Admin123456";
2023-04-25 00:48:12 +08:00
//String username = "stanGG";
//String password = "St12345678";
2023-04-26 17:43:55 +08:00
String username = acc;
String password = pass;
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
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()))
{
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);
//xmlDoc.Load("N4v1021.xml");//N4v1021
//xmlDoc.Save("N4.xml");
string jsonText = JsonConvert.SerializeXmlNode(xmlDoc);
var data = Welcome.FromJson(jsonText);
foreach (var item in data.Obj.Str)
{
Device_value row = new Device_value();
row.value = item.Val;
string[] s1 = item.Val.Split(',');
2023-01-13 17:28:23 +08:00
string[] s2 = s1[0].Remove(s1[0].Length - 1, 1).Remove(0, 1).Split('/');
string displayName = s1[1].Split('=')[1];
2022-11-11 15:44:40 +08:00
row.tag_name = "";
2023-04-11 10:28:33 +08:00
if (int.Parse(tag_quantity) == 8)
2022-11-11 15:44:40 +08:00
{
2023-04-11 10:28:33 +08:00
if (s2.Length == 8)
2022-11-11 15:44:40 +08:00
{
2023-04-11 10:28:33 +08:00
for (int i = 0; i < s2.Length; i++)
2023-01-13 17:28:23 +08:00
{
2023-04-11 10:28:33 +08:00
if (i == s2.Length - 2)
{
row.point_name = s2[i];
}
2023-01-30 16:04:29 +08:00
2023-04-11 10:28:33 +08:00
if (i == 0)
{
row.tag_name += s2[i];
}
else
{
row.tag_name += "_" + s2[i];
}
}
row.displayName = displayName;
result.Add(row);
}
}
else {
if (s2.Length >=5)
{
// tag 在最後一段: Arena/D2/B/B2F/EL/D2_B_B2F_EL_424/
var lastStr = s2[s2.Length-1].Split('_');
if (lastStr.Length > 3)
2023-01-13 17:28:23 +08:00
{
2023-04-11 10:28:33 +08:00
row.tag_name = s2[s2.Length-1];
2023-01-13 17:28:23 +08:00
}
2023-01-30 16:04:29 +08:00
else
2023-04-11 10:28:33 +08:00
{ // tag 需要串接前幾段Arena/D2/B/B2F/EL/
// 這種的不需要匯入
//for (int i = 0; i < s2.Length; i++)
//{
// if (i == 0)
// {
// row.tag_name += s2[i];
// }
// else
// {
// row.tag_name += "_" + s2[i];
// }
//}
2023-01-13 17:28:23 +08:00
}
2023-04-11 10:28:33 +08:00
row.displayName = displayName;
result.Add(row);
}
}
2023-01-13 17:28:23 +08:00
}
return result;
}
2023-03-28 13:48:30 +08:00
/// <summary>
/// 獲取 niagara history 中的點位
/// </summary>
/// <param name="bqlUrlString"></param>
/// <param name="urlString"></param>
/// <param name="slot"></param>
/// <returns></returns>
2023-04-21 17:40:18 +08:00
public List<ImpNiaItem> obixHisQuery(string bqlUrlString, string urlString, string slot, string acc, string pass)
2023-01-13 17:28:23 +08:00
{
2023-04-21 02:06:32 +08:00
//String username = "obixUser";
//String password = "Admin123456";
2023-04-25 00:48:12 +08:00
//String username = "stanGG";
//String password = "St12345678";
2023-04-21 17:40:18 +08:00
String username = acc;
String password = pass;
2023-01-13 17:28:23 +08:00
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
2023-04-26 17:43:55 +08:00
String oneStationName = null;
2023-01-13 17:28:23 +08:00
#region get control point data
List<control_point> conPoint = new List<control_point>();
String cp_API_Url = bqlUrlString;
HttpWebRequest cp_Postrequest = (HttpWebRequest)WebRequest.Create(cp_API_Url);
cp_Postrequest.Method = "POST";
cp_Postrequest.Headers.Add("Authorization", "Basic " + encoded);
cp_Postrequest.PreAuthenticate = true;
using (var streamWriter = new StreamWriter(cp_Postrequest.GetRequestStream()))
{
string json = "<str val='" + slot + "bql: select * from control:ControlPoint'/>";
streamWriter.Write(json);
}
HttpWebResponse cp_response = (HttpWebResponse)cp_Postrequest.GetResponse();
var cp_responseString = new StreamReader(cp_response.GetResponseStream()).ReadToEnd();
XmlDocument cp_xmlDoc = new XmlDocument();
cp_xmlDoc.LoadXml(cp_responseString);
string cp_jsonText = JsonConvert.SerializeXmlNode(cp_xmlDoc);
var cp_data = Welcome.FromJson(cp_jsonText);
foreach (var item in cp_data.Obj.Str)
{
control_point row = new control_point();
string[] s1 = item.Val.Split(',');
string[] s2 = s1[0].Split('/');
var displayName = s1[1].Split('=')[1];
row.name = s1[0].Remove(s1[0].Length - 1, 1).Remove(0, 1);
2023-01-13 17:28:23 +08:00
row.displayName = displayName;
2023-04-26 17:43:55 +08:00
row.isHistory = false;
2023-01-13 17:28:23 +08:00
conPoint.Add(row);
}
#endregion
#region main program
List<ImpNiaItem> result = new List<ImpNiaItem>();
String API_Url = urlString;
HttpWebRequest Postrequest = (HttpWebRequest)WebRequest.Create(API_Url);
Postrequest.Method = "GET";
Postrequest.Headers.Add("Authorization", "Basic " + encoded);
Postrequest.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)Postrequest.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(responseString);
2023-03-07 15:02:29 +08:00
//ref https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c
foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
2023-01-13 17:28:23 +08:00
{
2023-04-26 17:43:55 +08:00
var stationName = node.Attributes["name"].InnerText; // WSP_Supervisor
oneStationName = oneStationName ?? stationName;
2023-03-07 15:02:29 +08:00
String API_Url2 = urlString + "/" + stationName; // http://192.168.0.136:8081/obix/histories/WSP_Supervisor
2023-01-13 17:28:23 +08:00
HttpWebRequest Postrequest2 = (HttpWebRequest)WebRequest.Create(API_Url2);
Postrequest2.Method = "GET";
Postrequest2.Headers.Add("Authorization", "Basic " + encoded);
Postrequest2.PreAuthenticate = true;
HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse();
var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
XmlDocument xmlDoc2 = new XmlDocument();
xmlDoc2.LoadXml(responseString2);
2023-03-07 15:02:29 +08:00
foreach (XmlNode node2 in xmlDoc2.DocumentElement.ChildNodes)
{
2023-03-07 15:02:29 +08:00
string tagName = node2.Attributes["name"].InnerText;
if (tagName.Split('_').Length == 9)
{
2023-01-13 17:28:23 +08:00
ImpNiaItem row = new ImpNiaItem();
2023-03-07 15:02:29 +08:00
row.device_area_tag = tagName.Split('_')[0];
row.device_building_tag = tagName.Split('_')[1];
row.device_system_tag = tagName.Split('_')[2];
row.device_name_tag = tagName.Split('_')[3];
row.device_point_name = tagName.Split('_')[8];
row.parent_path = stationName;
2023-01-31 15:45:38 +08:00
//full_name 其實是點位名稱 point_name
2023-05-17 14:25:24 +08:00
row.full_name = conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).Select(x => x.displayName).FirstOrDefault();
if (conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).FirstOrDefault() != null)
conPoint.Where(x => x.name == tagName.Replace('_', '/') && !x.isHistory).FirstOrDefault().isHistory = true;
2023-04-26 17:43:55 +08:00
row.isHistory = true;
2023-01-13 17:28:23 +08:00
result.Add(row);
2023-03-07 15:02:29 +08:00
} else if (tagName.Split('_').Length == 6)
{ //巨蛋 tag 5 段版本
2023-03-28 13:48:30 +08:00
ImpNiaItem row = new ImpNiaItem();
2023-04-21 17:40:18 +08:00
if (tagName.Split('_')[1] == "S") //for security system
{
row.device_building_tag = tagName.Split('_')[0];
row.device_system_tag = tagName.Split('_')[1];
row.device_floor_tag = tagName.Split('_')[2];
2023-04-26 17:43:55 +08:00
row.device_name_tag = tagName.Split('_')[3];
2023-04-21 17:40:18 +08:00
row.device_point_name = tagName.Split('_')[5];
}
else //for normal
{
row.device_building_tag = tagName.Split('_')[0];
//row.device_system_tag = tagName.Split('_')[1];
row.device_floor_tag = tagName.Split('_')[2];
row.device_name_tag = tagName.Split('_')[1];
row.device_point_name = tagName.Split('_')[5];
}
2023-03-28 13:48:30 +08:00
2023-04-21 17:40:18 +08:00
row.parent_path = stationName;
2023-03-28 13:48:30 +08:00
//full_name 其實是點位名稱 point_name
2023-05-19 10:06:18 +08:00
var deviceNumber = tagName.Substring(0, tagName.LastIndexOf(tagName.Split("_")[5]) - 1);
var point = tagName.Split("_")[5];
conPoint = conPoint.Where(x => x.name.Split("/").Length > 6).ToList();
row.full_name = conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).Select(x => x.displayName).FirstOrDefault();
if (conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).FirstOrDefault() != null)
conPoint.Where(x => x.name.Split("/")[5] == deviceNumber && x.name.Split("/")[6] == point && !x.isHistory).FirstOrDefault().isHistory = true;
2023-04-26 17:43:55 +08:00
row.isHistory = true;
2023-04-21 02:06:32 +08:00
result.Add(row);
2023-01-13 17:28:23 +08:00
}
2023-03-07 15:02:29 +08:00
}
}
2023-01-13 17:28:23 +08:00
#endregion
2023-04-26 17:43:55 +08:00
var newConPoint = conPoint.Where(x => !x.isHistory).ToArray();
foreach(var n in newConPoint)
{
if (n.name.Split('/').Length == 9)
2023-04-26 17:43:55 +08:00
{
result.Add(new ImpNiaItem
{
device_area_tag = n.name.Split('/')[0],
device_building_tag = n.name.Split('/')[1],
device_system_tag = n.name.Split('/')[2],
device_name_tag = n.name.Split('/')[3],
device_point_name = n.name.Split('/')[8],
2023-04-26 17:43:55 +08:00
full_name = n.displayName,
parent_path = oneStationName,
isHistory = n.isHistory
});
}
else if (n.name.Split('/').Length == 11) //Arena_D2_CWB_L110_CAP_D2_CWB_L110_CAP_MET1_ER
2023-04-26 17:43:55 +08:00
{
if (n.name.Split('/')[6] == "S" || n.name.Split('/')[6] == "CWB") //for security system and CWB system
2023-04-26 17:43:55 +08:00
{
result.Add(new ImpNiaItem {
device_building_tag = n.name.Split('/')[5],
device_system_tag = n.name.Split('/')[6],
device_floor_tag = n.name.Split('/')[7],
device_name_tag = n.name.Split('/')[8],
device_point_name = n.name.Split('/')[10],
2023-04-26 17:43:55 +08:00
full_name = n.displayName,
parent_path = oneStationName,
isHistory = n.isHistory
});
}
else //for normal
{
result.Add(new ImpNiaItem
{
device_building_tag = n.name.Split('/')[5],
//device_system_tag = n.name.Split('/')[1],
device_floor_tag = n.name.Split('/')[7],
device_name_tag = n.name.Split('/')[6],
device_point_name = n.name.Split('/')[10],
2023-04-26 17:43:55 +08:00
full_name = n.displayName,
parent_path = oneStationName,
isHistory = n.isHistory
});
}
}
}
2023-01-13 17:28:23 +08:00
2023-05-17 15:42:21 +08:00
return result.Where(x => x.full_name != null).ToList();
}
public List<Device_value_disaster> obixDevDisaster(string urlString, string bql, string tag_quantity, string acc, string pass, string dt)
{
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()))
{
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);
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++)
{
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);
}
}
return result;
}
2023-03-07 15:02:29 +08:00
//private static void getRefData(string urlString, string encoded, List<control_point> conPoint, List<ImpNiaItem> result, Welcome data ) //obixHistory data
//{
// foreach (var item in data.Obj.Ref)
// {
// //var item = data.Obj.Ref;
// String API_Url2 = urlString + "/" + item.Name;
// HttpWebRequest Postrequest2 = (HttpWebRequest)WebRequest.Create(API_Url2);
// Postrequest2.Method = "GET";
// Postrequest2.Headers.Add("Authorization", "Basic " + encoded);
// Postrequest2.PreAuthenticate = true;
// HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse();
// var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
// XmlDocument xmlDoc2 = new XmlDocument();
// xmlDoc2.LoadXml(responseString2);
// string jsonText2 = JsonConvert.SerializeXmlNode(xmlDoc2);
// var data2 = Welcome.FromJson(jsonText2);
// foreach (var item2 in data2.Obj.Ref)
// {
// if (item2.Name.Split('_').Length == 9)
// {
// ImpNiaItem row = new ImpNiaItem();
// row.device_area_tag = item2.Name.Split('_')[0];
// row.device_building_tag = item2.Name.Split('_')[1];
// row.device_system_tag = item2.Name.Split('_')[2];
// row.device_name_tag = item2.Name.Split('_')[3];
// row.device_point_name = item2.Name.Split('_')[8];
// row.parent_path = item.Name;
// //full_name 其實是點位名稱 point_name
// row.full_name = conPoint.Where(x => x.name == item2.Name).Select(x => x.displayName).FirstOrDefault();
// result.Add(row);
// }
// }
// }
//}
//private static void getRefData(string urlString, string encoded, List<control_point> conPoint, List<ImpNiaItem> result, Welcome4 data)
//{
// foreach (var item in data.Obj.Ref)
// {
// String API_Url2 = urlString + "/" + item.Name;
// HttpWebRequest Postrequest2 = (HttpWebRequest)WebRequest.Create(API_Url2);
// Postrequest2.Method = "GET";
// Postrequest2.Headers.Add("Authorization", "Basic " + encoded);
// Postrequest2.PreAuthenticate = true;
// HttpWebResponse response2 = (HttpWebResponse)Postrequest2.GetResponse();
// var responseString2 = new StreamReader(response2.GetResponseStream()).ReadToEnd();
// XmlDocument xmlDoc2 = new XmlDocument();
// xmlDoc2.LoadXml(responseString2);
// string jsonText2 = JsonConvert.SerializeXmlNode(xmlDoc2);
// var data2 = Welcome.FromJson(jsonText2);
// foreach (var item2 in data2.Obj.Ref)
// {
// if (item2.Name.Split('_').Length == 9)
// {
// ImpNiaItem row = new ImpNiaItem();
// row.device_area_tag = item2.Name.Split('_')[0];
// row.device_building_tag = item2.Name.Split('_')[1];
// row.device_system_tag = item2.Name.Split('_')[2];
// row.device_name_tag = item2.Name.Split('_')[3];
// row.device_point_name = item2.Name.Split('_')[8];
// row.parent_path = item.Name;
// //full_name 其實是點位名稱 point_name
// row.full_name = conPoint.Where(x => x.name == item2.Name).Select(x => x.displayName).FirstOrDefault();
// result.Add(row);
// }
// }
// }
//}
//public void getObix()
//{
// //#region 取得obix 設定
// //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 backgroundServiceRepository.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 設定
// HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/FIC_Center/{deviceNumberPoint.FullDeviceNumberPoint}/~historyRollup/");
// //HttpWebRequest archiveMonthRequest = (HttpWebRequest)WebRequest.Create($"{obixApiConfig.ApiBase}obix/histories/FIC_Center/H_E1_B1F_MVCB_MVCBH_V1/~historyRollup/");
// archiveMonthRequest.Method = "POST";
// archiveMonthRequest.Headers.Add("Authorization", "Basic " + encoded);
// archiveMonthRequest.PreAuthenticate = true;
// byte[] byteArray = Encoding.UTF8.GetBytes(historyQueryFilter);
// using (Stream reqStream = archiveMonthRequest.GetRequestStream())
// {
// reqStream.Write(byteArray, 0, byteArray.Length);
// }
// HttpWebResponse archiveMonthResponse = (HttpWebResponse)archiveMonthRequest.GetResponse();
// var archiveMonthResponseContent = new StreamReader(archiveMonthResponse.GetResponseStream()).ReadToEnd();
// xmlDocument.LoadXml(archiveMonthResponseContent);
// string archiveMonthJson = JsonConvert.SerializeXmlNode(xmlDocument);
// JObject archiveMonthJsonResult = (JObject)JsonConvert.DeserializeObject(archiveMonthJson);
// if (archiveMonthJsonResult.ContainsKey("err")) //抓取錯誤
// {
// //logger.LogError("【ArchiveElectricMeterDayJob】【月歸檔】【取得資料失敗】");
// //logger.LogError("【ArchiveElectricMeterDayJob】【月歸檔】【取得資料失敗】[錯誤內容]{0}", archiveMonthJsonResult);
// Dictionary<string, object> archiveMonthRawData = new Dictionary<string, object>();
// archiveMonthRawData.Add("@device_number", deviceNumberPoint.DeviceNumber);
// archiveMonthRawData.Add("@point", deviceNumberPoint.Point);
// archiveMonthRawData.Add("@start_timestamp", startTimestamp.Replace("T", " ").Substring(0, 19));
// archiveMonthRawData.Add("@end_timestamp", endTimestamp.Replace("T", " ").Substring(0, 19));
// archiveMonthRawData.Add("@is_complete", 0);
// archiveMonthRawData.Add("@repeat_times", 0);
// archiveMonthRawData.Add("@fail_reason", archiveMonthJson);
// archiveMonthRawData.Add("@count_rawdata", 0);
// archiveMonthRawData.Add("@min_rawdata", 0);
// archiveMonthRawData.Add("@max_rawdata", 0);
// archiveMonthRawData.Add("@avg_rawdata", 0);
// archiveMonthRawData.Add("@sum_rawdata", 0);
// archiveMonthRawData.Add("@updated_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
// archiveMonthRawDatas.Add(archiveMonthRawData);
// }
// if (archiveMonthJsonResult.ContainsKey("obj")) //表示可以讀取到內容
// {
// var ArrangeRawDatas = ArrangeRawData(deviceNumberPoint, archiveMonthJsonResult);
// if (ArrangeRawDatas != null && ArrangeRawDatas.Count() > 0)
// {
// archiveMonthRawDatas.AddRange(ArrangeRawDatas);
// }
// }
//}
}
}