LanYinService.cs
14.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Common;
using Rcs.Application.Shared;
using Rcs.Cyaninetech.Models;
using Rcs.Domain.Settings;
namespace Rcs.Cyaninetech.Services;
/// <summary>
/// LanYin外挂服务实现
/// </summary>
public class LanYinService : ILanYinService
{
private readonly IHttpClientService _httpClient;
private readonly ILogger<LanYinService> _logger;
private readonly LanYinSettings _settings;
private readonly SemaphoreSlim _loginLock = new SemaphoreSlim(1, 1);
public LanYinService(
IHttpClientService httpClient,
ILogger<LanYinService> logger,
IOptions<AppSettings> settings)
{
_httpClient = httpClient;
_logger = logger;
_settings = settings.Value.LanYinSettings;
}
public async Task<bool> LoginAsync(
LanYinLoginRequest request,
CancellationToken cancellationToken = default)
{
try
{
_logger.LogInformation(
"尝试使用账号 {Account} 登录",
request.account);
var url = $"{_settings.BaseUrl}{_settings.Endpoints.Login}";
var response = await _httpClient.PutAsync<LanYinLoginRequest, LanYinResponse<LanYinLoginData>>(
url,
request,
null, // 登录请求不需要认证头
cancellationToken);
if (response?.success == true && response.data != null)
{
// 自动更新服务的认证令牌和登录凭证
_settings.AuthToken = response.data.access_token;
// _settings.Account = _settings.Account;
// _settings.Password = _settings.Password;
_logger.LogInformation("成功以账号 {Account} 登录", request.account);
return true;
}
else
{
var errorId = response?.msg?.detail?.error_id ?? 0;
var errorInfo = response?.msg?.detail?.info ?? "Unknown error";
throw new Exception($"[{errorId}]-{errorInfo}");
}
}
catch (Exception ex)
{
_logger.LogError(
ex.Message);
return false;
}
}
public async Task<List<LanYinLocationData>> GetLocationsAsync(
string url,
CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
var headers = GetAuthHeaders();
var response = await _httpClient.GetAsync<LanYinResponse<List<LanYinLocationData>>>(
url,
headers,
cancellationToken);
if (response?.success == true)
{
return response.data != null ? (List<LanYinLocationData>)response.data : new List<LanYinLocationData>();
}
else
{
// 检查是否需要重新登录
if (NeedsRelogin(response.msg))
{
throw new TokenExpiredException("Token已过期或无效");
}
throw new Exception("获取库位信息失败");
}
},
cancellationToken,
new List<LanYinLocationData>());
}
public async Task<ApiResponse<LanYinTaskData>> DispatchTaskAsync(
LanYinDispatchTaskRequest request,
CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
_logger.LogInformation(
"正在将库位 {LocationId} 区域 {Area} 的任务下发到LanYin系统",
request.location_id,
request.area);
ApiResponse<LanYinTaskData> res = new ApiResponse<LanYinTaskData>();
var url = $"{_settings.BaseUrl}{_settings.Endpoints.DispatchTask}";
var headers = GetAuthHeaders();
var response = await _httpClient.PutAsync<LanYinDispatchTaskRequest, LanYinResponse<LanYinTaskData>>(
url,
request,
headers,
cancellationToken);
res.Success = response?.success ?? false;
res.Data = response?.data ?? new LanYinTaskData();
if (response?.success != true)
{
// 检查是否需要重新登录
if (NeedsRelogin(response?.msg))
{
throw new TokenExpiredException("Token已过期或无效");
}
res.Message = (response?.msg?.detail.info + response?.msg?.detail?.error_id) ?? "Unknown error";
}
return res;
},
cancellationToken,
new ApiResponse<LanYinTaskData>());
}
public async Task<LanYinMapInfoData> SyncMapResource(string url, CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
var headers = GetAuthHeaders();
var response = await _httpClient.GetAsync<LanYinResponse<List<LanYinMapInfoData>>>(
url,
headers,
cancellationToken);
if (response?.success == true)
{
return response.data?.Count > 0 ? response.data[0] : new LanYinMapInfoData();
}
else
{
// 检查是否需要重新登录
if (NeedsRelogin(response.msg))
{
throw new TokenExpiredException("Token已过期或无效");
}
throw new Exception("获取地图资源信息失败");
}
},
cancellationToken,
new LanYinMapInfoData());
}
/// <summary>
/// 确认工况异常
/// @author zzy
/// </summary>
public async Task<ApiResponse> ConfirmExceptionAsync(string robotId, CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
_logger.LogInformation("正在确认工况异常...");
var headers = GetAuthHeaders();
var url = $"{_settings.BaseUrl}{_settings.Endpoints.ConfirmException}";
var response = await _httpClient.PutAsync<LanYinRobotIdRequest, LanYinResponse<object>>(
url,
new LanYinRobotIdRequest(){slave_id = robotId},
headers,
cancellationToken);
if (response?.success != true)
{
if (NeedsRelogin(response?.msg)) throw new TokenExpiredException("Token已过期或无效");
return ApiResponse.Failed($"确认工况异常失败: {response?.msg?.detail?.info}");
}
return ApiResponse.Successful();
},
cancellationToken,
ApiResponse.Failed("操作失败"));
}
/// <summary>
/// 取消任务
/// @author zzy
/// </summary>
public async Task<ApiResponse> CancelTaskAsync(CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
_logger.LogInformation("正在取消任务...");
var res = new ApiResponse<bool>();
var headers = GetAuthHeaders();
var url = $"{_settings.BaseUrl}{_settings.Endpoints.CancelTask}";
var response = await _httpClient.PutAsync<object, LanYinResponse<object>>(url, new { }, headers, cancellationToken);
if (response?.success != true)
{
if (NeedsRelogin(response?.msg)) throw new TokenExpiredException("Token已过期或无效");
return ApiResponse.Failed($"取消任务失败: {response?.msg?.detail?.info}");
}
return ApiResponse.Successful();
},
cancellationToken,
ApiResponse.Failed("操作失败"));
}
/// <summary>
/// 取消指定机器人的任务
/// @author zzy
/// </summary>
public async Task<ApiResponse> CancelTaskByRobotAsync(string robotId, CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
_logger.LogInformation("正在取消机器人 {RobotId} 的任务...", robotId);
var res = new ApiResponse<bool>();
var headers = GetAuthHeaders();
var url = $"{_settings.BaseUrl}{_settings.Endpoints.CancelTask}";
var response = await _httpClient.PatchAsync<LanYinCancelTaskRequest, LanYinResponse<object>>(
url,
new LanYinCancelTaskRequest(){slave_id = robotId},
headers,
cancellationToken);
if (response?.success != true)
{
if (NeedsRelogin(response?.msg)) throw new TokenExpiredException("Token已过期或无效");
return ApiResponse.Failed($"取消指定机器人的任务失败: {response?.msg?.detail?.info}");
}
return ApiResponse.Successful();
},
cancellationToken,
ApiResponse.Failed("操作失败"));
}
/// <summary>
/// 复位指定机器人
/// @author zzy
/// </summary>
public async Task<ApiResponse> ResetRobotAsync(string robotId, CancellationToken cancellationToken = default)
{
return await ExecuteWithAutoRetryAsync(
async () =>
{
_logger.LogInformation("正在复位机器人 {RobotId}...", robotId);
var res = new ApiResponse<bool>();
var headers = GetAuthHeaders();
var url = $"{_settings.BaseUrl}{_settings.Endpoints.ResetRobot}";
var response = await _httpClient.PutAsync<LanYinRobotIdRequest, LanYinResponse<object>>(
url,
new LanYinRobotIdRequest(){slave_id = robotId},
headers,
cancellationToken);
if (response?.success != true)
{
if (NeedsRelogin(response?.msg)) throw new TokenExpiredException("Token已过期或无效");
return ApiResponse.Failed($"复位指定机器人的任务失败: {response?.msg?.detail?.info}");
}
return ApiResponse.Successful();
},
cancellationToken,
ApiResponse.Failed("操作失败"));
}
/// <summary>
/// 执行带自动重试的请求(如果token过期会自动重新登录)
/// </summary>
private async Task<T> ExecuteWithAutoRetryAsync<T>(
Func<Task<T>> operation,
CancellationToken cancellationToken,
T defaultValue)
{
try
{
return await operation();
}
catch (TokenExpiredException)
{
_logger.LogWarning("Token已过期,尝试重新登录...");
// 使用信号量确保只有一个线程执行登录
await _loginLock.WaitAsync(cancellationToken);
try
{
// 检查是否已经由其他线程完成了登录
if (!string.IsNullOrWhiteSpace(_settings.Account) &&
!string.IsNullOrWhiteSpace(_settings.Password))
{
var loginRequest = new LanYinLoginRequest
{
account = _settings.Account,
password = _settings.Password
};
var loginSuccess = await LoginAsync(loginRequest, cancellationToken);
if (loginSuccess)
{
_logger.LogInformation("重新登录成功,重试原始请求...");
// 重新执行原始操作
try
{
return await operation();
}
catch (TokenExpiredException)
{
_logger.LogError("重新登录后仍然失败");
return defaultValue;
}
}
else
{
_logger.LogError("重新登录失败");
return defaultValue;
}
}
else
{
_logger.LogError("无法自动重新登录:未配置账号或密码");
return defaultValue;
}
}
finally
{
_loginLock.Release();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "执行请求时发生错误");
return defaultValue;
}
}
/// <summary>
/// 检查响应是否表示需要重新登录
/// </summary>
private bool NeedsRelogin(ResMessage? msg)
{
if (msg?.detail?.error_id == null)
return false;
var errorId = msg.detail?.error_id;
return errorId == 51050008 || errorId == 51050006;
}
private Dictionary<string, string> GetAuthHeaders()
{
var headers = new Dictionary<string, string>();
if (!string.IsNullOrWhiteSpace(_settings.ApiKey))
{
headers.Add("X-API-Key", _settings.ApiKey);
}
if (!string.IsNullOrWhiteSpace(_settings.AuthToken))
{
headers.Add("Authorization", $"Bearer {_settings.AuthToken}");
}
return headers;
}
}
/// <summary>
/// Token过期异常
/// </summary>
internal class TokenExpiredException : Exception
{
public TokenExpiredException(string message) : base(message) { }
}