LanYinWsHostedService.cs
11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Services;
using Rcs.Cyaninetech.Models;
using Rcs.Cyaninetech.Services;
using Rcs.Domain.Entities;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Shared.Utils;
namespace Rcs.Cyaninetech.BackgroundServices
{
/// <summary>
/// 蓝音 WebSocket 后台服务 - 自动连接并订阅消息
/// @author zzy
/// </summary>
public class LanYinWsHostedService : BackgroundService
{
private readonly ILogger<LanYinWsHostedService> _logger;
private readonly ILanYinWsClientService _wsClient;
private readonly LanYinWsSettings _settings;
private readonly IServiceScopeFactory _scopeFactory;
private readonly TimeSpan _reconnectInterval = TimeSpan.FromSeconds(5);
public LanYinWsHostedService(
ILogger<LanYinWsHostedService> logger,
ILanYinWsClientService wsClient,
IOptions<AppSettings> settings,
IServiceScopeFactory scopeFactory)
{
_logger = logger;
_wsClient = wsClient;
_settings = settings.Value.LanYinSettings.WebSocket;
_scopeFactory = scopeFactory;
// 注册事件处理
_wsClient.OnRobotStatusReceived += HandleRobotStatus;
_wsClient.OnRobotInfoReceived += HandleRobotInfo;
_wsClient.OnRobotRealtimePathReceived += HandleRobotRealtimePath;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// 检查是否启
if (!_settings.Enabled)
{
_logger.LogWarning("内部服务未启用");
return;
}
try
{
if (!_wsClient.IsConnected)
{
await _wsClient.ConnectAsync(stoppingToken);
// 连接成功后发送订阅请求(使用配置)
await _wsClient.SubscribeAsync(_settings.Topics.ToList());
}
await Task.Delay(_reconnectInterval, stoppingToken);
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "[LanYin WS] 连接异常,{Interval}秒后重试", _reconnectInterval.TotalSeconds);
await Task.Delay(_reconnectInterval, stoppingToken);
}
}
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("[LanYin WS] 后台服务停止");
await _wsClient.DisconnectAsync();
await base.StopAsync(cancellationToken);
}
/// <summary>
/// 处理机器人状态数据(直接使用消息中的制造商和序列号更新缓存)
/// @author zzy
/// </summary>
private void HandleRobotStatus(object? sender, List<LanYinRobotStatus> data)
{
_ = Task.Run(async () =>
{
using var scope = _scopeFactory.CreateScope();
var cacheService = scope.ServiceProvider.GetRequiredService<IRobotCacheService>();
foreach (var status in data)
{
try
{
//更新操作模式
var operatingMode = status.OperatingMode.ToUpper() switch
{
"AUTOMATIC" => OperatingMode.Automatic,
"SEMIAUTOMATIC" => OperatingMode.Semiautomatic,
"MANUAL" => OperatingMode.Manual,
"SERVICE" => OperatingMode.Service,
"TEACHIN" => OperatingMode.Teachin,
_ => OperatingMode.Manual
};
await cacheService.UpdateStatusAsync(
null,
status.SerialNumber,
null,
null,
status.BatteryState?.BatteryCharge ?? 0,
status.Driving,
//status.Paused,
false,
status.BatteryState?.Charging,
operatingMode,
status.Errors.ToJsonWithChinese()
);
// 更新位置缓存
if (status.Position != null)
{
var basic = await cacheService.GetBasicAsync(null, status.SerialNumber);
var scale = basic?.CoordinateScale ?? 1d;
await cacheService.UpdateLocationAsync(
null,
status.SerialNumber,
null,
null,
status.Position.X * scale,
status.Position.Y * scale,
AngleConverter.NormalizeRadians(status.Position.Rad));
}
}
catch (Exception ex)
{
_logger.LogError(ex, "[LanYin WS] 更新机器人状态缓存失败: {Manufacturer}:{SerialNumber}",
status.Manufacturer, status.SerialNumber);
}
}
});
}
/// <summary>
/// 处理机器人信息数据(直接使用消息中的序列号和固定制造商更新缓存)
/// @author zzy
/// </summary>
private void HandleRobotInfo(object? sender, List<LanYinRobotInfo> data)
{
_ = Task.Run(async () =>
{
using var scope = _scopeFactory.CreateScope();
var cacheService = scope.ServiceProvider.GetRequiredService<IRobotCacheService>();
var taskRepo = scope.ServiceProvider.GetRequiredService<IRobotTaskRepository>();
foreach (var info in data)
{
var status = RobotStatus.Idle;
var currTask = info.CurrentTask;
var onlineStatus = OnlineStatus.Online;
if (info.RunningStatus.ToUpper().Equals("FAULT") || info.RunningStatus.ToUpper().Equals("DISCONNECT"))
{
status = RobotStatus.Error;
if (info.RunningStatus.ToUpper().Equals("DISCONNECT"))
{
onlineStatus = OnlineStatus.Offline;
}
}
else
{
// 根据 task_status 映射 RobotStatus
// free - 空闲(无任务), resting/prerest - 休息中 → Idle
// use/pre_use/precharge/charging → Busy
status = info.TaskStatus switch
{
"free" or "prerest" or "resting" or "charging" => RobotStatus.Idle,
"use" or "pre_use" or "precharge" => RobotStatus.Busy,
_ => RobotStatus.Busy
};
}
await cacheService.UpdateStatusAsync(
null,
info.Id,
status,
onlineStatus,
null,
null,
null,
null,
null,
null
);
// 临时用法,蓝因无法指定机器人执行任务,所以通过状态同步任务对应的机器人编号
if (status == RobotStatus.Busy)
{
var robot = await cacheService.GetBasicAsync(null,info.Id);
var task = await taskRepo.GetByRelationAsync(currTask);
if (task != null && Guid.TryParse(robot?.RobotId, out var robotId))
{
task.RobotId = robotId;
await taskRepo.UpdateAsync(task);
}
}
}
});
}
/// <summary>
/// 处理机器人实时路径数据
/// @author zzy
/// </summary>
private void HandleRobotRealtimePath(object? sender, LanYinRobotRealtimePath data)
{
// 1. 校验核心数据 data 非空
if (data == null)
{
// 可根据实际需求添加日志记录,方便排查问题
// _logger?.LogWarning("处理机器人实时路径时,传入的路径数据为空");
return;
}
_ = Task.Run(async () =>
{
using var scope = _scopeFactory.CreateScope();
var cacheService = scope.ServiceProvider.GetRequiredService<IRobotCacheService>();
// 2. 遍历前先校验 data 集合非空且有数据
if (data == null || !data.Any())
{
return;
}
foreach (var (robotId, path) in data)
{
// 3. 校验 robotId 非空/非空字符串、path 非空且有数据
if (string.IsNullOrEmpty(robotId) || path == null || !path.Any())
{
// _logger?.LogWarning("机器人ID为空或路径点集合为空,跳过处理。RobotId: {RobotId}", robotId ?? "空");
continue;
}
var basic = await cacheService.GetBasicAsync(null, robotId);
// 4. basic 为空时 scale 直接取默认值 1d,无需额外处理
var scale = basic?.CoordinateScale ?? 1d;
foreach (var point in path)
{
// 5. 校验坐标点数组非空且至少有2个元素(x,y)
if (point == null || point.ToArray().Length < 2)
{
// _logger?.LogWarning("机器人{RobotId}的路径点数据异常,跳过该点。", robotId);
continue;
}
point[0] *= scale;
point[1] *= scale;
}
// 6. 最终存储前再次确认 path 非空(防御性校验)
if (path.Any())
{
await cacheService.SetLocationValueAsync(null, robotId, "Path", path.ToJsonWithChinese());
}
}
});
}
}
}