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

383 lines
17 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;
namespace Backend.Services.Implement
{
public class webRequestService
{
public List<Device_value> obixQuery(string urlString, string bql)
{
List<Device_value> result = new List<Device_value>();
String username = "obixUser";
String password = "Admin123456";
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-01-13 17:28:23 +08:00
if (s2.Length == 8)
2022-11-11 15:44:40 +08:00
{
2023-01-13 17:28:23 +08:00
for (int i = 0; i < s2.Length; i++)
2022-11-11 15:44:40 +08:00
{
2023-01-13 17:28:23 +08:00
if (i == s2.Length - 2)
{
row.point_name = s2[i];
}
2023-01-30 16:04:29 +08:00
if (i == 0)
2023-01-13 17:28:23 +08:00
{
row.tag_name += s2[i];
}
2023-01-30 16:04:29 +08:00
else
2023-01-13 17:28:23 +08:00
{
row.tag_name += "_" + s2[i];
}
2022-11-11 15:44:40 +08:00
}
2023-01-13 17:28:23 +08:00
row.displayName = displayName;
/*foreach (var ss in s2)
2022-11-11 15:44:40 +08:00
{
2023-01-13 17:28:23 +08:00
if (ss.Contains('_'))
{
string[] s3 = ss.Split('_');
if (s3.Count() > 3)
{
row.tag_name = ss;
row.point_name = s2[s2.Length - 2];
break;
}
}
}*/
result.Add(row);
2022-11-11 15:44:40 +08:00
}
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-01-13 17:28:23 +08:00
public List<ImpNiaItem> obixHisQuery(string bqlUrlString, string urlString, string slot)
{
String username = "obixUser";
String password = "Admin123456";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
#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].Replace('/', '_').Remove(s1[0].Length - 1, 1).Remove(0, 1);
row.displayName = displayName;
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-03-07 15:02:29 +08:00
string stationName = node.Attributes["name"].InnerText; // WSP_Supervisor
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-03-07 15:02:29 +08:00
row.full_name = conPoint.Where(x => x.name == tagName).Select(x => x.displayName).FirstOrDefault();
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();
row.device_building_tag = tagName.Split('_')[0];
row.device_system_tag = tagName.Split('_')[1];
//row.device_floor_tag = tagName.Split('_')[4];
row.device_name_tag = tagName.Split('_')[3];
row.device_point_name = tagName.Split('_')[8];
row.parent_path = stationName;
//full_name 其實是點位名稱 point_name
row.full_name = conPoint.Where(x => x.name == tagName).Select(x => x.displayName).FirstOrDefault();
2023-01-13 17:28:23 +08:00
}
2023-03-07 15:02:29 +08:00
}
}
2023-03-07 15:02:29 +08:00
2023-01-13 17:28:23 +08:00
#endregion
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);
// }
// }
//}
}
}