| | 1 | | using Grpc.Core; |
| | 2 | | using LGDXRobotCloud.API.Configurations; |
| | 3 | | using LGDXRobotCloud.API.Services.Navigation; |
| | 4 | | using LGDXRobotCloud.Protos; |
| | 5 | | using LGDXRobotCloud.Utilities.Constants; |
| | 6 | | using LGDXRobotCloud.Utilities.Enums; |
| | 7 | | using Microsoft.AspNetCore.Authorization; |
| | 8 | | using Microsoft.Extensions.Options; |
| | 9 | | using Microsoft.IdentityModel.Tokens; |
| | 10 | | using static LGDXRobotCloud.Protos.RobotClientsService; |
| | 11 | | using System.IdentityModel.Tokens.Jwt; |
| | 12 | | using System.Security.Claims; |
| | 13 | | using System.Text; |
| | 14 | | using LGDXRobotCloud.Data.Models.Business.Navigation; |
| | 15 | | using LGDXRobotCloud.API.Services.Automation; |
| | 16 | | using System.Threading.Channels; |
| | 17 | | using LGDXRobotCloud.API.Services.Common; |
| | 18 | |
|
| | 19 | | namespace LGDXRobotCloud.API.Services; |
| | 20 | |
|
| | 21 | | [Authorize(AuthenticationSchemes = LgdxRobotCloudAuthenticationSchemes.RobotClientsJwtScheme)] |
| 0 | 22 | | public class RobotClientsService( |
| 0 | 23 | | IAutoTaskSchedulerService autoTaskSchedulerService, |
| 0 | 24 | | IEventService eventService, |
| 0 | 25 | | IOnlineRobotsService OnlineRobotsService, |
| 0 | 26 | | IOptionsSnapshot<LgdxRobotCloudSecretConfiguration> lgdxRobotCloudSecretConfiguration, |
| 0 | 27 | | IRobotService robotService |
| 0 | 28 | | ) : RobotClientsServiceBase |
| | 29 | | { |
| 0 | 30 | | private readonly IAutoTaskSchedulerService _autoTaskSchedulerService = autoTaskSchedulerService; |
| 0 | 31 | | private readonly IEventService _eventService = eventService; |
| 0 | 32 | | private readonly IOnlineRobotsService _onlineRobotsService = OnlineRobotsService; |
| 0 | 33 | | private readonly LgdxRobotCloudSecretConfiguration _lgdxRobotCloudSecretConfiguration = lgdxRobotCloudSecretConfigurat |
| 0 | 34 | | private readonly IRobotService _robotService = robotService; |
| 0 | 35 | | private Guid _streamingRobotId = Guid.Empty; |
| 0 | 36 | | private RobotClientsRobotStatus _streamingRobotStatus = RobotClientsRobotStatus.Offline; |
| 0 | 37 | | private readonly Channel<RobotClientsRespond> _streamMessageQueue = Channel.CreateUnbounded<RobotClientsRespond>(); |
| | 38 | |
|
| | 39 | | private static Guid? ValidateRobotClaim(ServerCallContext context) |
| 0 | 40 | | { |
| 0 | 41 | | var robotClaim = context.GetHttpContext().User.FindFirst(ClaimTypes.NameIdentifier); |
| 0 | 42 | | if (robotClaim == null) |
| 0 | 43 | | { |
| 0 | 44 | | return null; |
| | 45 | | } |
| 0 | 46 | | return Guid.Parse(robotClaim.Value); |
| 0 | 47 | | } |
| | 48 | |
|
| | 49 | | private static RobotClientsRespond ValidateRobotClaimFailed() |
| 0 | 50 | | { |
| 0 | 51 | | return new RobotClientsRespond { |
| 0 | 52 | | Status = RobotClientsResultStatus.Failed, |
| 0 | 53 | | }; |
| 0 | 54 | | } |
| | 55 | |
|
| | 56 | | // TODO: Validate in authorisation |
| | 57 | | private async Task<bool> ValidateOnlineRobotsAsync(Guid robotId) |
| 0 | 58 | | { |
| 0 | 59 | | return await _onlineRobotsService.IsRobotOnlineAsync(robotId); |
| 0 | 60 | | } |
| | 61 | |
|
| | 62 | | private static RobotClientsRespond ValidateOnlineRobotsFailed() |
| 0 | 63 | | { |
| 0 | 64 | | return new RobotClientsRespond { |
| 0 | 65 | | Status = RobotClientsResultStatus.Failed, |
| 0 | 66 | | }; |
| 0 | 67 | | } |
| | 68 | |
|
| | 69 | | [Authorize(AuthenticationSchemes = LgdxRobotCloudAuthenticationSchemes.RobotClientsCertificateScheme)] |
| | 70 | | public override async Task<RobotClientsGreetRespond> Greet(RobotClientsGreet request, ServerCallContext context) |
| 0 | 71 | | { |
| 0 | 72 | | var robotId = ValidateRobotClaim(context); |
| 0 | 73 | | if (robotId == null) |
| 0 | 74 | | return new RobotClientsGreetRespond { |
| 0 | 75 | | Status = RobotClientsResultStatus.Failed, |
| 0 | 76 | | AccessToken = string.Empty |
| 0 | 77 | | }; |
| | 78 | |
|
| 0 | 79 | | var robotIdGuid = (Guid)robotId; |
| 0 | 80 | | var robot = await _robotService.GetRobotAsync(robotIdGuid); |
| 0 | 81 | | if (robot == null) |
| 0 | 82 | | return new RobotClientsGreetRespond { |
| 0 | 83 | | Status = RobotClientsResultStatus.Failed, |
| 0 | 84 | | AccessToken = string.Empty |
| 0 | 85 | | }; |
| | 86 | |
|
| | 87 | | // Compare System Info |
| 0 | 88 | | var incomingSystemInfo = new RobotSystemInfoBusinessModel { |
| 0 | 89 | | Id = 0, |
| 0 | 90 | | Cpu = request.SystemInfo.Cpu, |
| 0 | 91 | | IsLittleEndian = request.SystemInfo.IsLittleEndian, |
| 0 | 92 | | Motherboard = request.SystemInfo.Motherboard, |
| 0 | 93 | | MotherboardSerialNumber = request.SystemInfo.MotherboardSerialNumber, |
| 0 | 94 | | RamMiB = request.SystemInfo.RamMiB, |
| 0 | 95 | | Gpu = request.SystemInfo.Gpu, |
| 0 | 96 | | Os = request.SystemInfo.Os, |
| 0 | 97 | | Is32Bit = request.SystemInfo.Is32Bit, |
| 0 | 98 | | McuSerialNumber = request.SystemInfo.McuSerialNumber, |
| 0 | 99 | | }; |
| 0 | 100 | | var systemInfo = await _robotService.GetRobotSystemInfoAsync(robotIdGuid); |
| 0 | 101 | | if (systemInfo == null) |
| 0 | 102 | | { |
| | 103 | | // Create Robot System Info for the first time |
| 0 | 104 | | await _robotService.CreateRobotSystemInfoAsync(robotIdGuid, incomingSystemInfo.ToCreateBusinessModel()); |
| 0 | 105 | | } |
| | 106 | | else |
| 0 | 107 | | { |
| | 108 | | // Hardware Protection |
| 0 | 109 | | if (robot.IsProtectingHardwareSerialNumber && incomingSystemInfo.MotherboardSerialNumber != systemInfo.Motherboard |
| 0 | 110 | | { |
| 0 | 111 | | return new RobotClientsGreetRespond { |
| 0 | 112 | | Status = RobotClientsResultStatus.Failed, |
| 0 | 113 | | AccessToken = string.Empty |
| 0 | 114 | | }; |
| | 115 | | } |
| 0 | 116 | | if (robot.IsProtectingHardwareSerialNumber && incomingSystemInfo.McuSerialNumber != systemInfo.McuSerialNumber) |
| 0 | 117 | | { |
| 0 | 118 | | return new RobotClientsGreetRespond { |
| 0 | 119 | | Status = RobotClientsResultStatus.Failed, |
| 0 | 120 | | AccessToken = string.Empty |
| 0 | 121 | | }; |
| | 122 | | } |
| 0 | 123 | | await _robotService.UpdateRobotSystemInfoAsync(robotIdGuid, incomingSystemInfo.ToUpdateBusinessModel()); |
| 0 | 124 | | } |
| | 125 | |
|
| | 126 | | // Generate Access Token |
| 0 | 127 | | var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_lgdxRobotCloudSecretConfiguration.RobotClientsJwt |
| 0 | 128 | | var credentials = new SigningCredentials(securityKey, _lgdxRobotCloudSecretConfiguration.RobotClientsJwtAlgorithm); |
| 0 | 129 | | var secToken = new JwtSecurityToken( |
| 0 | 130 | | _lgdxRobotCloudSecretConfiguration.RobotClientsJwtIssuer, |
| 0 | 131 | | _lgdxRobotCloudSecretConfiguration.RobotClientsJwtIssuer, |
| 0 | 132 | | [new Claim(ClaimTypes.NameIdentifier, robot.Id.ToString())], |
| 0 | 133 | | DateTime.UtcNow, |
| 0 | 134 | | DateTime.UtcNow.AddMinutes(_lgdxRobotCloudSecretConfiguration.RobotClientsJwtExpireMins), |
| 0 | 135 | | credentials); |
| 0 | 136 | | var token = new JwtSecurityTokenHandler().WriteToken(secToken); |
| | 137 | |
|
| 0 | 138 | | await _onlineRobotsService.AddRobotAsync((Guid)robotId); |
| | 139 | |
|
| 0 | 140 | | return new RobotClientsGreetRespond { |
| 0 | 141 | | Status = RobotClientsResultStatus.Success, |
| 0 | 142 | | AccessToken = token, |
| 0 | 143 | | IsRealtimeExchange = await _robotService.GetRobotIsRealtimeExchange((Guid)robotId) |
| 0 | 144 | | }; |
| 0 | 145 | | } |
| | 146 | |
|
| | 147 | | public override async Task<RobotClientsRespond> Exchange(RobotClientsExchange request, ServerCallContext context) |
| 0 | 148 | | { |
| 0 | 149 | | var robotId = ValidateRobotClaim(context); |
| 0 | 150 | | if (robotId == null) |
| 0 | 151 | | return ValidateRobotClaimFailed(); |
| 0 | 152 | | if (!await ValidateOnlineRobotsAsync((Guid)robotId)) |
| 0 | 153 | | return ValidateOnlineRobotsFailed(); |
| | 154 | |
|
| 0 | 155 | | await _onlineRobotsService.UpdateRobotDataAsync((Guid)robotId, request); |
| 0 | 156 | | var manualAutoTask = _onlineRobotsService.GetAutoTaskNextApi((Guid)robotId); |
| 0 | 157 | | if (manualAutoTask != null) |
| 0 | 158 | | { |
| | 159 | | // Triggered by API |
| 0 | 160 | | return new RobotClientsRespond { |
| 0 | 161 | | Status = RobotClientsResultStatus.Success, |
| 0 | 162 | | Commands = _onlineRobotsService.GetRobotCommands((Guid)robotId), |
| 0 | 163 | | Task = await _autoTaskSchedulerService.AutoTaskNextConstructAsync(manualAutoTask) |
| 0 | 164 | | }; |
| | 165 | | } |
| | 166 | | else |
| 0 | 167 | | { |
| | 168 | | // Get AutoTask |
| 0 | 169 | | RobotClientsAutoTask? task = null; |
| 0 | 170 | | if (request.RobotStatus == RobotClientsRobotStatus.Idle) |
| 0 | 171 | | { |
| 0 | 172 | | task = await _autoTaskSchedulerService.GetAutoTaskAsync((Guid)robotId); |
| 0 | 173 | | } |
| 0 | 174 | | return new RobotClientsRespond { |
| 0 | 175 | | Status = RobotClientsResultStatus.Success, |
| 0 | 176 | | Commands = _onlineRobotsService.GetRobotCommands((Guid)robotId), |
| 0 | 177 | | Task = task |
| 0 | 178 | | }; |
| | 179 | | } |
| 0 | 180 | | } |
| | 181 | |
|
| | 182 | | public override async Task ExchangeStream(IAsyncStreamReader<RobotClientsExchange> requestStream, IServerStreamWriter< |
| 0 | 183 | | { |
| 0 | 184 | | var robotId = ValidateRobotClaim(context); |
| 0 | 185 | | if (robotId == null) |
| 0 | 186 | | { |
| 0 | 187 | | var response = ValidateRobotClaimFailed(); |
| 0 | 188 | | await responseStream.WriteAsync(response); |
| 0 | 189 | | return; |
| | 190 | | } |
| 0 | 191 | | if (!await ValidateOnlineRobotsAsync((Guid)robotId)) |
| 0 | 192 | | { |
| 0 | 193 | | var response = ValidateOnlineRobotsFailed(); |
| 0 | 194 | | await responseStream.WriteAsync(response); |
| 0 | 195 | | return; |
| | 196 | | } |
| 0 | 197 | | _streamingRobotId = (Guid)robotId; |
| 0 | 198 | | _eventService.RobotCommandsUpdated += OnRobotCommandsUpdated; |
| 0 | 199 | | _eventService.RobotHasNextTask += OnRobotHasNextTask; |
| 0 | 200 | | _eventService.AutoTaskCreated += OnAutoTaskCreated; |
| | 201 | |
|
| 0 | 202 | | var clientToServer = ExchangeStreamClientToServerAsync((Guid)robotId, requestStream, context); |
| 0 | 203 | | var serverToClient = ExchangeStreamServerToClientAsync(responseStream, context); |
| 0 | 204 | | await Task.WhenAll(clientToServer, serverToClient); |
| 0 | 205 | | } |
| | 206 | |
|
| | 207 | | private async Task ExchangeStreamClientToServerAsync(Guid robotId, IAsyncStreamReader<RobotClientsExchange> requestStr |
| 0 | 208 | | { |
| 0 | 209 | | while (await requestStream.MoveNext(CancellationToken.None) && !context.CancellationToken.IsCancellationRequested) |
| 0 | 210 | | { |
| 0 | 211 | | var request = requestStream.Current; |
| 0 | 212 | | _streamingRobotStatus = request.RobotStatus; |
| | 213 | | // Get auto task |
| 0 | 214 | | if (request.RobotStatus == RobotClientsRobotStatus.Idle) |
| 0 | 215 | | { |
| 0 | 216 | | var task = await _autoTaskSchedulerService.GetAutoTaskAsync(robotId); |
| 0 | 217 | | if (task != null) |
| 0 | 218 | | { |
| 0 | 219 | | await _streamMessageQueue.Writer.WriteAsync(new RobotClientsRespond { |
| 0 | 220 | | Status = RobotClientsResultStatus.Success, |
| 0 | 221 | | Commands = _onlineRobotsService.GetRobotCommands(_streamingRobotId), |
| 0 | 222 | | Task = task |
| 0 | 223 | | }); |
| 0 | 224 | | } |
| 0 | 225 | | } |
| 0 | 226 | | await _onlineRobotsService.UpdateRobotDataAsync(robotId, request); |
| 0 | 227 | | } |
| | 228 | |
|
| | 229 | | // The reading stream is completed, stop wirting task |
| 0 | 230 | | _eventService.RobotCommandsUpdated -= OnRobotCommandsUpdated; |
| 0 | 231 | | _eventService.RobotHasNextTask -= OnRobotHasNextTask; |
| 0 | 232 | | _eventService.AutoTaskCreated -= OnAutoTaskCreated; |
| 0 | 233 | | _streamMessageQueue.Writer.TryComplete(); |
| 0 | 234 | | await _streamMessageQueue.Reader.Completion; |
| 0 | 235 | | } |
| | 236 | |
|
| | 237 | | private async Task ExchangeStreamServerToClientAsync(IServerStreamWriter<RobotClientsRespond> responseStream, ServerCa |
| 0 | 238 | | { |
| 0 | 239 | | await foreach (var message in _streamMessageQueue.Reader.ReadAllAsync(context.CancellationToken)) |
| 0 | 240 | | { |
| 0 | 241 | | await responseStream.WriteAsync(message); |
| 0 | 242 | | } |
| 0 | 243 | | } |
| | 244 | |
|
| | 245 | | private async void OnRobotCommandsUpdated(object? sender, Guid robotId) |
| 0 | 246 | | { |
| 0 | 247 | | if (_streamingRobotId != robotId) |
| 0 | 248 | | return; |
| 0 | 249 | | await _streamMessageQueue.Writer.WriteAsync(new RobotClientsRespond { |
| 0 | 250 | | Status = RobotClientsResultStatus.Success, |
| 0 | 251 | | Commands = _onlineRobotsService.GetRobotCommands(_streamingRobotId), |
| 0 | 252 | | }); |
| 0 | 253 | | } |
| | 254 | |
|
| | 255 | | private async void OnAutoTaskCreated(object? sender, EventArgs e) |
| 0 | 256 | | { |
| | 257 | | // Read |
| 0 | 258 | | if (_streamingRobotStatus != RobotClientsRobotStatus.Idle) |
| 0 | 259 | | return; |
| 0 | 260 | | var autoTask = await _autoTaskSchedulerService.GetAutoTaskAsync(_streamingRobotId); |
| 0 | 261 | | if (autoTask != null) |
| 0 | 262 | | { |
| 0 | 263 | | await _streamMessageQueue.Writer.WriteAsync(new RobotClientsRespond { |
| 0 | 264 | | Status = RobotClientsResultStatus.Success, |
| 0 | 265 | | Commands = _onlineRobotsService.GetRobotCommands(_streamingRobotId), |
| 0 | 266 | | Task = autoTask |
| 0 | 267 | | }); |
| 0 | 268 | | } |
| 0 | 269 | | } |
| | 270 | |
|
| | 271 | | private async void OnRobotHasNextTask(object? sender, Guid robotId) |
| 0 | 272 | | { |
| | 273 | | // When an auto task is completed by API |
| 0 | 274 | | if (_streamingRobotId != robotId) |
| 0 | 275 | | return; |
| 0 | 276 | | var manualAutoTask = _onlineRobotsService.GetAutoTaskNextApi(robotId); |
| 0 | 277 | | RobotClientsAutoTask? task = null; |
| 0 | 278 | | if (manualAutoTask != null) |
| 0 | 279 | | { |
| 0 | 280 | | task = await _autoTaskSchedulerService.AutoTaskNextConstructAsync(manualAutoTask); |
| 0 | 281 | | } |
| 0 | 282 | | await _streamMessageQueue.Writer.WriteAsync(new RobotClientsRespond { |
| 0 | 283 | | Status = RobotClientsResultStatus.Success, |
| 0 | 284 | | Commands = _onlineRobotsService.GetRobotCommands(robotId), |
| 0 | 285 | | Task = task |
| 0 | 286 | | }); |
| 0 | 287 | | } |
| | 288 | |
|
| | 289 | | public override async Task<RobotClientsRespond> AutoTaskNext(RobotClientsNextToken request, ServerCallContext context) |
| 0 | 290 | | { |
| 0 | 291 | | var robotId = ValidateRobotClaim(context); |
| 0 | 292 | | if (robotId == null) |
| 0 | 293 | | return ValidateRobotClaimFailed(); |
| 0 | 294 | | if (!await ValidateOnlineRobotsAsync((Guid)robotId)) |
| 0 | 295 | | return ValidateOnlineRobotsFailed(); |
| | 296 | |
|
| 0 | 297 | | var task = await _autoTaskSchedulerService.AutoTaskNextAsync((Guid)robotId, request.TaskId, request.NextToken); |
| 0 | 298 | | return new RobotClientsRespond { |
| 0 | 299 | | Status = task != null ? RobotClientsResultStatus.Success : RobotClientsResultStatus.Failed, |
| 0 | 300 | | Commands = _onlineRobotsService.GetRobotCommands((Guid)robotId), |
| 0 | 301 | | Task = task |
| 0 | 302 | | }; |
| 0 | 303 | | } |
| | 304 | |
|
| | 305 | | public override async Task<RobotClientsRespond> AutoTaskAbort(RobotClientsAbortToken request, ServerCallContext contex |
| 0 | 306 | | { |
| 0 | 307 | | var robotId = ValidateRobotClaim(context); |
| 0 | 308 | | if (robotId == null) |
| 0 | 309 | | return ValidateRobotClaimFailed(); |
| 0 | 310 | | if (!await ValidateOnlineRobotsAsync((Guid)robotId)) |
| 0 | 311 | | return ValidateOnlineRobotsFailed(); |
| | 312 | |
|
| 0 | 313 | | await _onlineRobotsService.SetAbortTaskAsync((Guid)robotId, false); |
| | 314 | |
|
| 0 | 315 | | AutoTaskAbortReason autoTaskAbortReason = (AutoTaskAbortReason)(int)request.AbortReason; |
| 0 | 316 | | var task = await _autoTaskSchedulerService.AutoTaskAbortAsync((Guid)robotId, request.TaskId, request.NextToken, auto |
| 0 | 317 | | return new RobotClientsRespond { |
| 0 | 318 | | Status = task != null ? RobotClientsResultStatus.Success : RobotClientsResultStatus.Failed, |
| 0 | 319 | | Commands = _onlineRobotsService.GetRobotCommands((Guid)robotId), |
| 0 | 320 | | Task = task |
| 0 | 321 | | }; |
| 0 | 322 | | } |
| | 323 | | } |