using Application.Domain.Entities; using CSScriptLib; using Hangfire; using Infrastructure.Application.Entites.Settings; using Infrastructure.Events; using Infrastructure.Extensions; using IoT.Shared.Services; using IoTNode.DeviceServices.Onvif; using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace IoTNode.Services { public class IoTNodeEventHandler : IEventHander>, IEventHander>, IEventHander>, IEventHander>, IEventHander> { private readonly ILogger _logger; private readonly ISceneTiggerService _sceneTiggerService; private readonly IoTNodeJob _job; private readonly OnvifService _onvifService; private readonly IoTNodeClient _ioTNodeClient; public IoTNodeEventHandler(ILogger logger, ISceneTiggerService sceneTiggerService, IoTNodeJob job, OnvifService onvifService, IoTNodeClient ioTNodeClient) { this._logger = logger; this._sceneTiggerService = sceneTiggerService; this._job = job; this._onvifService = onvifService; this._ioTNodeClient = ioTNodeClient; } public void Handle(EntityInsertedEvent message) { RecurringJob.AddOrUpdate(message.Data.Id.ToString(), o => o.TimerHanle(message.Data.Id), message.Data.Cron, TimeZoneInfo.Local); } public void Handle(EntityUpdatedEvent message) { RecurringJob.AddOrUpdate(message.Data.Id.ToString(), o => o.TimerHanle(message.Data.Id), message.Data.Cron, TimeZoneInfo.Local); } public void Handle(EntityDeletedEvent message) { RecurringJob.RemoveIfExists(message.Data.Id.ToString()); } public void Handle(EntityUpdatedEvent message) { this.TiggerHandle(message); } public void Handle(EntityUpdatedEvent message) { if (message.Data.Name == "stream.rtmp" || message.Data.Name == "ffmpeg.args") { Task.Delay(1000); this._onvifService.StopPushToServer(); this._onvifService.StartPushToServer(); } else if (message.Data.Name == "organ") { this._ioTNodeClient.Close(); this._ioTNodeClient.Connect(); } } private void TiggerHandle(BaseEvent message) { try { this._logger.LogInformation($"Debug>call tigger handler when data update at {DateTime.Now.ToLongDateString()} "); foreach (var tigger in this._sceneTiggerService.GetSceneTiggers()) { var data = message.Data; if (tigger.DataId == data.Id) { this._logger.LogInformation($"Debug>match tigger at {DateTime.Now.ToLongDateString()} "); var methodText = $"bool Valid(string name,string key,{data.Type.ToString().ToLower()} value,string description){{ return {tigger.Condition};}}"; try { dynamic method = CSScript.Evaluator.LoadMethod(methodText); dynamic value = data.GetValue(); var result = method.Valid(data.Name, data.Key, value, data.Description); if (result) { this._logger.LogInformation($"Debug>match contdation at {DateTime.Now.ToLongDateString()} "); this._job.TiggerHandle(tigger.Id); } } catch (Exception ex) { this._logger.LogError(ex.ToString()); } } } } catch (Exception ex) { this._logger.LogError(ex.ToString()); } } } }