You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/IoTNode/Services/IoTNodeEventHandler.cs

126 lines
3.6 KiB

using Application.Domain.Entities;
using Infrastructure.Application.Entites.Settings;
using Infrastructure.Events;
using Infrastructure.Extensions;
using Infrastructure.Web.SignalR;
using IoT.Shared.Application.Models;
using IoT.Shared.Services;
using IoTNode.DeviceServices.Onvif;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace IoTNode.Services
{
public class IoTNodeEventHandler :
IEventHander<EntityUpdated<Setting>>,
IEventHander<EntityInserted<IoTDevice>>,
IEventHander<EntityUpdated<IoTDevice>>,
IEventHander<EntityDeleted<IoTDevice>>,
IEventHander<EntityInserted<IoTData>>,
IEventHander<EntityUpdated<IoTData>>,
IEventHander<EntityDeleted<IoTData>>
{
private readonly ILogger<IoTNodeEventHandler> _logger;
private readonly IHubContext<BasePageHub> _hub;
private readonly OnvifService _onvifService;
private readonly IoTNodeClient _ioTNodeClient;
public IoTNodeEventHandler(ILogger<IoTNodeEventHandler> logger,
IHubContext<BasePageHub> hub,
OnvifService onvifService,
IoTNodeClient ioTNodeClient
)
{
this._logger = logger;
this._hub = hub;
this._onvifService = onvifService;
this._ioTNodeClient = ioTNodeClient;
}
public void Handle(EntityUpdated<Setting> 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 == "notify:host")
{
this._ioTNodeClient.Close();
this._ioTNodeClient.Connect();
}
else if (message.Data.Name == "code")
{
this._ioTNodeClient.Close();
this._ioTNodeClient.Connect();
}
}
public void Handle(EntityInserted<IoTDevice> message)
{
this.Notify(message);
}
public void Handle(EntityUpdated<IoTDevice> message)
{
this.Notify(message);
}
public void Handle(EntityDeleted<IoTDevice> message)
{
this.Notify(message);
}
public void Handle(EntityInserted<IoTData> message)
{
this.Upload(message);
}
public void Handle(EntityUpdated<IoTData> message)
{
this.Upload(message);
}
public void Handle(EntityDeleted<IoTData> message)
{
this.Upload(message);
}
private void Notify<T>(BaseEvent<T> message)
{
Task.Run(() =>
{
try
{
_hub.Clients.Group("page").SendAsync(Methods.ServerToClient, $"{typeof(T).Name}{message.Arg}", message.Data.ToJson(true), null, null);
}
catch (Exception ex)
{
ex.PrintStack();
}
});
}
private void Upload<T>(BaseEvent<T> message)
{
Task.Run(() =>
{
try
{
this._ioTNodeClient.ClientToServer($"{typeof(T).Name}{message.Arg}", message.Data, null);
}
catch (Exception ex)
{
ex.PrintStack();
}
});
}
}
}