forked from equinor/flotilla
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMqttEventHandler.cs
More file actions
943 lines (842 loc) · 35.2 KB
/
Copy pathMqttEventHandler.cs
File metadata and controls
943 lines (842 loc) · 35.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using Api.Controllers.Models;
using Api.Database.Models;
using Api.Mqtt.MessageModels;
using Api.Services;
using Api.Services.ActionServices;
using Api.Services.Events;
using Api.Services.Models;
using Api.Utilities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
namespace Api.EventHandlers
{
/// <summary>
/// A background service which listens to events and performs callback functions.
/// </summary>
public class MqttEventHandler : EventHandlerBase
{
private readonly ILogger<MqttEventHandler> _logger;
private readonly IServiceScopeFactory _scopeFactory;
private readonly IMemoryCache _cache;
private EventAggregatorSingletonService _eventAggregatorSingletonService;
private readonly ConcurrentDictionary<string, RobotMetricData> _batteryMetrics = new();
private readonly ConcurrentDictionary<string, RobotMetricData> _pressureMetrics = new();
private record RobotMetricData(
float Value,
string RobotId,
string InstallationCode,
DateTimeOffset Timestamp
);
public MqttEventHandler(
ILogger<MqttEventHandler> logger,
IServiceScopeFactory scopeFactory,
IMemoryCache cache,
Meter meter,
EventAggregatorSingletonService eventAggregatorSingletonService
)
{
_logger = logger;
// Reason for using factory: https://www.thecodebuzz.com/using-dbcontext-instance-in-ihostedservice/
_scopeFactory = scopeFactory;
_cache = cache;
_eventAggregatorSingletonService = eventAggregatorSingletonService;
meter.CreateObservableGauge(
"robot.battery.level",
() =>
{
return _batteryMetrics.Select(kvp => new Measurement<float>(
kvp.Value.Value,
new KeyValuePair<string, object?>("robot.id", kvp.Value.RobotId),
new KeyValuePair<string, object?>(
"installation.code",
kvp.Value.InstallationCode
)
));
},
unit: "%",
description: "Current battery level of the robot"
);
meter.CreateObservableGauge(
"robot.pressure.level",
() =>
{
return _pressureMetrics.Select(kvp => new Measurement<float>(
kvp.Value.Value,
new KeyValuePair<string, object?>("robot.id", kvp.Value.RobotId),
new KeyValuePair<string, object?>(
"installation.code",
kvp.Value.InstallationCode
)
));
},
unit: "bar",
description: "Current pressure level of the robot"
);
Subscribe();
}
private IInspectionService InspectionService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<IInspectionService>();
private IInstallationService InstallationService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<IInstallationService>();
private ILastMissionRunService LastMissionRunService =>
_scopeFactory
.CreateScope()
.ServiceProvider.GetRequiredService<ILastMissionRunService>();
private IMissionRunService MissionRunService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<IMissionRunService>();
private IMissionSchedulingService MissionScheduling =>
_scopeFactory
.CreateScope()
.ServiceProvider.GetRequiredService<IMissionSchedulingService>();
private IMissionTaskService MissionTaskService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<IMissionTaskService>();
private IRobotService RobotService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<IRobotService>();
private ISignalRService SignalRService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<ISignalRService>();
private ITaskDurationService TaskDurationService =>
_scopeFactory.CreateScope().ServiceProvider.GetRequiredService<ITaskDurationService>();
public override void Subscribe()
{
_eventAggregatorSingletonService.Subscribe<IsarStatusMessage>(OnIsarStatus);
_eventAggregatorSingletonService.Subscribe<IsarRobotInfoMessage>(OnIsarRobotInfo);
_eventAggregatorSingletonService.Subscribe<IsarMissionMessage>(OnIsarMissionUpdate);
_eventAggregatorSingletonService.Subscribe<IsarTaskMessage>(OnIsarTaskUpdate);
_eventAggregatorSingletonService.Subscribe<IsarBatteryMessage>(OnIsarBatteryUpdate);
_eventAggregatorSingletonService.Subscribe<IsarPressureMessage>(OnIsarPressureUpdate);
_eventAggregatorSingletonService.Subscribe<IsarPoseMessage>(OnIsarPoseUpdate);
_eventAggregatorSingletonService.Subscribe<IsarCloudHealthMessage>(
OnIsarCloudHealthUpdate
);
_eventAggregatorSingletonService.Subscribe<IsarInterventionNeededMessage>(
OnIsarInterventionNeededUpdate
);
_eventAggregatorSingletonService.Subscribe<IsarStartupMessage>(OnIsarStartup);
_eventAggregatorSingletonService.Subscribe<IsarMissionAbortedMessage>(
OnIsarMissionAborted
);
_eventAggregatorSingletonService.Subscribe<SaraInspectionResultMessage>(
OnSaraInspectionResultUpdate
);
_eventAggregatorSingletonService.Subscribe<SaraAnalysisResultMessage>(
OnSaraAnalysisResultMessage
);
}
public override void Unsubscribe() { }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await stoppingToken;
}
private async void OnIsarStatus(IsarStatusMessage isarStatus)
{
var robot = await RobotService.ReadByIsarId(isarStatus.IsarId, readOnly: true);
if (robot == null)
{
_logger.LogInformation(
"Received message from unknown ISAR instance {Id} with robot name {Name}",
isarStatus.IsarId,
isarStatus.RobotName
);
return;
}
if (robot.Status == isarStatus.Status)
{
return;
}
_logger.LogInformation(
"OnIsarStatus: Robot {robotName} has status {robotStatus} and current inspection area id {areaId}",
robot.Name,
robot.Status,
robot.CurrentInspectionAreaId
);
await RobotService.UpdateRobotStatus(robot.Id, isarStatus.Status);
robot.Status = isarStatus.Status;
_logger.LogInformation(
"Updated status for robot {Name} to {Status}",
robot.Name,
robot.Status
);
_logger.LogInformation(
"OnIsarStatus: Robot {robotName} has status {robotStatus} and current inspection area id {areaId}",
robot.Name,
robot.Status,
robot.CurrentInspectionAreaId
);
if (Robot.IsStatusThatCanReceiveMissions(isarStatus.Status))
{
_eventAggregatorSingletonService.Publish(new RobotReadyForMissionsEventArgs(robot));
}
}
private async void CreateRobot(
IsarRobotInfoMessage isarRobotInfo,
Installation installation
)
{
_logger.LogInformation(
"Received message from new ISAR instance '{Id}' with robot name '{Name}'. Adding new robot to database",
isarRobotInfo.IsarId,
isarRobotInfo.RobotName
);
var robotQuery = new CreateRobotQuery
{
IsarId = isarRobotInfo.IsarId,
Name = isarRobotInfo.RobotName,
RobotType = isarRobotInfo.RobotType,
SerialNumber = isarRobotInfo.SerialNumber,
CurrentInstallationCode = installation.InstallationCode,
Documentation = isarRobotInfo.DocumentationQueries,
Host = isarRobotInfo.Host,
Port = isarRobotInfo.Port,
RobotCapabilities = isarRobotInfo.Capabilities,
Status = RobotStatus.Available,
};
try
{
var newRobot = await RobotService.CreateFromQuery(robotQuery);
_logger.LogInformation(
"Added robot '{RobotName}' with ISAR id '{IsarId}' to database",
newRobot.Name,
newRobot.IsarId
);
}
catch (DbUpdateException)
{
_logger.LogError(
"Failed to add robot {robotQueryName} with to the database",
robotQuery.Name
);
}
}
private async void OnIsarRobotInfo(IsarRobotInfoMessage isarRobotInfo)
{
var installation = await InstallationService.ReadByInstallationCode(
isarRobotInfo.CurrentInstallation,
readOnly: true
);
if (installation is null)
{
_logger.LogError(
new InstallationNotFoundException(
$"No installation with code {isarRobotInfo.CurrentInstallation} found"
),
"Could not create new robot due to missing installation"
);
return;
}
try
{
var robot = await RobotService.ReadByIsarId(isarRobotInfo.IsarId, readOnly: true);
if (robot == null)
{
CreateRobot(isarRobotInfo, installation);
return;
}
List<string> updatedFields = [];
if (isarRobotInfo.Host is not null)
UpdateHostIfChanged(isarRobotInfo.Host, ref robot, ref updatedFields);
UpdatePortIfChanged(isarRobotInfo.Port, ref robot, ref updatedFields);
if (isarRobotInfo.CurrentInstallation is not null)
UpdateCurrentInstallationIfChanged(installation, ref robot, ref updatedFields);
if (isarRobotInfo.Capabilities is not null)
UpdateRobotCapabilitiesIfChanged(
isarRobotInfo.Capabilities,
ref robot,
ref updatedFields
);
if (updatedFields.Count < 1)
return;
await RobotService.Update(robot);
_logger.LogInformation(
"Updated robot '{Id}' ('{RobotName}') in database: {Updates}",
robot.Id,
robot.Name,
updatedFields
);
}
catch (DbUpdateException e)
{
_logger.LogError(e, "Could not add robot to db");
}
catch (Exception e)
{
_logger.LogError(e, "Could not update robot in db");
}
}
private static void UpdateHostIfChanged(
string host,
ref Robot robot,
ref List<string> updatedFields
)
{
if (host.Equals(robot.Host, StringComparison.Ordinal))
return;
updatedFields.Add($"\nHost ({robot.Host} -> {host})\n");
robot.Host = host;
}
private static void UpdatePortIfChanged(
int port,
ref Robot robot,
ref List<string> updatedFields
)
{
if (port.Equals(robot.Port))
return;
updatedFields.Add($"\nPort ({robot.Port} -> {port})\n");
robot.Port = port;
}
private static void UpdateCurrentInstallationIfChanged(
Installation newCurrentInstallation,
ref Robot robot,
ref List<string> updatedFields
)
{
if (
newCurrentInstallation.InstallationCode.Equals(
robot.CurrentInstallation?.InstallationCode,
StringComparison.Ordinal
)
)
return;
updatedFields.Add(
$"\nCurrentInstallation ({robot.CurrentInstallation} -> {newCurrentInstallation})\n"
);
robot.CurrentInstallation = newCurrentInstallation;
}
public static void UpdateRobotCapabilitiesIfChanged(
IList<RobotCapabilitiesEnum> newRobotCapabilities,
ref Robot robot,
ref List<string> updatedFields
)
{
if (
robot.RobotCapabilities != null
&& Enumerable.SequenceEqual(newRobotCapabilities, robot.RobotCapabilities)
)
return;
updatedFields.Add(
$"\nRobotCapabilities ({robot.RobotCapabilities} -> {newRobotCapabilities})\n"
);
robot.RobotCapabilities = newRobotCapabilities;
}
private async void OnIsarMissionAborted(IsarMissionAbortedMessage isarAbortedMission)
{
var robot = await RobotService.ReadByIsarId(isarAbortedMission.IsarId, readOnly: true);
if (robot is null)
{
_logger.LogError(
"Could not find robot '{RobotName}' with ISAR id '{IsarId}'",
isarAbortedMission.RobotName,
isarAbortedMission.IsarId
);
return;
}
try
{
var missionRun = await MissionScheduling.MoveMissionRunBackToQueue(
robot.Id,
isarAbortedMission.MissionId,
isarAbortedMission.Reason
);
_logger.LogInformation(
"Mission '{Id}' (ISARMissionID='{IsarMissionId}') was aborted by ISAR for robot '{RobotName}' with ISAR id '{IsarId}': {Reason}",
missionRun.Id,
isarAbortedMission.MissionId,
isarAbortedMission.RobotName,
isarAbortedMission.IsarId,
isarAbortedMission.Reason
);
}
catch (NoUnfinishedTasksInMissionException) { }
catch (RobotNotFoundException)
{
_logger.LogWarning(
"Mission with ISAR ID '{IsarMissionId}' was aborted by ISAR with ISAR id '{IsarId}' but that robot could not be found: {Reason}",
isarAbortedMission.MissionId,
isarAbortedMission.IsarId,
isarAbortedMission.Reason
);
}
catch (MissionRunNotFoundException)
{
_logger.LogWarning(
"Mission with ISAR ID '{IsarMissionId}' was aborted by ISAR with ISAR id '{IsarId}' but could not be found: {Reason}",
isarAbortedMission.MissionId,
isarAbortedMission.IsarId,
isarAbortedMission.Reason
);
}
catch (Exception e)
{
_logger.LogError(
"Mission with ISAR ID '{IsarMissionId}' was aborted by ISAR with ISAR id '{IsarId}' but an unhandled exception occured: {Reason}",
isarAbortedMission.MissionId,
isarAbortedMission.IsarId,
e.StackTrace
);
}
}
private async void OnIsarMissionUpdate(IsarMissionMessage isarMission)
{
MissionStatus status;
try
{
status = MissionRun.GetMissionStatusFromString(isarMission.Status);
}
catch (ArgumentException e)
{
_logger.LogError(
e,
"Failed to parse mission status from MQTT message. Mission with ISARMissionId '{IsarMissionId}' was not updated",
isarMission.MissionId
);
return;
}
var flotillaMissionRun = await MissionRunService.ReadById(
isarMission.MissionId,
readOnly: true,
includeDeprecated: true
);
if (flotillaMissionRun is null)
{
_logger.LogInformation(
$"Mission with isar mission Id {isarMission.MissionId} was not found. This is expected if the mission is a return home mission."
);
var isarRobot = await RobotService.ReadByIsarId(isarMission.IsarId, readOnly: true);
// Check if return home mission fails
if (status == MissionStatus.Failed && isarRobot != null)
{
string errorDescription =
isarMission.ErrorDescription ?? "The initiated mission failed";
string reportMessage = $"Failed mission for robot {isarRobot.Name}";
SignalRService.ReportGeneralFailToSignalR(
isarRobot,
reportMessage,
errorDescription
);
}
return;
}
if (
flotillaMissionRun.Status == MissionStatus.Aborted
&& status == MissionStatus.Cancelled
)
status = MissionStatus.Aborted;
// Handle that mission_status only reflects last part of mission if recharging occurred during mission
if (
status == MissionStatus.Successful
&& flotillaMissionRun.Tasks.Any(task =>
task.Status == Database.Models.TaskStatus.Failed
)
)
status = MissionStatus.PartiallySuccessful;
else if (
status == MissionStatus.Failed
&& flotillaMissionRun.Tasks.Any(task =>
task.Status == Database.Models.TaskStatus.Successful
)
)
status = MissionStatus.PartiallySuccessful;
MissionRun updatedFlotillaMissionRun;
try
{
if (flotillaMissionRun.IsDeprecated)
{
updatedFlotillaMissionRun = await MissionRunService.UpdateMissionRunProperty(
isarMission.MissionId,
"IsDeprecated",
false,
includeDeprecated: true
);
_logger.LogInformation(
$"Mission with isar mission Id {isarMission.MissionId} was deprecated on mission updated, setting to not deprecated."
);
}
if (isarMission.ErrorDescription?.Length >= 450)
{
_logger.LogInformation(
$"Mission with isar mission Id {isarMission.MissionId} got error description: {isarMission.ErrorDescription} from ISAR. This text is more than 450 char and will be shorted down."
);
isarMission.ErrorDescription =
isarMission.ErrorDescription.Substring(0, 446) + "...";
}
updatedFlotillaMissionRun = await MissionRunService.UpdateMissionRunStatus(
isarMission.MissionId,
status,
isarMission.ErrorDescription
);
}
catch (MissionRunNotFoundException)
{
return;
}
_logger.LogInformation(
"Mission '{Id}' (ISARMissionID='{IsarMissionId}') status updated to '{Status}' for robot '{RobotName}' with ISAR id '{IsarId}'",
updatedFlotillaMissionRun.Id,
isarMission.MissionId,
isarMission.Status,
isarMission.RobotName,
isarMission.IsarId
);
var robot = await RobotService.ReadByIsarId(isarMission.IsarId, readOnly: true);
if (robot is null)
{
_logger.LogError(
"Could not find robot '{RobotName}' with ISAR id '{IsarId}'",
isarMission.RobotName,
isarMission.IsarId
);
return;
}
if (!updatedFlotillaMissionRun.IsCompleted)
{
await RobotService.UpdateCurrentMissionId(robot.Id, updatedFlotillaMissionRun.Id);
robot.CurrentMissionId = updatedFlotillaMissionRun.Id;
return;
}
_logger.LogInformation(
"Robot '{Id}' ('{Name}') - completed mission run {MissionRunId}",
robot.IsarId,
robot.Name,
updatedFlotillaMissionRun.Id
);
if (robot.CurrentMissionId == flotillaMissionRun.Id)
{
await RobotService.UpdateCurrentMissionId(robot.Id, null);
robot.CurrentMissionId = null;
}
try
{
await LastMissionRunService.SetLastMissionRun(
updatedFlotillaMissionRun.Id,
updatedFlotillaMissionRun.MissionId
);
}
catch (MissionNotFoundException)
{
_logger.LogError(
"Mission not found when setting last mission run for mission definition {missionId}",
updatedFlotillaMissionRun.MissionId
);
return;
}
await TaskDurationService.UpdateAverageDurationPerTask(robot);
}
private async void OnIsarTaskUpdate(IsarTaskMessage task)
{
IsarTaskStatus status;
try
{
status = IsarTask.StatusFromString(task.Status);
}
catch (ArgumentException e)
{
_logger.LogError(
e,
"Failed to parse mission status from MQTT message. Mission '{Id}' was not updated",
task.MissionId
);
return;
}
if (!task.IsInspectionTask(task.TaskType))
{
_logger.LogInformation(
"Received status update to status {status} for task of type {taskType}. As this is not an inspection task, the task update will be disregarded.",
status,
task.TaskType
);
return;
}
MissionTask missionTask;
try
{
missionTask = await MissionTaskService.UpdateMissionTaskStatus(
task.TaskId,
status,
task.ErrorDescription
);
}
catch (MissionTaskNotFoundException)
{
return;
}
var missionRun = await MissionRunService.ReadById(task.MissionId, readOnly: true);
if (missionRun is null)
{
_logger.LogWarning("Mission run with ID {Id} was not found", task.MissionId);
return;
}
_ = SignalRService.SendMessageAsync(
"Mission run updated",
missionRun.InspectionArea.Installation,
new MissionRunResponse(missionRun)
);
_logger.LogInformation(
"Task '{Id}' updated to '{Status}' for robot '{RobotName}' with ISAR id '{IsarId}'",
task.TaskId,
task.Status,
task.RobotName,
task.IsarId
);
}
private async Task<(string, string)?> GetRobotInstallationCodeAndId(string robotIsarId)
{
if (!_cache.TryGetValue(robotIsarId, out (string, string)? installationCodeAndId))
{
var robot = await RobotService.ReadByIsarId(robotIsarId);
if (robot == null)
return null;
var cacheEntryOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1),
};
_cache.Set(
robotIsarId,
(robot.CurrentInstallation.InstallationCode, robot.Id),
cacheEntryOptions
);
installationCodeAndId = (robot.CurrentInstallation.InstallationCode, robot.Id);
}
return installationCodeAndId;
}
private async void OnIsarBatteryUpdate(IsarBatteryMessage batteryStatus)
{
(string installationCode, string robotId)? installationCodeAndId =
await GetRobotInstallationCodeAndId(batteryStatus.IsarId);
if (installationCodeAndId == null)
return;
_batteryMetrics[batteryStatus.IsarId] = new RobotMetricData(
batteryStatus.BatteryLevel,
installationCodeAndId.Value.robotId,
installationCodeAndId.Value.installationCode,
DateTimeOffset.UtcNow
);
await SignalRService.SendMessageAsync(
"Robot telemetry updated",
installationCodeAndId.Value.installationCode,
new UpdateRobotTelemetryMessage
{
RobotId = installationCodeAndId.Value.robotId,
TelemetryName = "batteryState",
TelemetryValue = batteryStatus.BatteryState,
}
);
await SignalRService.SendMessageAsync(
"Robot telemetry updated",
installationCodeAndId.Value.installationCode,
new UpdateRobotTelemetryMessage
{
RobotId = installationCodeAndId.Value.robotId,
TelemetryName = "batteryLevel",
TelemetryValue = batteryStatus.BatteryLevel,
}
);
}
private async void OnIsarPressureUpdate(IsarPressureMessage pressureStatus)
{
(string installationCode, string robotId)? installationCodeAndId =
await GetRobotInstallationCodeAndId(pressureStatus.IsarId);
if (installationCodeAndId == null)
return;
_pressureMetrics[pressureStatus.IsarId] = new RobotMetricData(
pressureStatus.PressureLevel,
installationCodeAndId.Value.robotId,
installationCodeAndId.Value.installationCode,
DateTimeOffset.UtcNow
);
await SignalRService.SendMessageAsync(
"Robot telemetry updated",
installationCodeAndId.Value.installationCode,
new UpdateRobotTelemetryMessage
{
RobotId = installationCodeAndId.Value.robotId,
TelemetryName = "pressureLevel",
TelemetryValue = pressureStatus.PressureLevel,
}
);
}
private async void OnIsarPoseUpdate(IsarPoseMessage poseStatus)
{
(string installationCode, string robotId)? installationCodeAndId =
await GetRobotInstallationCodeAndId(poseStatus.IsarId);
if (installationCodeAndId == null)
return;
var pose = new Pose(poseStatus.Pose);
await SignalRService.SendMessageAsync(
"Robot telemetry updated",
installationCodeAndId.Value.installationCode,
new UpdateRobotTelemetryMessage
{
RobotId = installationCodeAndId.Value.robotId,
TelemetryName = "pose",
TelemetryValue = pose,
}
);
}
private async void OnIsarCloudHealthUpdate(IsarCloudHealthMessage cloudHealthStatus)
{
var robot = await RobotService.ReadByIsarId(cloudHealthStatus.IsarId, readOnly: true);
if (robot == null)
{
_logger.LogInformation(
"Received message from unknown ISAR instance {Id} with robot name {Name}",
cloudHealthStatus.IsarId,
cloudHealthStatus.RobotName
);
return;
}
string message = $"Failed telemetry request for robot {cloudHealthStatus.RobotName}.";
_eventAggregatorSingletonService.Publish(new TeamsMessageEventArgs(message));
}
private async void OnIsarInterventionNeededUpdate(
IsarInterventionNeededMessage interventionNeededMessage
)
{
var robot = await RobotService.ReadByIsarId(
interventionNeededMessage.IsarId,
readOnly: true
);
if (robot == null)
{
_logger.LogInformation(
"Received message from unknown ISAR instance {Id} with robot name {Name}",
interventionNeededMessage.IsarId,
interventionNeededMessage.RobotName
);
return;
}
string message =
$"Intervention needed for robot {interventionNeededMessage.RobotName}. "
+ $"Reason: {interventionNeededMessage.Reason}";
_eventAggregatorSingletonService.Publish(new TeamsMessageEventArgs(message));
}
private async void OnIsarStartup(IsarStartupMessage startupMessage)
{
var robot = await RobotService.ReadByIsarId(startupMessage.IsarId, readOnly: true);
if (robot == null)
{
_logger.LogInformation(
"Received message from unknown ISAR instance {Id}",
startupMessage.IsarId
);
return;
}
_logger.LogInformation(
"Received ISAR restart event for robot {robotName} with ISAR id {isarId}.",
robot.Name,
robot.IsarId
);
var missionToAbort = robot.CurrentMissionId;
if (missionToAbort == null)
{
_logger.LogInformation(
"Robot {robotName} with ISAR id {isarId} has no ongoing mission. No action required.",
robot.Name,
robot.IsarId
);
return;
}
try
{
var missionRun = await MissionScheduling.MoveMissionRunBackToQueue(
robot.Id,
missionToAbort,
"Isar restarted during mission"
);
_logger.LogInformation(
"Mission with id '{Id}' was aborted for robot '{RobotName}' due to ISAR restart",
missionRun.Id,
robot.Name
);
}
catch (NoUnfinishedTasksInMissionException) { }
catch (RobotNotFoundException)
{
_logger.LogWarning(
"Could not find robot with id {RobotId} when attempting to abort mission '{MissionToAbort}' due to isar restart",
robot.Id,
missionToAbort
);
}
catch (MissionRunNotFoundException)
{
_logger.LogWarning(
"Could not find mission with id {MissionToAbort} when attempting to abort mission due to isar restart",
missionToAbort
);
}
catch (Exception e)
{
_logger.LogError(
"An unhandled exception occured when attempting to abort mission with id {MissionToAbort} on robot {RobotId} due to isar restart. Error message: {StackTrace}",
missionToAbort,
robot.Id,
e.StackTrace
);
}
}
private async void OnSaraInspectionResultUpdate(
SaraInspectionResultMessage inspectionResult
)
{
var inspectionResultMessage = new InspectionResultMessage
{
InspectionId = inspectionResult.InspectionId,
};
var missionRun = await MissionRunService.ReadByTaskId(
inspectionResult.InspectionId,
readOnly: true
);
var installation = missionRun?.InspectionArea?.Installation;
if (installation == null)
{
_logger.LogError(
"Installation could not be found when processing SARA inspection result update with inspection ID {InspectionId}",
inspectionResult.InspectionId
);
return;
}
_ = SignalRService.SendMessageAsync(
"Inspection Visulization Ready",
installation,
inspectionResultMessage
);
}
private async void OnSaraAnalysisResultMessage(SaraAnalysisResultMessage saraAnalysisResult)
{
if (saraAnalysisResult.InspectionIds.Count == 0)
{
_logger.LogError(
"SARA analysis result message contained no inspection IDs; skipping"
);
return;
}
// TODO: SARA may emit multiple inspection IDs for group analyses
// (e.g. results derived from several inspections). For now we only
// persist the result against the first ID; future work should iterate
// the full list and emit one persist + SignalR event per inspection.
var inspectionId = saraAnalysisResult.InspectionIds[0];
var missionRun = await MissionRunService.ReadByTaskId(inspectionId, readOnly: true);
var installation = missionRun?.InspectionArea?.Installation;
if (installation == null)
{
_logger.LogError(
"Installation could not found when processing SARA analysis result update with inspection ID {inspectionId}",
inspectionId
);
return;
}
_ = SignalRService.SendMessageAsync(
"Analysis Result Ready",
installation,
new AnalysisResultMessage()
{
InspectionId = inspectionId,
AnalysisType = saraAnalysisResult.AnalysisType,
InstallationCode = installation.InstallationCode,
}
);
}
}
}