[BGService]天氣相關撈取邏輯修正

This commit is contained in:
張家睿 2024-08-06 13:31:59 +08:00
parent 9142748afc
commit 9f957b06b4
4 changed files with 424 additions and 196 deletions

View File

@ -19,6 +19,7 @@ using NCrontab;
using BackendWorkerService.Services.Implement;
using RainApi;
using System.Globalization;
using System.Text.RegularExpressions;
namespace BackendWorkerService.Quartz.Jobs
{
@ -103,7 +104,7 @@ namespace BackendWorkerService.Quartz.Jobs
try
{
await task_Detail.InsertWorkTime("WeatherAPI", "ClearWeatherData", null, new DateTime(DateTime.Now.AddDays(1).Year, DateTime.Now.AddDays(1).Month, DateTime.Now.AddDays(1).Day, 0, 0, 0));
await ClearWeatherDataBef30();
await ClearData("api_weateher", 1);
await task_Detail.InsertWorkTime_End("WeatherAPI", "ClearWeatherData");
}
catch (Exception ex)
@ -212,80 +213,140 @@ namespace BackendWorkerService.Quartz.Jobs
{
//await task_Detail.InsertWorkTime("WeatherAPI", "api_rain", null, new DateTime(DateTime.Now.AddDays(1).Year, DateTime.Now.AddDays(1).Month, DateTime.Now.AddDays(1).Day, 0, 25, 0));
await task_Detail.InsertWorkTime("WeatherAPI", "api_rain");
await ClearData("api_rain", 3);
WebClient mywebClient = new WebClient();
mywebClient.DownloadFile("https://opendata.cwa.gov.tw/fileapi/v1/opendataapi/W-C0033-003?Authorization=CWB-EA24220B-DDCC-4188-84E5-AD37A0E03F80&downloadType=WEB&format=CAP", @"root/PowerfulRain.xml");
XmlDocument doc = new XmlDocument();
doc.Load("root/PowerfulRain.xml");
var json = JsonConvert.SerializeXmlNode(doc);
var haveinfo = json.Split("info");
if (haveinfo.Length > 2)
{
var observation = JsonConvert.DeserializeObject<RainApi.Welcome>(json);
var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
var sql = $"select id from api_rain where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
Dictionary<string, object> RainAPIdb = new Dictionary<string, object>()
var observation = JsonConvert.DeserializeObject<RainApi.Welcome>(json);
var taipeiInfo = observation.Alert.Info
.Where(info => info.Area
.Any(area => area.AreaDesc == "臺北市" || area.AreaDesc == "臺北市信義區"))
//.Any(area => area.Geocode.Value == "63" || area.Geocode.Value == "6300200"))
.FirstOrDefault();
var result = "";
if (taipeiInfo != null)
{
var sql = $"select id from api_rain where msgType = '{observation.Alert.MsgType}' and onset = '{taipeiInfo.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{taipeiInfo.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
if (NeedCallApi == 0)
{
var area = taipeiInfo.Area.Where(a => a.AreaDesc == "臺北市" || a.AreaDesc == "臺北市信義區").Select(x => x.AreaDesc).FirstOrDefault();
var severity_level = taipeiInfo.Parameter
.Where(x => x.ValueName == "severity_level")
.Select(x => x.Value)
.FirstOrDefault();
Dictionary<string, object> RainAPIdb = new Dictionary<string, object>()
{
{ "@msgType", observation.Alert.MsgType},
{ "@headline", observation.Alert.Info.Headline},
{ "@headline", taipeiInfo.Headline},
{ "@severity_level", severity_level },
{ "@areaDesc", area},
{ "@onset", observation.Alert.Info.Onset},
{ "@expires", observation.Alert.Info.Expires},
{ "@onset", taipeiInfo.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@expires", taipeiInfo.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
var id = await backendRepository.AddOneByCustomTableReturnId(RainAPIdb, "api_rain");
if (NeedCallApi != 0)
{
var val = RainValue(observation.Alert.MsgType, observation.Alert.Info.Headline);
var id = await backendRepository.AddOneByCustomTableReturnId(RainAPIdb, "api_rain");
var val = RainValue(severity_level, taipeiInfo.Headline);
if (val < 5)
{
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/SeverityLEVL_RAIN/set", val.ToString());
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/ALMLEVL_RAIN/set", val.ToString());
UpdatedNiagara("api_rain", ReStr, id);
logger.LogInformation($"set niagara rain value success");
result = ReStr.Contains("err") ? "fail" : "success";
logger.LogInformation($"set niagara rain value {result}");
}
}
FolderFunction folderFunction = new FolderFunction();
folderFunction.DeleteFile("root/PowerfulRain.xml");
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_rain");
}
else
{
var observation = JsonConvert.DeserializeObject<RainApi.Welcome>(json);
var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
var sql = $"select id from api_rain where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
Dictionary<string, object> RainAPIdb = new Dictionary<string, object>()
{
{ "@msgType", observation.Alert.MsgType},
{ "@headline", observation.Alert.Info.Headline},
{ "@areaDesc", area},
{ "@onset", observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@expires", observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
var id = await backendRepository.AddOneByCustomTableReturnId(RainAPIdb, "api_rain");
if (NeedCallApi != 0)
{
var val = RainValue(observation.Alert.MsgType, observation.Alert.Info.Headline);
if (val < 5)
{
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/SeverityLEVL_RAIN/set", val.ToString());
UpdatedNiagara("api_rain", ReStr, id);
logger.LogInformation($"set niagara rain value success");
}
}
FolderFunction folderFunction = new FolderFunction();
folderFunction.DeleteFile("root/PowerfulRain.xml");
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_rain");
// 目前看起來只有全縣市都無警報才會有解除警報的資訊故若警報中途更新後沒臺北了則應視為解除table裡的紀錄只留發生跟解除的紀錄
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/ALMLEVL_RAIN/set", "0");
result = ReStr.Contains("err") ? "fail" : "success";
logger.LogInformation($"set niagara rain value {result}");
}
FolderFunction folderFunction = new FolderFunction();
folderFunction.DeleteFile(@"root/PowerfulRain.xml");
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_rain");
//var haveinfo = json.Split("info");
//var sql = $"select id from api_rain where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
//if (haveinfo.Length > 2)
//{
// var observation = JsonConvert.DeserializeObject<RainApi.Welcome>(json);
// var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
// var sql = $"select id from api_rain where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
// var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
// Dictionary<string, object> RainAPIdb = new Dictionary<string, object>()
// {
// { "@msgType", observation.Alert.MsgType},
// { "@headline", observation.Alert.Info.Headline},
// { "@areaDesc", area},
// { "@onset", observation.Alert.Info.Onset},
// { "@expires", observation.Alert.Info.Expires},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// var id = await backendRepository.AddOneByCustomTableReturnId(RainAPIdb, "api_rain");
// if (NeedCallApi != 0)
// {
// var val = RainValue(observation.Alert.MsgType, observation.Alert.Info.Headline);
// if (val < 5)
// {
// var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/SeverityLEVL_RAIN/set", val.ToString());
// UpdatedNiagara("api_rain", ReStr, id);
// logger.LogInformation($"set niagara rain value success");
// }
// }
// FolderFunction folderFunction = new FolderFunction();
// folderFunction.DeleteFile("root/PowerfulRain.xml");
// await task_Detail.InsertWorkTime_End("WeatherAPI", "api_rain");
//}
//else
//{
// var observation = JsonConvert.DeserializeObject<RainApi.Welcome>(json);
// var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
// var sql = $"select id from api_rain where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
// var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
// Dictionary<string, object> RainAPIdb = new Dictionary<string, object>()
// {
// { "@msgType", observation.Alert.MsgType},
// { "@headline", observation.Alert.Info.Headline},
// { "@areaDesc", area},
// { "@onset", observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
// { "@expires", observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// var id = await backendRepository.AddOneByCustomTableReturnId(RainAPIdb, "api_rain");
// if (NeedCallApi != 0)
// {
// var val = RainValue(observation.Alert.MsgType, observation.Alert.Info.Headline);
// if (val < 5)
// {
// var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET1/SeverityLEVL_RAIN/set", val.ToString());
// UpdatedNiagara("api_rain", ReStr, id);
// logger.LogInformation($"set niagara rain value success");
// }
// }
// FolderFunction folderFunction = new FolderFunction();
// folderFunction.DeleteFile("root/PowerfulRain.xml");
// await task_Detail.InsertWorkTime_End("WeatherAPI", "api_rain");
//}
}
catch (Exception ex)
{
@ -300,83 +361,133 @@ namespace BackendWorkerService.Quartz.Jobs
{
//await task_Detail.InsertWorkTime("WeatherAPI", "api_typhoon", null, new DateTime(DateTime.Now.AddDays(1).Year, DateTime.Now.AddDays(1).Month, DateTime.Now.AddDays(1).Day, 0, 25, 0));
await task_Detail.InsertWorkTime("WeatherAPI", "api_typhoon");
await ClearData("api_typhoon", 3);
WebClient mywebClient = new WebClient();
mywebClient.DownloadFile("https://opendata.cwa.gov.tw/fileapi/v1/opendataapi/W-C0034-001?Authorization=CWB-EA24220B-DDCC-4188-84E5-AD37A0E03F80&downloadType=WEB&format=CAP", @"root/Typhoon.xml");
XmlDocument doc = new XmlDocument();
doc.Load("root/Typhoon.xml");
doc.Load(@"root/Typhoon.xml");
var json = JsonConvert.SerializeXmlNode(doc);
var observation = JsonConvert.DeserializeObject<TyphoonApi.Welcome>(json);
var taipeiInfo = observation.Alert.Info
.Where(info => info.Area
.Any(area => area.AreaDesc == "臺北市"))
.FirstOrDefault();
var result = "";
var haveinfo = json.Split("info");
if (haveinfo.Length > 2)
if (taipeiInfo != null)
{
var observation = JsonConvert.DeserializeObject<TyphoonApi.Welcome>(json);
var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
var sql = $"select id from api_typhoon where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
var sql = $"select id from api_typhoon where msgType = '{observation.Alert.MsgType}' and onset = '{taipeiInfo.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{taipeiInfo.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
if (NeedCallApi == 0)
{
var area = taipeiInfo.Area.Where(a => a.AreaDesc == "臺北市").Select(x => x.AreaDesc).FirstOrDefault();
Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
{
{ "@msgType", observation.Alert.MsgType},
{ "@headline", observation.Alert.Info.Headline},
{ "@headline", taipeiInfo.Headline},
{ "@areaDesc", area},
{ "@urgency",observation.Alert.Info.Urgency},
{ "@severity",observation.Alert.Info.Severity},
{ "@onset", observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@expires", observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@urgency",taipeiInfo.Urgency},
{ "@severity",taipeiInfo.Severity},
{ "@onset", taipeiInfo.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@expires", taipeiInfo.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
var id = await backendRepository.AddOneByCustomTableReturnId(EarthquakeAPIdb, "api_typhoon");
if (NeedCallApi != 0)
{
if (observation.Alert.Info.Urgency != null && observation.Alert.Info.Urgency != "Expected")
var id = await backendRepository.AddOneByCustomTableReturnId(EarthquakeAPIdb, "api_typhoon");
if (taipeiInfo.Urgency != null && taipeiInfo.Urgency != "Expected")
{
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET2/SeverityLEVL_Typhoon/set", observation.Alert.Info.Urgency);
var val = taipeiInfo.Urgency;
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET2/ALMLEVL_Typhoon/set", val);
UpdatedNiagara("api_typhoon", ReStr, id);
logger.LogInformation($"set niagara typhoon value success");
result = ReStr.Contains("err") ? "fail" : "success";
logger.LogInformation($"set niagara typhoon value {result}");
}
}
FolderFunction folderFunction = new FolderFunction();
folderFunction.DeleteFile("root/Typhoon.xml");
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_typhoon");
}
else
{
var observation = JsonConvert.DeserializeObject<TyphoonApi.Welcome>(json);
var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
var sql = $"select id from api_typhoon where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
{
{ "@msgType", observation.Alert.MsgType},
{ "@headline", observation.Alert.Info.Headline},
{ "@areaDesc", area},
{ "@urgency",observation.Alert.Info.Urgency},
{ "@severity",observation.Alert.Info.Severity},
{ "@onset", observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@expires", observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
var id = await backendRepository.AddOneByCustomTableReturnId(EarthquakeAPIdb, "api_typhoon");
if (NeedCallApi != 0)
{
if (observation.Alert.Info.Urgency != null && observation.Alert.Info.Urgency != "Expected")
{
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET2/SeverityLEVL_Typhoon/set", observation.Alert.Info.Urgency);
UpdatedNiagara("api_typhoon", ReStr, id);
logger.LogInformation($"set niagara typhoon value success");
}
}
FolderFunction folderFunction = new FolderFunction();
folderFunction.DeleteFile("root/Typhoon.xml");
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_typhoon");
// 目前看起來只有全縣市都無警報才會有解除警報的資訊故若警報中途更新後沒臺北了則應視為解除table裡的紀錄只留發生跟解除的紀錄
var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET2/ALMLEVL_Typhoon/set", "Past");
result = ReStr.Contains("err") ? "fail" : "success";
logger.LogInformation($"set niagara typhoon value {result}");
}
FolderFunction folderFunction = new FolderFunction();
folderFunction.DeleteFile(@"root/Typhoon.xml");
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_typhoon");
//var haveinfo = json.Split("info");
//if (haveinfo.Length > 2)
//{
// var observation = JsonConvert.DeserializeObject<TyphoonApi.Welcome>(json);
// var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
// var sql = $"select id from api_typhoon where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
// var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
// Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
// {
// { "@msgType", observation.Alert.MsgType},
// { "@headline", observation.Alert.Info.Headline},
// { "@areaDesc", area},
// { "@urgency",observation.Alert.Info.Urgency},
// { "@severity",observation.Alert.Info.Severity},
// { "@onset", observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
// { "@expires", observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// var id = await backendRepository.AddOneByCustomTableReturnId(EarthquakeAPIdb, "api_typhoon");
// if (NeedCallApi != 0)
// {
// if (observation.Alert.Info.Urgency != null && observation.Alert.Info.Urgency != "Expected")
// {
// var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET2/ALMLEVL_Typhoon/set", observation.Alert.Info.Urgency);
// UpdatedNiagara("api_typhoon", ReStr, id);
// logger.LogInformation($"set niagara typhoon value success");
// }
// }
// FolderFunction folderFunction = new FolderFunction();
// folderFunction.DeleteFile("root/Typhoon.xml");
// await task_Detail.InsertWorkTime_End("WeatherAPI", "api_typhoon");
//}
//else
//{
// var observation = JsonConvert.DeserializeObject<TyphoonApi.Welcome>(json);
// var area = observation.Alert.Info.Area.Where(a => a.Geocode.Value == "63").Select(a => a.AreaDesc).FirstOrDefault();
// var sql = $"select id from api_typhoon where msgType = '{observation.Alert.MsgType}' and onset = '{observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")}' and expires = '{observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")}'";
// var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
// Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
// {
// { "@msgType", observation.Alert.MsgType},
// { "@headline", observation.Alert.Info.Headline},
// { "@areaDesc", area},
// { "@urgency",observation.Alert.Info.Urgency},
// { "@severity",observation.Alert.Info.Severity},
// { "@onset", observation.Alert.Info.Onset.ToString("yyyy-MM-dd HH:mm:ss")},
// { "@expires", observation.Alert.Info.Expires.ToString("yyyy-MM-dd HH:mm:ss")},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// var id = await backendRepository.AddOneByCustomTableReturnId(EarthquakeAPIdb, "api_typhoon");
// if (NeedCallApi != 0)
// {
// if (observation.Alert.Info.Urgency != null && observation.Alert.Info.Urgency != "Expected")
// {
// var ReStr = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_MET2/ALMLEVL_Typhoon/set", observation.Alert.Info.Urgency);
// UpdatedNiagara("api_typhoon", ReStr, id);
// logger.LogInformation($"set niagara typhoon value success");
// }
// }
// FolderFunction folderFunction = new FolderFunction();
// folderFunction.DeleteFile("root/Typhoon.xml");
// await task_Detail.InsertWorkTime_End("WeatherAPI", "api_typhoon");
//}
}
catch (Exception ex)
{
@ -389,11 +500,14 @@ namespace BackendWorkerService.Quartz.Jobs
try
{
await task_Detail.InsertWorkTime("WeatherAPI", "api_earthquake");
await ClearData("api_earthquake", 3);
var client = new HttpClient();
var UVUri = "https://opendata.cwa.gov.tw/api/v1/rest/datastore/E-A0015-001?Authorization=CWB-EA24220B-DDCC-4188-84E5-AD37A0E03F80&format=JSON&areaName=%E8%87%BA%E5%8C%97%E5%B8%82";
HttpResponseMessage response = client.GetAsync(UVUri).Result;
String jsonUVs = response.Content.ReadAsStringAsync().Result.ToString();
var j = JsonConvert.DeserializeObject(jsonUVs);
var result = "";
var observation = JsonConvert.DeserializeObject<QuickType.Welcome>(jsonUVs);
if (!observation.Success)
{
@ -403,89 +517,138 @@ namespace BackendWorkerService.Quartz.Jobs
{
logger.LogInformation("【WeatherAPIJob】【開始存入地震觀測到資料庫】");
List<Dictionary<string, object>> EarthquakeAPIdbS = new List<Dictionary<string, object>>();
var nowNo = await backendRepository.GetOneAsync<int>("select if( Max(earthquakeNo) is null ,0,Max(earthquakeNo)) earthquakeNo from api_earthquake where newEarthquake = 1");
foreach (var a in observation.Records.Earthquake)
var maxEarthquakeNo = observation.Records.Earthquake.Max(eq => eq.EarthquakeNo);
var eq = observation.Records.Earthquake.Where(eq => eq.EarthquakeNo == maxEarthquakeNo).FirstOrDefault();
var exist = eq.Intensity.ShakingArea.Where(area => area.CountyName == "臺北市").FirstOrDefault();
if (exist != null)
{
if (a.EarthquakeNo <= nowNo)
var sql = $"select id from api_earthquake where earthquakeNo = {eq.EarthquakeNo}";
var NeedCallApi = await backendRepository.GetOneAsync<int>(sql);
if (NeedCallApi == 0)
{
Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
{
{ "@earthquakeNo", a.EarthquakeNo},
{ "@newEarthquake", 0},
{ "@originTime", DateTime.Parse(a.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
{ "@magnitudeValue", a.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
{ "@areaName", null},
{ "@areaIntensity", null},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
EarthquakeAPIdbS.Add(EarthquakeAPIdb);
break;
}
else
{
if (a.Intensity.ShakingArea.Count > 0)
{
Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
{
{ "@earthquakeNo", a.EarthquakeNo},
{ "@earthquakeNo", eq.EarthquakeNo},
{ "@newEarthquake", 1},
{ "@originTime", DateTime.Parse(a.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
{ "@magnitudeValue", a.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
{ "@areaName", a.Intensity.ShakingArea[0].CountyName},
{ "@areaIntensity", a.Intensity.ShakingArea[0].AreaIntensity},
{ "@originTime", DateTime.Parse(eq.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
{ "@magnitudeValue", eq.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
{ "@areaName", exist.CountyName},
{ "@areaIntensity", exist.AreaIntensity},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
var Nag = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_GEO/SeverityLEVL_LMI/set", a.Intensity.ShakingArea[0].AreaIntensity.ToString());
var Nag = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_GEO/ALMLEVL_LMI/set", Regex.Match(exist.AreaIntensity, @"\d+").ToString());
if (Nag.Contains("err"))
{
EarthquakeAPIdb.Add("@niagara", Nag);
logger.LogInformation($"set niagara earthquake value fail: {Nag}");
}
else
{
EarthquakeAPIdb.Add("@niagara", "success");
logger.LogInformation($"set niagara earthquake value success");
}
EarthquakeAPIdbS.Add(EarthquakeAPIdb);
if (Nag.Contains("err"))
{
EarthquakeAPIdb.Add("@niagara", Nag);
logger.LogInformation($"set niagara earthquake value fail: {Nag}");
}
else
{
Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
{
{ "@earthquakeNo", a.EarthquakeNo},
{ "@newEarthquake", 1},
{ "@originTime", DateTime.Parse(a.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
{ "@magnitudeValue", a.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
{ "@areaName", null},
{ "@areaIntensity", null},
{ "@created_by", "system"},
{ "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
};
var Nag = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_GEO/SeverityLEVL_LMI/set", "NULL");
if (Nag.Contains("err"))
{
EarthquakeAPIdb.Add("@niagara", Nag);
logger.LogInformation($"set niagara earthquake value fail: {Nag}");
}
else
{
EarthquakeAPIdb.Add("@niagara", "success");
logger.LogInformation($"set niagara earthquake value success");
}
EarthquakeAPIdbS.Add(EarthquakeAPIdb);
EarthquakeAPIdb.Add("@niagara", "success");
logger.LogInformation($"set niagara earthquake value success");
}
EarthquakeAPIdbS.Add(EarthquakeAPIdb);
}
}
else
{
var Nag = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_GEO/ALMLEVL_LMI/set", "0");
result = Nag.Contains("err") ? "fail" : "success";
logger.LogInformation($"set niagara earthquake value {result}");
}
//var nowNo = await backendRepository.GetOneAsync<int>("select if( Max(earthquakeNo) is null ,0,Max(earthquakeNo)) earthquakeNo from api_earthquake where newEarthquake = 1");
//foreach (var a in observation.Records.Earthquake)
//{
// if (a.EarthquakeNo <= nowNo)
// {
// Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
// {
// { "@earthquakeNo", a.EarthquakeNo},
// { "@newEarthquake", 0},
// { "@originTime", DateTime.Parse(a.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
// { "@magnitudeValue", a.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
// { "@areaName", null},
// { "@areaIntensity", null},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// EarthquakeAPIdbS.Add(EarthquakeAPIdb);
// break;
// }
// else
// {
// if (a.Intensity.ShakingArea.Count > 0)
// {
// Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
// {
// { "@earthquakeNo", a.EarthquakeNo},
// { "@newEarthquake", 1},
// { "@originTime", DateTime.Parse(a.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
// { "@magnitudeValue", a.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
// { "@areaName", a.Intensity.ShakingArea[0].CountyName},
// { "@areaIntensity", a.Intensity.ShakingArea[0].AreaIntensity},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// var Nag = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_GEO/ALMLEVL_LMI/set", a.Intensity.ShakingArea[0].AreaIntensity.ToString());
// if (Nag.Contains("err"))
// {
// EarthquakeAPIdb.Add("@niagara", Nag);
// logger.LogInformation($"set niagara earthquake value fail: {Nag}");
// }
// else
// {
// EarthquakeAPIdb.Add("@niagara", "success");
// logger.LogInformation($"set niagara earthquake value success");
// }
// EarthquakeAPIdbS.Add(EarthquakeAPIdb);
// }
// else
// {
// Dictionary<string, object> EarthquakeAPIdb = new Dictionary<string, object>()
// {
// { "@earthquakeNo", a.EarthquakeNo},
// { "@newEarthquake", 1},
// { "@originTime", DateTime.Parse(a.EarthquakeInfo.OriginTime.ToString(), System.Globalization.CultureInfo.CurrentCulture)},
// { "@magnitudeValue", a.EarthquakeInfo.EarthquakeMagnitude.MagnitudeValue},
// { "@areaName", null},
// { "@areaIntensity", null},
// { "@created_by", "system"},
// { "@created_at", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")},
// };
// var Nag = Fetch_PostWithJSONFormat($@"{obixApiConfig.ApiBase}obix/config/Arena/D2/CWB/L110/CAP/D2_CWB_L110_CAP_GEO/ALMLEVL_LMI/set", "NULL");
// if (Nag.Contains("err"))
// {
// EarthquakeAPIdb.Add("@niagara", Nag);
// logger.LogInformation($"set niagara earthquake value fail: {Nag}");
// }
// else
// {
// EarthquakeAPIdb.Add("@niagara", "success");
// logger.LogInformation($"set niagara earthquake value success");
// }
// EarthquakeAPIdbS.Add(EarthquakeAPIdb);
// }
// }
//}
EarthquakeAPIdbS.Reverse();
await backendRepository.AddMutiByCustomTable(EarthquakeAPIdbS, "api_earthquake");
if (EarthquakeAPIdbS.Count != 0)
{
await backendRepository.AddMutiByCustomTable(EarthquakeAPIdbS, "api_earthquake");
}
}
await task_Detail.InsertWorkTime_End("WeatherAPI", "api_earthquake");
}
@ -540,31 +703,30 @@ namespace BackendWorkerService.Quartz.Jobs
}
}
public int RainValue(string Ty, string Headline)
public int RainValue(string severity_level, string Headline)
{
var rint = 5;
if (Ty == "")
if (severity_level == null)
{
return 0;
}
else
{
if (Headline.Contains("解除"))
rint = 0;
else if (Headline.Contains("大雨"))
else if (severity_level.Contains("大雨"))
{
rint = 1;
}
else if (Headline.Contains("豪雨"))
else if (severity_level.Contains("豪雨"))
{
rint = 2;
}
else if (Headline.Contains("大豪雨"))
else if (severity_level.Contains("大豪雨"))
{
rint = 3;
}
else if (Headline.Contains("超大豪雨"))
else if (severity_level.Contains("超大豪雨"))
{
rint = 4;
}
@ -595,16 +757,16 @@ namespace BackendWorkerService.Quartz.Jobs
}
}
public async Task ClearWeatherDataBef30()
public async Task ClearData(string tableName, int monthNumber)
{
try
{
string sql = $"delete from api_weateher WHERE created_at < DATE_SUB(NOW(), INTERVAL 1 MONTH)";
string sql = $@"delete from {tableName} WHERE created_at < DATE_SUB(NOW(), INTERVAL {monthNumber} MONTH)";
await backgroundServiceRepository.ExecuteSql(sql);
}
catch (Exception e)
{
logger.LogError("[ClearWether] clear wether data error");
logger.LogError($"[ClearData] clear {tableName} data error");
throw e;
}
}

View File

@ -18,6 +18,7 @@ namespace RainApi
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
public partial class Welcome
{
@ -35,7 +36,10 @@ namespace RainApi
public string MsgType { get; set; }
public string Scope { get; set; }
public string References { get; set; }
public Info Info { get; set; }
//此標籤為將資料統一轉成陣列,因氣象局資料會根據狀況傳回單個物件或陣列,會導致解析失敗
[JsonConverter(typeof(SingleOrArrayConverter<Info>))]
public List<Info> Info { get; set; }
}
public partial class Info
@ -55,7 +59,10 @@ namespace RainApi
public string Description { get; set; }
public string Instruction { get; set; }
public Uri Web { get; set; }
public EventCode Parameter { get; set; }
//此標籤為將資料統一轉成陣列,因氣象局資料會根據狀況傳回單個物件或陣列,會導致解析失敗
[JsonConverter(typeof(SingleOrArrayConverter<EventCode>))]
public List<EventCode> Parameter { get; set; }
public List<Area> Area { get; set; }
}
@ -78,4 +85,44 @@ namespace RainApi
}
public enum ValueName { AlertTitle, ProfileCapTwpEvent10, TaiwanGeocode103 };
//此標籤為將資料統一轉成陣列,因氣象局資料會根據狀況傳回單個物件或陣列,會導致解析失敗
public class SingleOrArrayConverter<T> : JsonConverter
{
// 判斷是否可以轉換該類型,這裡只處理 List<T> 類型
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}
// 讀取 JSON 並轉換成對應的物件
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader); // 讀取 JSON 標記
if (token.Type == JTokenType.Array) // 如果是陣列
{
return token.ToObject<List<T>>(); // 轉換成 List<T>
}
else // 如果不是陣列
{
return new List<T> { token.ToObject<T>() }; // 包裝成單一物件的 List<T>
}
}
// 將物件寫入 JSON
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var list = value as List<T>; // 將值轉換成 List<T>
if (list.Count == 1) // 如果列表中只有一個元素
{
serializer.Serialize(writer, list[0]); // 直接序列化該元素
}
else // 如果列表中有多個元素
{
serializer.Serialize(writer, list); // 序列化整個列表
}
}
}
}

View File

@ -18,6 +18,7 @@ namespace TyphoonApi
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using RainApi;
public partial class Welcome
{
@ -35,7 +36,10 @@ namespace TyphoonApi
public string MsgType { get; set; }
public string Scope { get; set; }
public string References { get; set; }
public Info Info { get; set; }
//此標籤為將資料統一轉成陣列,因氣象局資料會根據狀況傳回單個物件或陣列,會導致解析失敗
[JsonConverter(typeof(SingleOrArrayConverter<Info>))]
public List<Info> Info { get; set; }
}
public partial class Info
@ -55,7 +59,10 @@ namespace TyphoonApi
public Description Description { get; set; }
public object Instruction { get; set; }
public Uri Web { get; set; }
public EventCode Parameter { get; set; }
//此標籤為將資料統一轉成陣列,因氣象局資料會根據狀況傳回單個物件或陣列,會導致解析失敗
[JsonConverter(typeof(SingleOrArrayConverter<EventCode>))]
public List<EventCode> Parameter { get; set; }
public List<Area> Area { get; set; }
}

View File

@ -923,24 +923,32 @@
<tr>
<td colspan="2">
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq1" value="3">
<label class="form-check-label" for="inlineRadio1">3級</label>
<input class="form-check-input" type="radio" name="eqRadio" id="eq1" value="1">
<label class="form-check-label" for="eq1">1級</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq2" value="4">
<label class="form-check-label" for="eq2">4級</label>
<input class="form-check-input" type="radio" name="eqRadio" id="eq2" value="2">
<label class="form-check-label" for="eq2">2級</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq3" value="5">
<label class="form-check-label" for="eq3">5級</label>
<input class="form-check-input" type="radio" name="eqRadio" id="eq3" value="3">
<label class="form-check-label" for="eq3">3級</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq4" value="6">
<label class="form-check-label" for="eq4">6級</label>
<input class="form-check-input" type="radio" name="eqRadio" id="eq4" value="4">
<label class="form-check-label" for="eq4">4級</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq5" value="7">
<label class="form-check-label" for="eq5">7級</label>
<input class="form-check-input" type="radio" name="eqRadio" id="eq5" value="5">
<label class="form-check-label" for="eq5">5級</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq6" value="6">
<label class="form-check-label" for="eq6">6級</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="eqRadio" id="eq7" value="7">
<label class="form-check-label" for="eq7">7級</label>
</div>
</td>
</tr>
@ -1041,6 +1049,8 @@
function onEqRadioChange(e) {
let eqDecDict = {
1: "微震。",
2: "電燈等懸掛物有小搖晃。",
3: "房屋震動,碗盤門窗發出聲音,懸掛物搖擺。",
4: "房屋搖動甚烈,少數未固定物品可能傾倒掉落,少數傢俱移動,可能有輕微災害。",
5: "部分未固定物品傾倒掉落,少數傢俱可能移動或翻倒,少數門窗可能變形,部分牆壁產生裂痕。",
@ -1083,6 +1093,8 @@
$("#rainDesc").text(rainDecDict[rainValue] || "");
let eqDecDict = {
1: "微震。",
2: "電燈等懸掛物有小搖晃。",
3: "房屋震動,碗盤門窗發出聲音,懸掛物搖擺。",
4: "房屋搖動甚烈,少數未固定物品可能傾倒掉落,少數傢俱移動,可能有輕微災害。",
5: "部分未固定物品傾倒掉落,少數傢俱可能移動或翻倒,少數門窗可能變形,部分牆壁產生裂痕。",