using Application.Domain.Entities; using Hangfire; using Infrastructure.Application.Entites.Settings; using Infrastructure.Events; using IoT.Shared.Services; using IoTNode.DeviceServices.Onvif; using Jint; using Jint.Native; using Microsoft.Extensions.Logging; using System; using System.Threading.Tasks; 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 { foreach (var tigger in this._sceneTiggerService.GetSceneTiggers()) { var data = message.Data; if (tigger.DataId == data.Id) { try { var condition = tigger.Condition; var value = data.Value; var engine = new Engine().Execute($"function valid(value){{return {condition};}}"); var result = engine.Invoke("valid", value); if (result == JsValue.True) { this._job.TiggerHandle(tigger.Id); } } catch (Exception ex) { this._logger.LogError(ex.ToString()); } } } } catch (Exception ex) { this._logger.LogError(ex.ToString()); } } } }