diff --git a/BackendWorkerService/BackendWorkerService.csproj b/BackendWorkerService/BackendWorkerService.csproj
index 06a89c1..5564a43 100644
--- a/BackendWorkerService/BackendWorkerService.csproj
+++ b/BackendWorkerService/BackendWorkerService.csproj
@@ -17,6 +17,7 @@
+
diff --git a/BackendWorkerService/Program.cs b/BackendWorkerService/Program.cs
index 6fdac3c..df384df 100644
--- a/BackendWorkerService/Program.cs
+++ b/BackendWorkerService/Program.cs
@@ -19,7 +19,7 @@ using Repository.FrontendRepository.Interface;
using Repository.Helper;
using Repository.Models;
using System;
-using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Threading.Tasks;
@@ -149,11 +149,20 @@ namespace BackendWorkerService
);
#endregion
+ #region 定時檢查燈控排程
+ services.AddSingleton< LightScheduleJob>();
+ services.AddSingleton(
+ new JobSchedule(jobType: typeof(LightScheduleJob), cronExpression: configuration.GetValue("BackgroundServiceCron:LightScheduleJob "))
+ );
+ #endregion
+
}).ConfigureLogging((hostContext, logFactory) => {
IConfiguration configuration = hostContext.Configuration;
//logFactory.AddFile("Logs/log-{Date}.txt");
- logFactory.AddFile(configuration.GetValue("LoggerPath") + "/log-{Date}.txt");
+ string loggerPath = configuration.GetValue("LoggerPath");
+
+ logFactory.AddFile($"{loggerPath}/log-{{Date}}.txt");
});
}
}
diff --git a/BackendWorkerService/Quartz/JobSchedule.cs b/BackendWorkerService/Quartz/JobSchedule.cs
index 249a920..4de3e0e 100644
--- a/BackendWorkerService/Quartz/JobSchedule.cs
+++ b/BackendWorkerService/Quartz/JobSchedule.cs
@@ -64,7 +64,7 @@ namespace BackendWorkerService.Quartz
///
///
///
- private async Task GetWorkRule(string task,string task_item)
+ private async Task GetWorkRule(string task, string task_item)
{
string Times = null;
try
@@ -74,10 +74,10 @@ namespace BackendWorkerService.Quartz
where a.task = '{task}' and a.task_item = '{task_item}'";
Times = await backendRepository.GetOneAsync(sql);
}
- catch(Exception exception)
+ catch (Exception exception)
{
logger.LogError("Task_Detail隞餃脣憭望");
- logger.LogError("Task_Detail隞餃脣憭望[Exception]嚗{0},Task:{1},task_item:{2}", exception.ToString(),task,task_item);
+ logger.LogError("Task_Detail隞餃脣憭望[Exception]嚗{0},Task:{1},task_item:{2}", exception.ToString(), task, task_item);
}
return Times;
}
@@ -100,13 +100,13 @@ namespace BackendWorkerService.Quartz
DateTime dateTime = lastworkTime != null ? Convert.ToDateTime(lastworkTime) : Convert.ToDateTime("1970-01-01 00:00:01");
- var nextTime = CrontabSchedule.Parse(await GetWorkRule(task, task_item), new ParseOptions { IncludingSeconds = true } ).GetNextOccurrence(dateTime);
+ var nextTime = CrontabSchedule.Parse(await GetWorkRule(task, task_item), new ParseOptions { IncludingSeconds = true }).GetNextOccurrence(dateTime);
if (DateTime.Now >= nextTime)
{
return true;
}
}
- catch(Exception exception)
+ catch (Exception exception)
{
logger.LogError("Task_Detail閫憭望[Exception]嚗{0},Task:{1},task_item:{2}", exception.ToString(), task, task_item);
}
@@ -118,7 +118,7 @@ namespace BackendWorkerService.Quartz
///
///
///
- public async Task InsertWorkTime(string task, string task_item ,string LoggerWord = null, DateTime? dateTime = null)
+ public async Task InsertWorkTime(string task, string task_item, string LoggerWord = null, DateTime? dateTime = null)
{
try
{
@@ -130,11 +130,14 @@ namespace BackendWorkerService.Quartz
};
await backendRepository.UpdateOneByCustomTable(worktime, "task_detail", $" task = '{task}' and task_item = '{task_item}'");
- if(LoggerWord == null)
+ if (LoggerWord == null)
{
logger.LogInformation($"Task_Detail憪{task},{task_item}隞餃");
}
- logger.LogInformation($"Task_Detail{LoggerWord}");
+ else
+ {
+ logger.LogInformation($"Task_Detail{LoggerWord}");
+ }
}
catch (Exception exception)
{
@@ -147,7 +150,7 @@ namespace BackendWorkerService.Quartz
///
///
///
- public async Task InsertWorkTime_End(string task, string task_item,string LoggerWord = null)
+ public async Task InsertWorkTime_End(string task, string task_item, string LoggerWord = null)
{
try
{
@@ -162,7 +165,10 @@ namespace BackendWorkerService.Quartz
{
logger.LogInformation($"Task_Detail蝯{task},{task_item}隞餃");
}
- logger.LogInformation($"Task_Detail{LoggerWord}");
+ else
+ {
+ logger.LogInformation($"Task_Detail{LoggerWord}");
+ }
}
catch (Exception exception)
{
@@ -175,7 +181,7 @@ namespace BackendWorkerService.Quartz
///
///
///
- public async Task WorkFail(string task, string task_item,string reason = "")
+ public async Task WorkFail(string task, string task_item, string reason = "")
{
try
{
diff --git a/BackendWorkerService/Quartz/Jobs/LightScheduleJob .cs b/BackendWorkerService/Quartz/Jobs/LightScheduleJob .cs
new file mode 100644
index 0000000..6866f2b
--- /dev/null
+++ b/BackendWorkerService/Quartz/Jobs/LightScheduleJob .cs
@@ -0,0 +1,194 @@
+嚜簑sing 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;
+
+namespace BackendWorkerService.Quartz.Jobs
+{
+ [DisallowConcurrentExecution]
+ class LightScheduleJob : IJob
+ {
+ private readonly ILogger logger;
+ private readonly IBackgroundServiceRepository backgroundServiceRepository;
+ private readonly IBackendRepository backendRepository;
+ private readonly ILogger loggers;
+ public LightScheduleJob(ILogger logger,
+ IBackgroundServiceRepository backgroundServiceRepository, IBackendRepository backendRepository, ILogger 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");
+ #region
+ var TimeNow = DateTime.Now.ToString("dddd HH:mm");
+ var schedule = await backendRepository.GetAllAsync("light_schedule","deleted = 0 and status = 1");
+ string date = DateTime.Now.ToString("yyyy-MM-dd");
+
+ foreach (var oneSchedule in schedule)
+ {
+ // 瑼X亙瑁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("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 log = new Dictionary()
+ {
+ { "@light_schedule_guid", light_schedule_guid},
+ { "@date", date},
+ };
+ await backendRepository.AddOneByCustomTable(log, "light_schedule_log");
+ }
+ // 憒log蝝
+
+ var weeklistN = oneSchedule.week.Split(',');
+ List weeklist = new List();
+ 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;
+ // 瑼X亥絲憪瑁
+ if (start_time == null && DateTime.Parse(Time[1]) >= DateTime.Parse(oneSchedule.start_time))
+ {
+ check = "";
+ UpdatedNiagara(oneSchedule, check);
+ Dictionary log = new Dictionary()
+ {
+ { "@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}");
+ }
+ // 瑼X亦瑁
+ if (end_time == null && DateTime.Parse(Time[1]) >= DateTime.Parse(oneSchedule.end_time))
+ {
+ check = "";
+ UpdatedNiagara(oneSchedule, check);
+ Dictionary log = new Dictionary()
+ {
+ { "@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}");
+ }
+ }
+ #endregion
+
+ 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(@$"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("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)
+ {
+ var d = deviceNum.Split("_");
+ 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邕verride
+ if (strResponse.Contains(" Schedule = new Dictionary();
+ // 扳蝔舐撘湔迷uid(蝔寞guid瑁韏瑕蝯銝甈∴乩葉靽格寞隞嗅銝瑁嚗雿甇支耨)
+ var newguid = Guid.NewGuid();
+
Schedule = new Dictionary()
{
+ { "@light_schedule_guid",newguid},
{ "@status", saveSchedule.status},
{ "@full_name", saveSchedule.full_name},
{ "@week", saveSchedule.week},
@@ -198,7 +202,7 @@ namespace FrontendWebApi.ApiControllers
Dictionary ScheduleDevice = new Dictionary();
ScheduleDevice = new Dictionary()
{
- { "@light_schedule_guid", saveSchedule.light_schedule_guid},
+ { "@light_schedule_guid", newguid},
{ "@device_guid", a}
};
ScheduleDevices.Add(ScheduleDevice);
diff --git a/FrontendWebApi/Models/LightSchedule.cs b/FrontendWebApi/Models/LightSchedule.cs
index 674457a..c885717 100644
--- a/FrontendWebApi/Models/LightSchedule.cs
+++ b/FrontendWebApi/Models/LightSchedule.cs
@@ -30,6 +30,14 @@ namespace FrontendWebApi.Models
public string end_time { get; set; }
public byte status { get; set; }
}
+ public class ScheduleLog
+ {
+ public int light_schedule_log_id { get; set; }
+ public string light_schedule_guid { get; set; }
+ public string date { get; set; }
+ public string start_time { get; set; }
+ public string end_time { get; set; }
+ }
public class SaveSchedule : Schedule
{
public List devicelist { get; set; }