From 19533f9c6356ba44dd9f9829bbbd21ac2ab06bf8 Mon Sep 17 00:00:00 2001 From: jiahao Date: Fri, 28 Jul 2023 13:31:33 +0800 Subject: [PATCH] =?UTF-8?q?[webAPI]=20-=20=E5=A0=B1=E8=A1=A8=E6=9F=A5?= =?UTF-8?q?=E8=A9=A2=E6=94=B9=E6=8A=93=20kwh=5Fresult?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ApiControllers/HydroMeterController.cs | 4 +- z01_WinAPP/App.config | 14 +- z01_WinAPP/Program.cs | 4 +- z01_WinAPP/Service/getDeviceSvc.cs | 222 +++++++++++++++++- z01_WinAPP/fmCheckTagName.cs | 32 ++- z01_WinAPP/z01_WinAPP.csproj | 1 + 6 files changed, 264 insertions(+), 13 deletions(-) diff --git a/FrontendWebApi/ApiControllers/HydroMeterController.cs b/FrontendWebApi/ApiControllers/HydroMeterController.cs index 2ff72b7..18cb614 100644 --- a/FrontendWebApi/ApiControllers/HydroMeterController.cs +++ b/FrontendWebApi/ApiControllers/HydroMeterController.cs @@ -95,10 +95,10 @@ namespace FrontendWebApi.ApiControllers if (input.tableType == "year") { sqlGroup = $@" group by year(start_timestamp), year(end_timestamp), device_number "; - sqlAvgRawData = " round(avg(avg_rawdata), 2) as avg_rawdata, year(start_timestamp) as start_timestamp, year(end_timestamp) as end_timestamp "; + sqlAvgRawData = " round(avg(kwh_result), 2) as avg_rawdata, year(start_timestamp) as start_timestamp, year(end_timestamp) as end_timestamp "; } else - sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp "; + sqlAvgRawData = " round(kwh_result, 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($"select system_value from variable where system_type = 'project_name'"); diff --git a/z01_WinAPP/App.config b/z01_WinAPP/App.config index 0d579f1..e98b5f4 100644 --- a/z01_WinAPP/App.config +++ b/z01_WinAPP/App.config @@ -6,10 +6,16 @@ connectionString="Data Source=210.65.10.150;Initial Catalog=STSP;Persist Security Info=True;User ID=sa;Password=jsene2wsx#EDC" providerName="System.Data.SqlClient" />--> - - - + + + + + \ No newline at end of file diff --git a/z01_WinAPP/Program.cs b/z01_WinAPP/Program.cs index c9a90d4..5845af6 100644 --- a/z01_WinAPP/Program.cs +++ b/z01_WinAPP/Program.cs @@ -18,8 +18,8 @@ namespace tpDomeWinAPP Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - //Application.Run(new fmCheckTagName()); - Application.Run(new fmDecrypt()); + Application.Run(new fmCheckTagName()); + // Application.Run(new fmDecrypt()); } } } diff --git a/z01_WinAPP/Service/getDeviceSvc.cs b/z01_WinAPP/Service/getDeviceSvc.cs index b0db0fe..c7f3e8e 100644 --- a/z01_WinAPP/Service/getDeviceSvc.cs +++ b/z01_WinAPP/Service/getDeviceSvc.cs @@ -9,6 +9,13 @@ using MySql.Data.MySqlClient; using Repository.Helper; using Repository.BackendRepository.Interface; using Dapper; +using System.Linq; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using FrontendWebApi.Models; +using Autodesk.Forge.Model; +using MySql.Data.MySqlClient; +using System.Data.SqlTypes; namespace tpDomeWinAPP.Service { @@ -31,8 +38,217 @@ namespace tpDomeWinAPP.Service Connection1 = ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString; } } - - public List getDevices() + public IDbConnection GetDbConnection() + { + IDbConnection conn; + //if (UseDB == "MSSQL") + //{ + // conn = new SqlConnection(Connection1); + //} + //else + //{ + //conn = new MySqlConnection(this._databaseHelper.GetMySqlConnectionString()); + conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString); + //} + return conn; + } + + //public List getNiagaraPara() + //{ + // var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'"; + // List result; + // //using (MySqlConnection conn = new MySqlConnection(Connection1)) + // //{ + // // //CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url, + // // conn.Open(); + // // StringBuilder sb = new StringBuilder(); + // // sb.Append(sql); + // // result = conn.Query(sb.ToString()).ToList(); + // //} + + // //var variableObix = backendRepository.GetAllAsync(sqlObix).Result; + // //var obixApiConfig = new Backend.Models.ObixApiConfig(); + // //EDFunction ed = new EDFunction(); + // //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(); + // ////obixApiConfig.UrlSlot = variableObix.Where(x => x.Name == "url_slot").Select(x => x.Value).FirstOrDefault(); + // //webRequestService svc = new webRequestService(); + // //var data = svc.obixHisQuery_v2(obixApiConfig.ApiBase + "obix/config/Program/ObixQuery/query/", obixApiConfig.ApiBase + "obix/histories", "", + // // obixApiConfig.UserName, obixApiConfig.Password); + // //// ds.AddRange(data); + // return result; + //} + + public List test_bgWork_sql() + { + string jwt_str = null; + string tableType = "day"; + string startTime = "2023-07"; + string endTime = "2023-07-21"; + List apiResult = new List(); + + try + { + //using (IDbConnection conn = GetDbConnection()) + //{ + // try + // { + // var sql = sqlString; + + // result = await conn.QueryFirstOrDefaultAsync(sql, param); + // } + // catch (Exception exception) + // { + // throw exception; + // } + // return result; + //} + + using (IDbConnection conn = GetDbConnection()) + { + //CONCAT('{baseURL}', '{deviceKindFilePath}', dk.device_image) AS device_image_url, + + startTime = tableType == "day" || tableType == "week" + ? startTime + "-01" + : tableType == "month" || tableType == "year" ? startTime + "-01-01" + : null; + endTime = tableType == "day" || tableType == "week" + ? startTime.Split("-")[0] + "-" + (Int32.Parse(startTime.Split("-")[1]) + 1).ToString().PadLeft(2, '0') + "-01" + : tableType == "month" ? (Int32.Parse(startTime.Split("-")[0]) + 1) + "-01-01" + : tableType == "year" ? (Int32.Parse(endTime) + 1).ToString() + "-01-01" + : null; + string sqlWhere = ""; + string sqlGroup = ""; + string sqlAvgRawData = ""; + string building_tag = "G6"; + string dbDateName = startTime.Split("-")[0].ToString().PadLeft(4, '0') + startTime.Split("-")[1].ToString().PadLeft(2, '0'); + string buildingSql = ""; + conn.Open(); + + //string tag_quantity = await backendRepository.GetOneAsync("select system_value from variable where system_type = 'obixConfig' and system_key = 'tag_quantity' and deleted = 0"); + string tag_quantity = conn.Query("select system_value from variable where system_type = 'obixConfig' and system_key = 'tag_quantity' and deleted = 0").FirstOrDefault().ToString(); + + if (tag_quantity == "5") + buildingSql = " and SUBSTRING_INDEX(device_number, '_', 1) = @building_tag "; + else + buildingSql = " and SUBSTRING_INDEX(SUBSTRING_INDEX(device_number, '_', 2), '_', -1) = @building_tag "; + + //if (input.floor_tag.Count > 0) + //{ + // if (tag_quantity == "5") + // sqlWhere = $@" and substring_index(substring_index(device_number, '_', 3), '_', -1) in @floor_tag "; + // else + // sqlWhere = $@" and substring_index(substring_index(device_number, '_', 5), '_', -1) in @floor_tag "; + //} + + if (tableType == "year") + { + sqlGroup = $@" group by year(start_timestamp), year(end_timestamp), device_number "; + sqlAvgRawData = " round(avg(avg_rawdata), 2) as avg_rawdata, year(start_timestamp) as start_timestamp, year(end_timestamp) as end_timestamp "; + } + else + sqlAvgRawData = " round(avg_rawdata, 2) as avg_rawdata, start_timestamp, end_timestamp "; + + var table = tableType == "year" ? "archive_electric_meter_month" : "archive_electric_meter_" + tableType + (tableType == "day" ? "_" + dbDateName : ""); + var schema = conn.Query($"select system_value from variable where system_type = 'project_name'").FirstOrDefault(); + var isTable = conn.Query($"select table_name from information_schema.tables where table_name = '{table}' and table_schema = '{schema.Split('/')[0]}'").FirstOrDefault(); + if (string.IsNullOrEmpty(isTable)) //check for has table or not + { + //MessageBox.Show("Empty"); + } + + var dateFormat = tableType == "day" || tableType == "week" ? "%Y-%m-%d" : tableType == "month" ? "%Y-%m" : tableType == "year" ? "%Y" : null; + var aemmEndDate = tableType == "year" ? $"year(DATE_ADD(fd.date, INTERVAL +1 {tableType}))" : $"DATE_ADD(fd.date, INTERVAL +1 {tableType})"; + var aemmStaDate = tableType == "year" ? "year(fd.date)" : "fd.date"; + var sql = $@"set @i = -1; + select fd.device_number, case when aemm.avg_rawdata = -1 then 'NaN' when aemm.avg_rawdata is null then 0.00 else aemm.avg_rawdata end as avg_rawdata, DATE_FORMAT(fd.date, @dateFormat) as timestamp + from ( + select * + from ( + ( + SELECT DATE(ADDDATE(@startTime, INTERVAL @i:=@i+1 day)) AS date + FROM {table} + HAVING @i < TIMESTAMPDIFF({tableType}, @startTime, ADDDATE(@endTime, INTERVAL -1 DAY)) + ) d, + ( + select device_number + from {table} + where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'KWH' {buildingSql} + {sqlWhere} + group by device_number + ) dn + ) + ) fd + left join ( + select device_number, {sqlAvgRawData} + from {table} + where start_timestamp >= @startTime and end_timestamp < @endTime and point = 'KWH' {buildingSql} + {sqlWhere} {sqlGroup} + ) aemm on aemm.start_timestamp >= {aemmStaDate} and aemm.end_timestamp < {aemmEndDate} and aemm.device_number = fd.device_number + order by fd.device_number, fd.date"; + var rawData = conn.Query (sql, + new { startTime = startTime, endtime = endTime, building_tag = building_tag, dateFormat = dateFormat }); + + List list = new List(); + if (tag_quantity == "5") + { + list = rawData + .GroupBy(x => new { building_tag = x.device_number.Split("_")[0], floor_tag = x.device_number.Split("_")[2], device_serial_tag = x.device_number.Split("_")[4], device_number = x.device_number }) + .Select(x => new FrontendWebApi.Models.HydroMeterOutput { building_tag = x.Key.building_tag, floor_tag = x.Key.floor_tag, device_serial_tag = x.Key.device_serial_tag, device_number = x.Key.device_number }) + .ToList(); + } + else + { + list = rawData + .GroupBy(x => new { building_tag = x.device_number.Split("_")[1], floor_tag = x.device_number.Split("_")[4], device_master = x.device_number.Split("_")[5], device_serial_tag = x.device_number.Split("_")[7], device_number = x.device_number }) + .Select(x => new FrontendWebApi.Models.HydroMeterOutput { building_tag = x.Key.building_tag, floor_tag = x.Key.floor_tag, device_serial_tag = x.Key.device_serial_tag, device_master = x.Key.device_master, device_number = x.Key.device_number }) + .ToList(); + } + + foreach (var l in list) + { + l.rawData = new List(); + l.device_full_name = conn.Query($"select full_name from device where device_number = '{l.device_number}'").FirstOrDefault(); + if (tag_quantity == "5") + { + l.rawData.AddRange( + rawData.Where(x => x.device_number.Split("_")[0] == l.building_tag && x.device_number.Split("_")[2] == l.floor_tag && x.device_number.Split("_")[4] == l.device_serial_tag) + ); + } + else + { + l.rawData.AddRange( + rawData.Where(x => x.device_number.Split("_")[1] == l.building_tag && x.device_number.Split("_")[4] == l.floor_tag && x.device_number.Split("_")[5] == l.device_master && x.device_number.Split("_")[7] == l.device_serial_tag) + ); + } + l.building_name = conn.Query("select full_name from building where building_tag = @building_tag and deleted = 0", + new { building_tag = l.building_tag }).FirstOrDefault(); + l.total = l.rawData.Where(x => x.avg_rawdata != "NaN").Sum(x => decimal.Parse(x.avg_rawdata ?? "0", System.Globalization.NumberStyles.Float)).ToString(); + //l.price = input.price.HasValue + // ? (Math.Round(input.price.Value, 2)).ToString() + // : Math.Round((await backendRepository.GetOneAsync("select system_value from variable where system_type = 'ElectricPrice' and deleted = 0")), 2).ToString(); + l.price = "5"; + l.total_price = Math.Round((Decimal.Parse(l.total) * Decimal.Parse(l.price)), 2).ToString(); + } + + //apiResult.Code = "0000"; + //apiResult.Data = list; + return list; + } + } + catch (Exception exception) + { + throw exception.InnerException; + //apiResult.Code = "9999"; + //apiResult.Msg = "系統內部錯誤,請聯絡管理者。"; + //string json = System.Text.Json.JsonSerializer.Serialize(input); + //Logger.LogError("【" + controllerName + "/" + actionName + "】" + json); + //Logger.LogError("【" + controllerName + "/" + actionName + "】" + exception.Message); + } + } + + public List getDevices() { using (SqlConnection conn = new SqlConnection(Connection1)) @@ -82,7 +298,7 @@ namespace tpDomeWinAPP.Service ORDER BY d.priority ASC, d.device_number ASC "; - var devices = conn.Query(sql).AsList(); + var devices = conn.Query(sql).AsList(); return devices; //var sql_node = $@"SELECT // dn.device_node_guid, diff --git a/z01_WinAPP/fmCheckTagName.cs b/z01_WinAPP/fmCheckTagName.cs index 0c26ca4..c73657b 100644 --- a/z01_WinAPP/fmCheckTagName.cs +++ b/z01_WinAPP/fmCheckTagName.cs @@ -9,6 +9,8 @@ using tpDomeWinAPP.Service; using tpDomeWinAPP.Models; using System.Linq; using System.Collections; +using Repository.BackendRepository.Implement; +using MySql.Data.MySqlClient; namespace tpDomeWinAPP { @@ -63,13 +65,39 @@ namespace tpDomeWinAPP ds = null; dataGridView1.DataSource = null; - loadData(); + + // loadData(); + getDeviceSvc svc = new getDeviceSvc(); + var data = svc.test_bgWork_sql(); + //var data = svc.getDevices(); + dataGridView1.DataSource = data; + + //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); + + //// 1.循環所有的 station + ////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 + //} //load form //var tab = tabControl1.TabPages[2]; //tabControl1.TabPages[2].Controls. - + //if (dsDevice.Count == 0) loadData(); diff --git a/z01_WinAPP/z01_WinAPP.csproj b/z01_WinAPP/z01_WinAPP.csproj index 19f95ce..214c11d 100644 --- a/z01_WinAPP/z01_WinAPP.csproj +++ b/z01_WinAPP/z01_WinAPP.csproj @@ -11,6 +11,7 @@ +