[webAPI] - 報表查詢改抓 kwh_result

This commit is contained in:
jiahao 2023-07-28 13:31:33 +08:00
parent ecf97b5a23
commit 19533f9c63
6 changed files with 264 additions and 13 deletions

View File

@ -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<string>($"select system_value from variable where system_type = 'project_name'");

View File

@ -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" />-->
<!--<add name="dbConStr"
connectionString="Data Source=192.168.0.201:33306;Initial Catalog=bims_mitsubishi;Persist Security Info=True;User ID=bims;Password=mjmdev_BIMS2022"
connectionString="Data Source=192.168.0.201:33306;Initial Catalog=MCUT;Persist Security Info=True;User ID=root;Password=mjmdev_bim"
providerName="MySql.Data.MySqlClient" />-->
<add name="dbConStr" connectionString="server=192.168.0.201;user=bims;Database=bims_mitsubishi;Port=33306;password=mjmdev_BIMS2022;charset='utf8';pooling=true;sslmode=none;;Connection Timeout=6000" providerName="MySql.Data.MySqlClient" />
<add name="dbConStr"
connectionString="server=192.168.0.201;port=33306;database=MCUT;user=root;password=mjmdev_bim;charset=utf8;Allow User Variables=True;"
providerName="MySql.Data.MySqlClient" />
<!-- var connStr = $"server={serverStr};port={portStr};database={databaseStr};user={rootStr};password={passwordStr};charset=utf8;Allow User Variables=True;";-->
<!--<add name="dbConStr" connectionString="server=192.168.0.201;user=bims;Database=MCUT;Port=33306;password=mjmdev_BIMS2022;
charset='utf8';pooling=true;sslmode=none;;Connection Timeout=6000"
providerName="MySql.Data.MySqlClient" />-->
</connectionStrings>
</configuration>

View File

@ -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());
}
}
}

View File

@ -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<Device> 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<NiagaraTags> getNiagaraPara()
//{
// var sqlObix = $@"SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'";
// List<NiagaraTags> 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<NiagaraTags>(sb.ToString()).ToList<NiagaraTags>();
// //}
// //var variableObix = backendRepository.GetAllAsync<Backend.Models.KeyValue>(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<FrontendWebApi.Models.HydroMeterOutput> test_bgWork_sql()
{
string jwt_str = null;
string tableType = "day";
string startTime = "2023-07";
string endTime = "2023-07-21";
List<HydroMeterOutput> apiResult = new List<HydroMeterOutput>();
try
{
//using (IDbConnection conn = GetDbConnection())
//{
// try
// {
// var sql = sqlString;
// result = await conn.QueryFirstOrDefaultAsync<A>(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<string>("select system_value from variable where system_type = 'obixConfig' and system_key = 'tag_quantity' and deleted = 0");
string tag_quantity = conn.Query<string>("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<string>($"select system_value from variable where system_type = 'project_name'").FirstOrDefault();
var isTable = conn.Query<string>($"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<FrontendWebApi.Models.HydroMeterRawDataOutput> (sql,
new { startTime = startTime, endtime = endTime, building_tag = building_tag, dateFormat = dateFormat });
List<HydroMeterOutput> list = new List<HydroMeterOutput>();
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<HydroMeterRawDataOutput>();
l.device_full_name = conn.Query<string>($"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<string>("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<decimal>("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<tpDomeWinAPP.Models.Device> 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<Device>(sql).AsList<Device>();
var devices = conn.Query<tpDomeWinAPP.Models.Device>(sql).AsList<tpDomeWinAPP.Models.Device>();
return devices;
//var sql_node = $@"SELECT
// dn.device_node_guid,

View File

@ -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<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);
//// 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();

View File

@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FrontendWebApi\FrontendWebApi.csproj" />
<ProjectReference Include="..\Repository\Repository.csproj" />
</ItemGroup>