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; using System.Diagnostics; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Repository.Models.CodeBeautify; using NPOI.SS.Formula.Functions; using Microsoft.AspNetCore.Localization; using MySqlX.XDevAPI.Relational; using Backend.Models; namespace Backend.Services.Implement { public class webRequestService { public List obixQuery(string urlString, string bql, string tag_quantity, string acc, string pass) { List result = new List(); //String username = "obixUser"; //String password = "Admin123456"; //String username = "stanGG"; //String password = "St12345678"; 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 = ""; 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(','); string[] s2 = s1[0].Remove(s1[0].Length - 1, 1).Remove(0, 1).Split('/'); string displayName = s1[1].Split('=')[1]; row.tag_name = ""; if (int.Parse(tag_quantity) == 8) { if (s2.Length == 8) { for (int i = 0; i < s2.Length; i++) { if (i == s2.Length - 2) { row.point_name = s2[i]; } 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) { row.tag_name = s2[s2.Length-1]; } else { // 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]; // } //} } row.displayName = displayName; result.Add(row); } } } return result; } /// /// 獲取 niagara history 中的點位 /// /// /// /// /// public List obixHisQuery(string bqlUrlString, string urlString, string slot, string acc, string pass) { //String username = "obixUser"; //String password = "Admin123456"; //String username = "stanGG"; //String password = "St12345678"; String username = acc; String password = pass; String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)); String oneStationName = null; #region get control point data List conPoint = new List(); 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 = ""; 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; row.isHistory = false; conPoint.Add(row); } #endregion #region main program List result = new List(); 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); //ref https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { var stationName = node.Attributes["name"].InnerText; // WSP_Supervisor oneStationName = oneStationName ?? stationName; String API_Url2 = urlString + "/" + stationName; // http://192.168.0.136:8081/obix/histories/WSP_Supervisor 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); foreach (XmlNode node2 in xmlDoc2.DocumentElement.ChildNodes) { string tagName = node2.Attributes["name"].InnerText; if (tagName.Split('_').Length == 9) { ImpNiaItem row = new ImpNiaItem(); 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; //full_name 其實是點位名稱 point_name row.full_name = conPoint.Where(x => x.name == tagName).Select(x => x.displayName).FirstOrDefault(); if (conPoint.Where(x => x.name == tagName).FirstOrDefault() != null) conPoint.Where(x => x.name == tagName).FirstOrDefault().isHistory = true; row.isHistory = true; result.Add(row); } else if (tagName.Split('_').Length == 6) { //巨蛋 tag 5 段版本 ImpNiaItem row = new ImpNiaItem(); 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]; row.device_name_tag = tagName.Split('_')[3]; 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]; } row.parent_path = stationName; //full_name 其實是點位名稱 point_name row.full_name = conPoint.Where(x => x.name.Contains(tagName) && !x.isHistory).Select(x => x.displayName).FirstOrDefault(); if (conPoint.Where(x => x.name.Contains(tagName) && !x.isHistory).FirstOrDefault() != null) conPoint.Where(x => x.name.Contains(tagName) && !x.isHistory).FirstOrDefault().isHistory = true; row.isHistory = true; result.Add(row); } } } #endregion var newConPoint = conPoint.Where(x => !x.isHistory).ToArray(); foreach(var n in newConPoint) { if (n.name.Split('_').Length == 9) { 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], 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 { if (n.name.Split('_')[6] == "S" || n.name.Split('_')[6] == "CWB") //for security system and CWB system { 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], 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], full_name = n.displayName, parent_path = oneStationName, isHistory = n.isHistory }); } } } return result; } //private static void getRefData(string urlString, string encoded, List conPoint, List 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 conPoint, List 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(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 archiveMonthRawData = new Dictionary(); // 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); // } // } //} } }