detect/detect.gui/Services/DeviceClientService.cs

327 lines
11 KiB
C#
Raw Normal View History

2024-11-13 17:09:15 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
2024-11-15 10:56:24 +08:00
using System.Threading.Tasks;
2024-11-13 17:09:15 +08:00
using detect.device;
using detect.gui.Models.Entities;
using detect.gui.Services.Detect;
using Serilog;
using Splat;
namespace detect.gui.Services;
public class DeviceClientService
{
private readonly IDictionary<long, IDeviceClient> _deviceClients = new Dictionary<long, IDeviceClient>();
public DeviceClientService()
{
ConnectAllDevices();
2024-11-15 14:49:29 +08:00
Log.Information("DeviceClientService Initialize Done.");
}
2024-11-22 13:35:39 +08:00
2024-11-15 14:49:29 +08:00
private static DeviceClientService? _instance;
2024-11-22 13:35:39 +08:00
2024-11-15 14:49:29 +08:00
public static DeviceClientService Instance()
{
2024-11-22 13:35:39 +08:00
return _instance ??= new DeviceClientService();
2024-11-13 17:09:15 +08:00
}
/// <summary>
/// 连接所有设备
/// </summary>
public void ConnectAllDevices()
{
2024-11-19 16:13:59 +08:00
var deviceService = Locator.Current.GetService<DetectDeviceService>()!;
var devices = deviceService.ListAll().Result!;
2024-11-13 17:09:15 +08:00
if (devices.Any())
{
2024-11-22 13:35:39 +08:00
devices.ForEach(device => { ConnectDevice(device); });
2024-11-13 17:09:15 +08:00
}
}
2024-11-15 10:05:49 +08:00
/// <summary>
/// 断开所有连接
/// </summary>
public void DisConnectAllDevices()
{
foreach (var (key, client) in _deviceClients)
{
client.DisConnectAsync();
}
}
2024-11-22 13:35:39 +08:00
2024-11-13 17:09:15 +08:00
/// <summary>
/// 根据设备id获取连接客户端
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
public IDeviceClient? GetDeviceClient(long deviceId)
{
_deviceClients.TryGetValue(deviceId, out var deviceClient);
return deviceClient;
}
2024-11-22 13:35:39 +08:00
2024-11-15 10:05:49 +08:00
/// <summary>
/// 刷新连接客户端,设备信息更新后调用
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
2024-11-15 15:58:09 +08:00
public IDeviceClient? RefreshDeviceClientById(long deviceId)
2024-11-15 10:05:49 +08:00
{
_deviceClients.TryGetValue(deviceId, out var deviceClient);
deviceClient?.DisConnectAsync();
var eventService = Locator.Current.GetService<DetectDeviceService>()!;
return ConnectDevice(eventService.ListById(deviceId).Result!);
}
2024-11-22 13:35:39 +08:00
2024-11-15 10:56:24 +08:00
/// <summary>
/// 刷新连接客户端,设备信息更新后调用
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public IDeviceClient? RefreshDeviceClient(DeviceEntity device)
{
_deviceClients.TryGetValue(device.Id!.Value, out var deviceClient);
deviceClient?.DisConnectAsync();
return ConnectDevice(device);
}
2024-11-22 13:35:39 +08:00
/// <summary>
/// 断开连接并释放
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
public void DeleteDeviceClientById(long deviceId)
{
_deviceClients.TryGetValue(deviceId, out var deviceClient);
deviceClient?.DisConnectAsync();
_deviceClients.Remove(deviceId);
}
2024-11-22 13:35:39 +08:00
2024-11-13 17:09:15 +08:00
/// <summary>
/// 连接云台设备
/// </summary>
/// <param name="device"></param>
/// <returns></returns>
public IDeviceClient? ConnectDevice(DeviceEntity device)
{
2024-11-15 10:05:49 +08:00
if (string.IsNullOrEmpty(device.DeviceIp))
{
Log.Warning("设备【{Name}】没有配置ip不连接", device.Name);
return null;
}
2024-11-22 13:35:39 +08:00
2024-11-13 17:09:15 +08:00
_deviceClients.TryGetValue(device.Id!.Value, out var deviceClient);
2024-11-15 10:05:49 +08:00
if (deviceClient == null)
{
deviceClient = new DeviceClientSocket(device.DeviceIp!, 13000);
deviceClient.ConnectAsync();
_deviceClients.Add(device.Id!.Value, deviceClient);
}
else
{
if (!deviceClient.Connected())
{
deviceClient.ConnectAsync();
}
}
2024-11-22 13:35:39 +08:00
2024-11-15 10:05:49 +08:00
deviceClient.DeviceEvent += DeviceClientOnDeviceEvent;
2024-11-22 13:35:39 +08:00
2024-11-13 17:09:15 +08:00
return deviceClient;
}
private void DeviceClientOnDeviceEvent(object? sender, DeviceEvent e)
{
2024-11-22 13:35:39 +08:00
Log.Information("DeviceEvent-[{Name}]-{Address}:{@Result}", e.Name, (sender as DeviceClientSocket)!.Address,
e.Result);
if (e.Name == DeviceEvent.EventDeviceConnected)
2024-11-15 10:56:24 +08:00
{
2024-11-21 16:28:36 +08:00
// var sysInfo = GetDeviceInfo(1).GetAwaiter().GetResult();
// Log.Information("device info: {@Info}", sysInfo);
2024-11-19 16:13:59 +08:00
// test
// AssignTasks(new long[] { 1 }).GetAwaiter();
2024-11-15 10:56:24 +08:00
}
2024-11-22 13:35:39 +08:00
2024-11-13 17:09:15 +08:00
// var deviceService = Locator.Current.GetService<VapDeviceService>()!;
// var eventService = Locator.Current.GetService<VapEventService>()!;
// var constantService = Locator.Current.GetService<VapConstantService>()!;
// var deviceClient = sender as DeviceClientSocket;
// var device = deviceService.ListByDeviceIp(deviceClient!.Address).Result!;
// var eventEntity = new EventEntity
// {
// RegionId = device.RegionId,
// DeviceId = device.Id,
// Code = e.Result["alarmType"] as string,
// AlarmLevel = "INFO",
// ImageUrl = $"http://{device.DeviceIp}:8000/{e.Result["image"] as string}",
// EventTime = DateTime.Parse((e.Result["datetime"] as string)!)
// };
// if (eventEntity.ImageUrl.StartsWith("http"))
// {
// var constant = constantService.ListOne(code: VapConstantService.EVENT_DATA_SAVE_PATH).Result;
// var savePath = Path.Join(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments),
// "aivap/event");
// if (constant != null)
// {
// savePath = constant.Value;
// }
// savePath = Path.Join(savePath, eventEntity.DeviceId.ToString());
// if (!Directory.Exists(savePath))
// {
// Directory.CreateDirectory(savePath!);
// }
// var filename = eventEntity.ImageUrl.Split("/").Last();
// var filePath = Path.Join(savePath!, filename);
// try
// {
// FileUtil.DownloadFileAsync(eventEntity.ImageUrl, filePath).GetAwaiter().GetResult();
// Log.Information("事件图片下载完成:{path}", filePath);
// eventEntity.ImageUrl = new FileInfo(filePath).FullName;
// }
// catch (Exception ex)
// {
// Log.Error(ex, "事件图片下载完成:{Error}", ex.Message);
// }
// }
// eventService.AddData(eventEntity);
}
2024-11-15 10:56:24 +08:00
#region
2024-11-22 13:35:39 +08:00
2024-11-15 10:56:24 +08:00
/// <summary>
/// 查询设备信息
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<Dictionary<string, object>?> GetDeviceInfo(long deviceId)
{
var deviceClient = GetDeviceClient(deviceId);
if (deviceClient == null)
{
throw new Exception("设备未连接!");
}
var req = DeviceClientRequestBuilder.Create().WithType("service").WithComponent("_database")
.WithMethod("system_info");
var resp = await deviceClient.RequestAction<Dictionary<string, object>>(req);
if (resp.IsFailed)
{
throw new Exception(resp.Message);
}
2024-11-22 13:35:39 +08:00
2024-11-15 10:56:24 +08:00
return resp.Result;
}
2024-11-22 13:35:39 +08:00
2024-11-19 16:13:59 +08:00
public async Task<Dictionary<string, object>?> AssignTasks(long[] taskIds)
{
var taskService = Locator.Current.GetService<DetectTaskService>()!;
var deviceService = Locator.Current.GetService<DetectDeviceService>()!;
var taskList = taskService.ListByIds(taskIds).Result!;
if (taskList.Count == 0)
{
throw new Exception("未选择需要下发的任务!");
}
var deviceSn = taskList[0].DeviceSn!;
var device = deviceService.ListBySn(deviceSn).Result!;
if (device == null)
{
throw new Exception("未找到设备!");
}
2024-11-22 13:35:39 +08:00
2024-11-19 16:13:59 +08:00
var deviceClient = GetDeviceClient(device.Id!.Value);
if (deviceClient == null)
{
throw new Exception("设备未连接!");
}
2024-11-22 13:35:39 +08:00
if (!deviceClient.Connected())
{
throw new Exception("设备连接失败!");
}
2024-11-22 13:35:39 +08:00
2024-11-19 16:13:59 +08:00
var req = DeviceClientRequestBuilder.Create().WithType("service").WithComponent("dat_task")
.WithMethod("add_server_tasks").WithParam("tasks", taskList);
var resp = await deviceClient.RequestAction<Dictionary<string, object>>(req);
if (resp.IsFailed)
{
throw new Exception(resp.Message);
}
2024-11-22 13:35:39 +08:00
2024-11-19 16:13:59 +08:00
return resp.Result;
}
2024-11-15 10:56:24 +08:00
public async Task SyncTasks(long[] taskIds)
{
var taskService = Locator.Current.GetService<DetectTaskService>()!;
var deviceService = Locator.Current.GetService<DetectDeviceService>()!;
var taskList = taskService.ListByIds(taskIds).Result!;
if (taskList.Count == 0)
{
throw new Exception("未选择需要同步的任务!");
}
2024-11-22 13:35:39 +08:00
var deviceSn = taskList[0].DeviceSn!;
var device = deviceService.ListBySn(deviceSn).Result!;
if (device == null)
{
throw new Exception("未找到设备!");
}
2024-11-22 13:35:39 +08:00
var deviceClient = GetDeviceClient(device.Id!.Value);
if (deviceClient == null)
{
throw new Exception("设备未连接!");
}
2024-11-22 13:35:39 +08:00
if (!deviceClient.Connected())
{
throw new Exception("设备连接失败!");
}
2024-11-22 13:35:39 +08:00
foreach (var task in taskList)
{
var req = DeviceClientRequestBuilder.Create().WithType("service").WithComponent("dat_task")
.WithMethod("sync_client_tasks").WithParam("device_id", task.Id!.Value)
.WithParam("device_sn", task.DeviceSn!);
var resp = await deviceClient.RequestAction<Dictionary<string, object>>(req);
if (resp.IsFailed)
{
throw new Exception(resp.Message);
}
2024-11-22 13:35:39 +08:00
if (resp.Result is null) continue;
task.ResultJson = (string?)resp.Result!["result_json"];
2024-11-22 13:35:39 +08:00
task.StartTime = Convert.ToDateTime(resp.Result!["start_time"]) == DateTime.MinValue
? null
: Convert.ToDateTime(resp.Result!["start_time"]);
task.EndTime = Convert.ToDateTime(resp.Result!["end_time"]) == DateTime.MinValue
? null
: Convert.ToDateTime(resp.Result!["end_time"]);
task.State = Convert.ToInt32((long)resp.Result!["state"]);
Locator.Current.GetService<DetectTaskService>()!.UpdateData(task);
}
}
2024-11-22 13:35:39 +08:00
public Task<Dictionary<string, bool>?> GetDeviceConnected()
{
var r = new Dictionary<string, bool>();
var deviceService = Locator.Current.GetService<DetectDeviceService>()!;
var devices = deviceService.ListAll().Result!;
if (devices.Count != 0)
{
devices.ForEach(device =>
{
_deviceClients.TryGetValue(device.Id!.Value, out var deviceClient);
if (device.DeviceSn != null) r.Add(device.DeviceSn, deviceClient != null && deviceClient.Connected());
});
}
return Task.FromResult(r.Count == 0 ? null : r);
}
2024-11-15 10:56:24 +08:00
#endregion
2024-11-13 17:09:15 +08:00
}