FIC_Solar/SolarPower/Quartz/Jobs/CalcAvgPowerStationJob.cs
2021-07-19 17:42:59 +08:00

463 lines
26 KiB
C#

using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Quartz;
using SolarPower.Models.PowerStation;
using SolarPower.Repository.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace SolarPower.Quartz.Jobs
{
[DisallowConcurrentExecution]
public class CalcAvgPowerStationJob : IJob
{
private readonly ILogger<CalcAvgPowerStationJob> logger;
private readonly IPowerStationRepository powerStationRepository;
public CalcAvgPowerStationJob(ILogger<CalcAvgPowerStationJob> logger, IPowerStationRepository powerStationRepository)
{
this.logger = logger;
this.powerStationRepository = powerStationRepository;
}
public async Task Execute(IJobExecutionContext context)
{
try
{
#region step1.
logger.LogInformation("【CalcAvgPowerStationJob】【開始取得電站資料】");
var powerStations = await powerStationRepository.GetAllAsync();
logger.LogInformation("【CalcAvgPowerStationJob】【取得成功電站資料】");
logger.LogInformation("【CalcAvgPowerStationJob】【電站資料】 - {0}", System.Text.Json.JsonSerializer.Serialize(powerStations));
#endregion
List<PowerStation> calcAvgPowerStations = new List<PowerStation>();
List<PowerStationHistoryDay> powerStationHistoryDays = new List<PowerStationHistoryDay>();
List<PowerStationHistoryMonth> insertPowerStationHistoryMonths = new List<PowerStationHistoryMonth>();
List<PowerStationHistoryMonth> updatePowerStationHistoryMonths = new List<PowerStationHistoryMonth>();
List<PyrheliometerHistory> pyrheliometerHistoryDays = new List<PyrheliometerHistory>();
List<PyrheliometerHistory> insertPyrheliometerHistoryMonths = new List<PyrheliometerHistory>();
List<PyrheliometerHistory> updatePyrheliometerHistoryMonths = new List<PyrheliometerHistory>();
List<InverterHistory> allofInverterHistorDays = new List<InverterHistory>();
List<InverterHistory> insertInverterHistoryMonths = new List<InverterHistory>();
List<InverterHistory> updateInverterHistoryMonths = new List<InverterHistory>();
List<WeatherForecast> weatherForecasts = new List<WeatherForecast>();
var DateTimeNow = DateTime.Now;
var count = 0;
#region ()
logger.LogInformation("【CalcAvgPowerStationJob】【開始取得氣象觀測】");
var client = new HttpClient();
var UVUri = "https://opendata.cwb.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=CWB-EA24220B-DDCC-4188-84E5-AD37A0E03F80&elementName=Wx,PoP&sort=time";
HttpResponseMessage response = client.GetAsync(UVUri).Result;
String jsonUVs = response.Content.ReadAsStringAsync().Result.ToString();
Root2 observation = JsonConvert.DeserializeObject<Root2>(jsonUVs);
logger.LogInformation("【CalcAvgPowerStationJob】【取得成功氣象觀測】");
#endregion
foreach (var location in observation.Records.Location)
{
WeatherForecast weatherForecast = new WeatherForecast();
weatherForecast.LocationName = location.LocationName;
List<WeatherForecast> SubweatherForecasts = new List<WeatherForecast>();
foreach (var a in location.WeatherElement)
{
if (a.ElementName == "Wx")
{
foreach (var time in a.Time)
{
int index = 0;
if (location.WeatherElement[0].ElementName == "Wx")
{
weatherForecast = new WeatherForecast();
weatherForecast.LocationName = location.LocationName;
weatherForecast.StartTime = time.StartTime.ToString();
weatherForecast.EndTime = time.EndTime.ToString();
weatherForecast.Wx = time.Parameter.ParameterName;
weatherForecast.WxValue = time.Parameter.ParameterValue;
SubweatherForecasts.Add(weatherForecast);
}
else
{
SubweatherForecasts[index].StartTime = time.StartTime.ToString();
SubweatherForecasts[index].EndTime = time.EndTime.ToString();
SubweatherForecasts[index].Wx = time.Parameter.ParameterName;
SubweatherForecasts[index].WxValue = time.Parameter.ParameterValue;
//SubweatherForecasts.Add(weatherForecast);
index++;
}
//weatherForecasts.Add(weatherForecast);
}
}
if (a.ElementName == "PoP")
{
int index = 0;
foreach (var time in a.Time)
{
if (location.WeatherElement[0].ElementName == "PoP")
{
weatherForecast = new WeatherForecast();
weatherForecast.LocationName = location.LocationName;
weatherForecast.PoP = time.Parameter.ParameterName;
SubweatherForecasts.Add(weatherForecast);
}
else
{
SubweatherForecasts[index].PoP = time.Parameter.ParameterName;
//SubweatherForecasts.Add(weatherForecast);
index++;
}
}
}
}
weatherForecasts.AddRange(SubweatherForecasts);
}
List<string> weather_forecast_properties = new List<string>()
{
"LocationName",
"StartTime",
"EndTime",
"Wx",
"WxValue",
"PoP"
};
await powerStationRepository.AddWeatherForecast(weatherForecasts, weather_forecast_properties);
#region step2. DB及電站編號找出該電站的控制器
foreach (var powerStation in powerStations)
{
if (count > 0)
{
break;
}
var calcPowerStation = new PowerStation();
calcPowerStation.Id = powerStation.Id;
var dateNowDay = DateTimeNow.AddDays(-1).ToString("yyyy-MM-dd");
#region step2-1. 30
var table_name = String.Format("`{0}`.`s{1}01_station`", powerStation.SiteDB, powerStation.Code);
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}的30天平均資料】", powerStation.Code, dateNowDay);
var history = await powerStationRepository.CalcAvgPowerStationHistory30day(dateNowDay, table_name);
logger.LogInformation("【CalcAvgPowerStationJob】【取得成功電站[{0}]在{1}的30天平均資料】", powerStation.Code, dateNowDay);
logger.LogInformation("【CalcAvgPowerStationJob】【電站[{0}]在{1}的30天平均資料】 - {2}", powerStation.Code, dateNowDay, System.Text.Json.JsonSerializer.Serialize(history));
if (history != null)
{
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}的30天平均資料】", powerStation.Code, dateNowDay);
history.PowerStationId = powerStation.Id;
#region 30 kWh/kWp PR
#region kWh/kWp
//直接填寫
calcPowerStation.Avg_kwhkwp = history.AvgKWHKWP;
#endregion
#region PR
//直接填寫
calcPowerStation.Avg_PR = history.AvgPR;
#endregion
#endregion
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}的30天平均資料】", powerStation.Code, dateNowDay);
}
#endregion
#region step2-2 30
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}的30天日照計平均資料】", powerStation.Code, dateNowDay);
var avgPyrheliometerHistory = await powerStationRepository.CalcAvgPyrheliometerHistory30day(dateNowDay, powerStation.Id);
logger.LogInformation("【CalcAvgPowerStationJob】【取得成功電站[{0}]在{1}的30天日照計平均資料】", powerStation.Code, dateNowDay);
logger.LogInformation("【CalcAvgPowerStationJob】【電站[{0}]在{1}的30天日照計平均資料】 - {2}", powerStation.Code, dateNowDay, System.Text.Json.JsonSerializer.Serialize(avgPyrheliometerHistory));
if (avgPyrheliometerHistory != null)
{
calcPowerStation.Avg_irradiance = avgPyrheliometerHistory.AvgIrradiance;
}
calcAvgPowerStations.Add(calcPowerStation);
#endregion
#region step2-3.
//電站資訊
logger.LogInformation("【CalcAvgPowerStationJob】【開始取得電站[{0}]在{1}的所有值的總和】", powerStation.Code, dateNowDay);
var historyDay = await powerStationRepository.GetLastOnePowerStationHistoryByDay(dateNowDay, table_name);
logger.LogInformation("【CalcAvgPowerStationJob】【取得成功電站[{0}]在{1}的所有值的總和】", powerStation.Code, dateNowDay);
logger.LogInformation("【CalcAvgPowerStationJob】【電站[{0}]在{1}的所有值的總和】 - {2}", powerStation.Code, dateNowDay, System.Text.Json.JsonSerializer.Serialize(historyDay));
var daynow = DateTime.Now.ToString("yyyy-MM-dd");
var moneyandcarbon = await powerStationRepository.GetMoneyAndCarbonWithHistoryHour(powerStation.Id, dateNowDay, 1);
var lastmoneyhistory = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 1,"");
if (historyDay != null)
{
historyDay.PowerStationId = powerStation.Id;
historyDay.CARBON = moneyandcarbon.CARBON;
historyDay.MONEY = moneyandcarbon.MONEY;
//historyDay.TODAYCARBON = lastmoneyhistory.TODAYCARBON;
//historyDay.TODAYMONEY = lastmoneyhistory.TODAYMONEY ;
historyDay.TOTALCARBON = lastmoneyhistory.TOTALCARBON + moneyandcarbon.CARBON;
historyDay.TOTALMONEY = lastmoneyhistory.TOTALMONEY + moneyandcarbon.MONEY;
powerStationHistoryDays.Add(historyDay);
}
//日照計
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}的日照計所有值的平均】", powerStation.Code, dateNowDay);
var pyrheliometerHistorDay = await powerStationRepository.CalcPyrheliometerHistoryDayDataByPowerStationId(dateNowDay, powerStation.Id);
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}的日照計所有值的平均】", powerStation.Code, dateNowDay);
if (pyrheliometerHistorDay != null)
{
pyrheliometerHistoryDays.Add(pyrheliometerHistorDay);
}
//逆變器
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}的逆變器所有值的平均】", powerStation.Code, dateNowDay);
var inverterHistoriesDay = await powerStationRepository.CalcInverterHistoryDayDataByPowerStationId(dateNowDay, powerStation.SiteDB, powerStation.Id);
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}的逆變器所有值的平均】", powerStation.Code, dateNowDay);
if (inverterHistoriesDay != null)
{
foreach(var inverterHistoryDay in inverterHistoriesDay)
{
allofInverterHistorDays.Add(inverterHistoryDay);
}
}
#endregion
#region step2-4.
//判斷這個月是否已存在
var dateNowMonth = DateTimeNow.ToString("yyyy-MM");
//電站該月份的歷史資料
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}月份的歷史資料總和】", powerStation.Code, dateNowMonth);
var exist_history = await powerStationRepository.GetOnePowerStationHistoryByPowerStationIdAndMonth(powerStation.Id, dateNowMonth);
if (exist_history == null)
{ //新增
var historyMonth = await powerStationRepository.ClacPowerStationHistoryMonthDataByPowerStationId(powerStation.Id, dateNowMonth);
var moneyandcarbonMon = await powerStationRepository.GetMoneyAndCarbonWithHistoryHour(powerStation.Id, dateNowMonth, 0);
var lastmoneyhistorymonth = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 2, "");
if (historyMonth != null)
{
historyMonth.Timestamp = Convert.ToDateTime(historyMonth.Timestamp).ToString("yyyy-MM-dd");
historyMonth.MONEY = moneyandcarbonMon.MONEY;
historyMonth.CARBON = moneyandcarbonMon.CARBON;
historyMonth.TOTALCARBON = lastmoneyhistorymonth.TOTALCARBON + moneyandcarbonMon.CARBON;
historyMonth.TOTALMONEY = lastmoneyhistorymonth.TOTALMONEY + moneyandcarbonMon.MONEY;
insertPowerStationHistoryMonths.Add(historyMonth);
}
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}月份的歷史資料總和】", powerStation.Code, dateNowMonth);
}
else
{ //修改
var historyMonth = await powerStationRepository.ClacPowerStationHistoryMonthDataByPowerStationId(powerStation.Id, dateNowMonth);
var moneyandcarbonMon = await powerStationRepository.GetMoneyAndCarbonWithHistoryHour(powerStation.Id, dateNowMonth, 0);
var lastmoneyhistorymonth = await powerStationRepository.GetLastMoneyAndCarbonInHour(powerStation.Id, 2, "");
if (historyMonth != null)
{
historyMonth.MONEY = historyMonth.MONEY + moneyandcarbonMon.MONEY;
historyMonth.CARBON = historyMonth.CARBON + moneyandcarbonMon.CARBON;
historyMonth.TOTALCARBON = lastmoneyhistorymonth.TOTALCARBON + moneyandcarbonMon.CARBON;
historyMonth.TOTALMONEY = lastmoneyhistorymonth.TOTALMONEY + moneyandcarbonMon.MONEY;
updatePowerStationHistoryMonths.Add(historyMonth);
}
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}月份的歷史資料總和】", powerStation.Code, dateNowMonth);
}
//電站該月份的的日照度歷史資料
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}月份的日照度歷史資料】", powerStation.Code, dateNowMonth);
var exist_pyrheliometer_history = await powerStationRepository.GetOnePyrheliometerHistoryByMonth(dateNowMonth, powerStation.Id);
if (exist_pyrheliometer_history == null)
{ //新增
var pyrheliometerHistoryMonth = await powerStationRepository.CalcPyrheliometerHistoryMonthDataByPowerStationId(dateNowMonth, powerStation.Id);
if (pyrheliometerHistoryMonth != null)
{
pyrheliometerHistoryMonth.Timestamp = Convert.ToDateTime(pyrheliometerHistoryMonth.Timestamp).ToString("yyyy-MM-dd");
insertPyrheliometerHistoryMonths.Add(pyrheliometerHistoryMonth);
}
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}月份的日照度歷史資料】", powerStation.Code, dateNowMonth);
}
else
{ //修改
var pyrheliometerHistoryMonth = await powerStationRepository.CalcPyrheliometerHistoryMonthDataByPowerStationId(dateNowMonth, powerStation.Id);
if (pyrheliometerHistoryMonth != null)
{
updatePyrheliometerHistoryMonths.Add(pyrheliometerHistoryMonth);
}
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}月份的日照度歷史資料】", powerStation.Code, dateNowMonth);
}
//電站該月份的的逆變器歷史資料
logger.LogInformation("【CalcAvgPowerStationJob】【開始計算電站[{0}]在{1}月份的逆變器歷史資料】", powerStation.Code, dateNowMonth);
var exist_inverter_histories = await powerStationRepository.GetInverterHistoryByPowerStationIdAndMonth(dateNowMonth, powerStation.Id);
if (exist_inverter_histories.Count == 0 )
{ //新增
var inverterHistoriesMonth = await powerStationRepository.CalcInverterHistoryMonthDataByPowerStationId(dateNowMonth, powerStation.SiteDB, powerStation.Id);
if (inverterHistoriesMonth.Count > 0)
{
foreach(var inverterHistoryMonth in inverterHistoriesMonth)
{
inverterHistoryMonth.TIMESTAMP = Convert.ToDateTime(inverterHistoryMonth.TIMESTAMP).ToString("yyyy-MM-dd");
insertInverterHistoryMonths.Add(inverterHistoryMonth);
}
}
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}月份的逆變器歷史資料】", powerStation.Code, dateNowMonth);
}
else
{ //修改
var inverterHistoriesMonth = await powerStationRepository.CalcInverterHistoryMonthDataByPowerStationId(dateNowMonth, powerStation.SiteDB, powerStation.Id);
if (inverterHistoriesMonth.Count > 0)
{
foreach (var inverterHistoryMonth in inverterHistoriesMonth)
{
inverterHistoryMonth.TIMESTAMP = Convert.ToDateTime(inverterHistoryMonth.TIMESTAMP).ToString("yyyy-MM-dd");
updateInverterHistoryMonths.Add(inverterHistoryMonth);
}
}
logger.LogInformation("【CalcAvgPowerStationJob】【計算完成電站[{0}]在{1}月份的逆變器歷史資料】", powerStation.Code, dateNowMonth);
}
#endregion
count++;
}
#endregion
#region step3. calcPowerStations UPDATE power_station
List<string> power_station_properties = new List<string>()
{
"Id",
"avg_kwhkwp",
"avg_PR",
"avg_irradiance"
};
await powerStationRepository.UpdateList(calcAvgPowerStations, power_station_properties);
#endregion
#region step4. insert or update
//每日
List<string> history_properties_day = new List<string>()
{
"PowerStationId",
"TIMESTAMP",
"SITEID",
"SITETYPE",
"TODAYKWH",
"TOTALKWH",
"KWHKWP",
"PR",
"MP",
"SolarHour",
"MONEY",
"CARBON",
"TOTALMONEY",
"TOTALCARBON"
};
await powerStationRepository.AddPowerStationHistoryDayList(powerStationHistoryDays, history_properties_day);
//每月
List<string> history_properties_month = new List<string>()
{
"PowerStationId",
"TIMESTAMP",
"SITEID",
"SITETYPE",
"MonthKWh",
"TOTALKWH",
"KWHKWP",
"PR",
"MP",
"SolarHour",
"MONEY",
"CARBON",
"TOTALMONEY",
"TOTALCARBON"
};
if (insertPowerStationHistoryMonths.Count > 0)
{
await powerStationRepository.AddPowerStationHistoryMonthList(insertPowerStationHistoryMonths, history_properties_month);
}
if (updatePowerStationHistoryMonths.Count > 0)
{
await powerStationRepository.UpdatePowerStationHistoryMonthList(updatePowerStationHistoryMonths);
}
#endregion
#region step5. insert or update
List<string> pyrheliometer_history_properties = new List<string>()
{
"PowerStationId",
"Timestamp",
"Irradiance",
"Temperature"
};
//每日
await powerStationRepository.AddPyrheliometerHistoryDayList(pyrheliometerHistoryDays, pyrheliometer_history_properties);
//每月
if (insertPyrheliometerHistoryMonths.Count > 0)
{
await powerStationRepository.AddPyrheliometerHistoryMonthList(insertPyrheliometerHistoryMonths, pyrheliometer_history_properties);
}
if (updatePyrheliometerHistoryMonths.Count > 0)
{
await powerStationRepository.UpdatePyrheliometerHistoryMonthList(updatePyrheliometerHistoryMonths);
}
#endregion
#region step6. insert or update
List<string> inverter_history_properties = new List<string>()
{
"PowerStationId",
"TIMESTAMP",
"INVERTERID",
"KWH",
"TODAYKWH",
"KWHKWP",
};
//每日
await powerStationRepository.AddInverterHistoryDayList(allofInverterHistorDays, inverter_history_properties);
//每月
if (insertInverterHistoryMonths.Count > 0)
{
await powerStationRepository.AddInverterHistoryMonthList(insertInverterHistoryMonths, inverter_history_properties);
}
if (updateInverterHistoryMonths.Count > 0)
{
await powerStationRepository.UpdateInverterHistoryMonthList(updateInverterHistoryMonths);
}
#endregion
}
catch (Exception exception)
{
logger.LogError("【{0}】{1}", "CalcAvgPowerStationJob", exception.Message);
}
}
}
}