2024-04-30 16:40:48 +08:00
using Backend.Models ;
using Microsoft.Extensions.Logging ;
using Newtonsoft.Json ;
using Newtonsoft.Json.Linq ;
using Quartz ;
using Repository.BackendRepository.Implement ;
using Repository.BackendRepository.Interface ;
using System ;
using System.Collections.Generic ;
using System.IO ;
using System.Net ;
using System.Net.Http ;
using System.Text ;
using System.Threading.Tasks ;
using System.Xml ;
using System.Xml.Serialization ;
using System.Linq ;
using NCrontab ;
using BackendWorkerService.Services.Implement ;
using RainApi ;
using System.Globalization ;
using FrontendWebApi.Models ;
using Repository.FrontendRepository.Interface ;
using Microsoft.Extensions.Hosting ;
using Repository.FrontendRepository.Implement ;
using iTextSharp.text ;
using NPOI.SS.Formula.Functions ;
2024-05-08 13:09:19 +08:00
using System.Text.RegularExpressions ;
using Repository.Models ;
2024-04-30 16:40:48 +08:00
namespace BackendWorkerService.Quartz.Jobs
{
[DisallowConcurrentExecution]
class LightScheduleJob : IJob
{
private readonly ILogger < LightScheduleJob > logger ;
private readonly IBackgroundServiceRepository backgroundServiceRepository ;
private readonly IBackendRepository backendRepository ;
private readonly ILogger < Task_Detail > loggers ;
public LightScheduleJob ( ILogger < LightScheduleJob > logger ,
IBackgroundServiceRepository backgroundServiceRepository , IBackendRepository backendRepository , ILogger < Task_Detail > loggers )
{
this . logger = logger ;
this . backgroundServiceRepository = backgroundServiceRepository ;
this . backendRepository = backendRepository ;
this . loggers = loggers ;
}
public async Task Execute ( IJobExecutionContext context )
{
Task_Detail task_Detail = new Task_Detail ( loggers , backendRepository ) ;
try
{
if ( await task_Detail . GetNeedWorkTask ( "LightScheduleJob" , "light_schedule" ) )
{
try
{
await task_Detail . InsertWorkTime ( "LightScheduleJob" , "light_schedule" ) ;
2024-05-08 13:09:19 +08:00
2024-04-30 16:40:48 +08:00
var TimeNow = DateTime . Now . ToString ( "dddd HH:mm" ) ;
var schedule = await backendRepository . GetAllAsync < Schedule > ( "light_schedule" , "deleted = 0 and status = 1" ) ;
string date = DateTime . Now . ToString ( "yyyy-MM-dd" ) ;
foreach ( var oneSchedule in schedule )
{
// 檢查執行log
string light_schedule_guid = oneSchedule . light_schedule_guid ;
string sWhere = @ $"light_schedule_guid = '{light_schedule_guid}' and date = '{date}'" ;
var schedule_log = await backendRepository . GetOneAsync < ScheduleLog > ( "light_schedule_log" , sWhere ) ;
string start_time = null ;
string end_time = null ;
if ( schedule_log ! = null )
{
start_time = schedule_log . start_time ;
end_time = schedule_log . end_time ;
}
if ( schedule_log = = null )
{
Dictionary < string , object > log = new Dictionary < string , object > ( )
{
{ "@light_schedule_guid" , light_schedule_guid } ,
{ "@date" , date } ,
} ;
await backendRepository . AddOneByCustomTable ( log , "light_schedule_log" ) ;
}
// 如果log有紀錄
var weeklistN = oneSchedule . week . Split ( ',' ) ;
List < string > weeklist = new List < string > ( ) ;
foreach ( var weekN in weeklistN )
{
var week = weekN switch
{
"0" = > "星期日" ,
"1" = > "星期一" ,
"2" = > "星期二" ,
"3" = > "星期三" ,
"4" = > "星期四" ,
"5" = > "星期五" ,
"6" = > "星期六" ,
_ = > ""
} ;
weeklist . Add ( week ) ;
}
var Time = TimeNow . Split ( " " ) ;
string check = string . Empty ;
// 檢查起始執行
if ( start_time = = null & & DateTime . Parse ( Time [ 1 ] ) > = DateTime . Parse ( oneSchedule . start_time ) )
{
check = "<real val='true' />" ;
UpdatedNiagara ( oneSchedule , check ) ;
Dictionary < string , object > log = new Dictionary < string , object > ( )
{
{ "@start_time" , Time [ 1 ] } ,
} ;
await backendRepository . UpdateOneByCustomTable ( log , "light_schedule_log" , $"light_schedule_guid = '{light_schedule_guid}' and date = '{date}'" ) ;
logger . LogInformation ( $"【LightScheduleJob】【燈控排程開啟成功】排程名稱 :{oneSchedule.full_name}" ) ;
}
// 檢查結束執行
if ( end_time = = null & & DateTime . Parse ( Time [ 1 ] ) > = DateTime . Parse ( oneSchedule . end_time ) )
{
check = "<real val='false' />" ;
UpdatedNiagara ( oneSchedule , check ) ;
Dictionary < string , object > log = new Dictionary < string , object > ( )
{
{ "@end_time" , Time [ 1 ] } ,
} ;
await backendRepository . UpdateOneByCustomTable ( log , "light_schedule_log" , $"light_schedule_guid = '{light_schedule_guid}' and date = '{date}'" ) ;
logger . LogInformation ( $"【LightScheduleJob】【燈控排程關閉成功】排程名稱 :{oneSchedule.full_name}" ) ;
}
}
2024-05-08 13:09:19 +08:00
2024-04-30 16:40:48 +08:00
await task_Detail . InsertWorkTime_End ( "LightScheduleJob" , "light_schedule" ) ;
}
catch ( Exception ex )
{
logger . LogInformation ( $"LightScheduleJob fail" ) ;
await task_Detail . WorkFail ( "LightScheduleJob" , "light_schedule" , ex . Message . ToString ( ) ) ;
}
}
}
catch ( Exception exception )
{
logger . LogError ( "【LightScheduleJob】【任務失敗】" ) ;
logger . LogError ( "【LightScheduleJob】【任務失敗】[Exception]: {0}" , exception . ToString ( ) ) ;
}
}
public async void UpdatedNiagara ( Schedule oneSchedule , string check )
{
try
{
var deviceNumList = await backendRepository . GetAllAsync < string > ( @ $ "select d.device_number from schedule_device sd join device d on sd.device_guid = d.device_guid
where light_schedule_guid = ' { oneSchedule . light_schedule_guid } ' and is_link = 1 ");
var variableObix = await backendRepository . GetAllAsync < Backend . Models . KeyValue > ( "SELECT system_value as Value, system_key as Name FROM variable WHERE deleted = 0 AND system_type = 'obixConfig'" ) ;
string url = variableObix . Where ( x = > x . Name = = "ApiBase" ) . Select ( x = > x . Value ) . FirstOrDefault ( ) ;
string account = variableObix . Where ( x = > x . Name = = "UserName" ) . Select ( x = > x . Value ) . FirstOrDefault ( ) ;
string pass = variableObix . Where ( x = > x . Name = = "Password" ) . Select ( x = > x . Value ) . FirstOrDefault ( ) ;
foreach ( var deviceNum in deviceNumList )
{
2024-05-08 13:09:19 +08:00
TagChangeFunction tagChange = new TagChangeFunction ( ) ;
var d = tagChange . AddStringIfStartsWithDigit ( deviceNum , "$3" ) ;
2024-04-30 16:40:48 +08:00
var html = $"{url}obix/config/Arena/" + $"{d[0]}/{d[1]}/{d[2]}/{d[3]}/{deviceNum}/SSC/set" ;
string authInfo = account + ":" + pass ;
authInfo = Convert . ToBase64String ( Encoding . Default . GetBytes ( authInfo ) ) ;
HttpWebRequest request = ( HttpWebRequest ) WebRequest . Create ( html ) ;
request . Method = "POST" ;
request . Accept = "application/json; charset=utf-8" ;
request . Headers [ "Authorization" ] = "Basic " + authInfo ;
byte [ ] byteArray = Encoding . UTF8 . GetBytes ( check ) ;
using ( Stream reqStream = request . GetRequestStream ( ) )
{
reqStream . Write ( byteArray , 0 , byteArray . Length ) ;
}
var response = ( HttpWebResponse ) request . GetResponse ( ) ;
string strResponse = "" ;
using ( var sr = new StreamReader ( response . GetResponseStream ( ) ) )
{
strResponse = sr . ReadToEnd ( ) ;
}
// 只取err會取到override
if ( strResponse . Contains ( "<err" ) )
{
logger . LogWarning ( $"【LightScheduleJob 】【set niagara light value fail】[排程 名稱]: {oneSchedule.full_name},[設備 名稱]: {deviceNum}" ) ;
}
}
}
catch ( Exception ex )
{
logger . LogError ( "【LightScheduleJob】" + "UpdatedNiagaraFail:" + ex . ToString ( ) ) ;
throw ex ;
}
}
}
}