设备重连加日志

This commit is contained in:
yanghongwei 2025-03-26 15:47:27 +08:00
parent c3ee874294
commit 2d9492d4df
3 changed files with 26 additions and 20 deletions

View File

@ -16,6 +16,7 @@ using Newtonsoft.Json;
using StackExchange.Redis; using StackExchange.Redis;
using LY.App.Common.HttpUtil; using LY.App.Common.HttpUtil;
using LY.App.Device.Command; using LY.App.Device.Command;
using LY.App.Service;
namespace LY.App.Device namespace LY.App.Device
{ {
@ -53,7 +54,9 @@ namespace LY.App.Device
private readonly RedisService _redis = ServiceLocator.Instance.GetService<RedisService>(); private readonly RedisService _redis = ServiceLocator.Instance.GetService<RedisService>();
private static readonly object _lock = new object(); private static readonly object _lock = new object();
private readonly CancellationTokenSource _monitorCancellationTokenSource = new(); private readonly CancellationTokenSource _monitorCancellationTokenSource = new();
private DeviceManager() { private readonly LogService _log = ServiceLocator.Instance.GetService<LogService>();
private DeviceManager()
{
Task.Run(() => MonitorDevices(_monitorCancellationTokenSource.Token)); Task.Run(() => MonitorDevices(_monitorCancellationTokenSource.Token));
} }
@ -124,6 +127,13 @@ namespace LY.App.Device
return _devices; return _devices;
} }
/// <summary>
/// 下发命令
/// </summary>
/// <param name="deviceId"></param>
/// <param name="command"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task SendCommand(long deviceId, string command) public async Task SendCommand(long deviceId, string command)
{ {
if (_devices.TryGetValue(deviceId, out var device)) if (_devices.TryGetValue(deviceId, out var device))
@ -295,7 +305,6 @@ namespace LY.App.Device
{ {
Console.WriteLine($"设备 {device.Id} 掉线,尝试重连..."); Console.WriteLine($"设备 {device.Id} 掉线,尝试重连...");
device.IsConnected = false; device.IsConnected = false;
await HandleDeviceConnection(device);
}; };
mqttClient.ApplicationMessageReceivedAsync += e => mqttClient.ApplicationMessageReceivedAsync += e =>
@ -312,20 +321,6 @@ namespace LY.App.Device
_mqttClients[device.Id] = mqttClient; // 保存 MQTT 客户端实例 _mqttClients[device.Id] = mqttClient; // 保存 MQTT 客户端实例
device.IsConnected = true; device.IsConnected = true;
} }
//while (device.isconnected)
//{
// await task.delay(1000);
//}
// 循环结束后断开连接
//if (!mqttClient.IsConnected)
//{
// await mqttClient.DisconnectAsync();
// mqttClient.Dispose();
//}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -338,7 +333,7 @@ namespace LY.App.Device
{ {
int retryDelay = 1000; // 初始重连间隔1秒 int retryDelay = 1000; // 初始重连间隔1秒
int maxDelay = 30000; // 最大重连间隔30秒 int maxDelay = 30000; // 最大重连间隔30秒
await _log.AddLog(new AddLog { Message = $"设备 {device.Id} 掉线,重新连接中...", Parameters = "", StackTrace = "", url = "" });
while (!device.IsConnected) while (!device.IsConnected)
{ {
try try
@ -363,6 +358,7 @@ namespace LY.App.Device
{ {
retryDelay = 1000; // 连接成功后重置重连间隔 retryDelay = 1000; // 连接成功后重置重连间隔
Console.WriteLine($"设备 {device.Id} 重新连接成功"); Console.WriteLine($"设备 {device.Id} 重新连接成功");
await _log.AddLog(new AddLog { Message = $"设备 {device.Id} 重新连接成功", Parameters = "", StackTrace = "", url = "" });
} }
} }
catch (Exception ex) catch (Exception ex)
@ -374,6 +370,11 @@ namespace LY.App.Device
retryDelay = Math.Min(retryDelay * 2, maxDelay); // 指数退避算法,避免频繁重试 retryDelay = Math.Min(retryDelay * 2, maxDelay); // 指数退避算法,避免频繁重试
} }
} }
/// <summary>
/// 监控设备状态
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task MonitorDevices(CancellationToken cancellationToken) private async Task MonitorDevices(CancellationToken cancellationToken)
{ {
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
@ -389,6 +390,11 @@ namespace LY.App.Device
await Task.Delay(10000, cancellationToken); // 每 10 秒检查一次设备状态 await Task.Delay(10000, cancellationToken); // 每 10 秒检查一次设备状态
} }
} }
/// <summary>
/// 测试设备连接
/// </summary>
/// <param name="deviceId"></param>
/// <returns></returns>
public async Task<bool> TestConnection(long deviceId) public async Task<bool> TestConnection(long deviceId)
{ {
if (_devices.TryGetValue(deviceId, out var device)) if (_devices.TryGetValue(deviceId, out var device))

View File

@ -124,7 +124,7 @@ namespace LY.App.Service
//更新 设备缓存 //更新 设备缓存
var key = RedisKeyList.DeviceInfo(input.product_ad_id); var key = RedisKeyList.DeviceInfo(input.product_ad_id);
var deviceinfo = await _redisService.GetAsync<DeviceEntity>(key); var deviceinfo = await _redisService.GetAsync<DeviceEntity>(key);
if (deviceinfo == null) if (deviceinfo != null)
{ {
deviceinfo.Lat = input.product_lat; deviceinfo.Lat = input.product_lat;
deviceinfo.Lon = input.product_lon; deviceinfo.Lon = input.product_lon;

View File

@ -137,7 +137,7 @@ namespace LY.App.Service
try try
{ {
var input = JsonConvert.DeserializeObject<RevData>(data); var input = JsonConvert.DeserializeObject<RevData>(data);
Console.WriteLine($"rev data:{data}"); // Console.WriteLine($"rev data:{data}");
await _alarmService.AddAlarm(input); await _alarmService.AddAlarm(input);
} }
catch (Exception ex) catch (Exception ex)