Skip to content

Commit

Permalink
Wait for possible multiple state updates when verifying robot type
Browse files Browse the repository at this point in the history
  • Loading branch information
DoctorMcKay committed Aug 9, 2023
1 parent f72e6f5 commit 2fe4c4c
Showing 1 changed file with 25 additions and 5 deletions.
30 changes: 25 additions & 5 deletions IRobotLANClient/RobotVerifierClient.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
using System.Threading.Tasks;
using IRobotLANClient.Enums;
using System.Timers;
using Newtonsoft.Json;

namespace IRobotLANClient {
public class RobotVerifierClient : RobotClient {
public RobotType DetectedType { get; private set; } = RobotType.Unrecognized;

private TaskCompletionSource<RobotType> _taskCompletionSource;
private bool _receivedStateUpdate = false;

public RobotVerifierClient(string address, string blid, string password) : base(address, blid, password) { }

Expand All @@ -15,17 +17,27 @@ public override bool IsCorrectRobotType() {
}

protected override void HandleRobotStateUpdate() {
DetectedType = RobotType.Unrecognized;
_receivedStateUpdate = true;

DetectedType = AttemptDetectType();
if (DetectedType != RobotType.Unrecognized) {
// Only complete the task if we were actually able to detect the robot type
// Otherwise, wait for more data
_taskCompletionSource.TrySetResult(DetectedType);
}
}

private RobotType AttemptDetectType() {
if (ReportedState.ContainsKey("bin")) {
DetectedType = RobotType.Vacuum;
return RobotType.Vacuum;
}

if (ReportedState.ContainsKey("mopReady") || ReportedState.ContainsKey("tankPresent")) {
DetectedType = RobotType.Mop;
return RobotType.Mop;
}

_taskCompletionSource.TrySetResult(DetectedType);
DebugOutput("Call to AttemptDetectType() returned RobotType.Unrecognized - " + JsonConvert.SerializeObject(ReportedState));
return RobotType.Unrecognized;
}

public Task<RobotType> WaitForDetectedType() {
Expand All @@ -34,7 +46,15 @@ public Task<RobotType> WaitForDetectedType() {
Timer timeout = new Timer {Enabled = true, AutoReset = false, Interval = 10000};
timeout.Elapsed += (sender, args) => {
timeout.Dispose();
_taskCompletionSource.TrySetCanceled();
DebugOutput($"WaitForDetectedType() elapsed. _receivedStateUpdate = {_receivedStateUpdate}");
if (_receivedStateUpdate) {
// If we received any data at all, complete task with robot type Unrecognized
_taskCompletionSource.TrySetResult(AttemptDetectType());
} else {
// We never received a single state update, so cancel the task to report timeout
_taskCompletionSource.TrySetCanceled();
}
};

return _taskCompletionSource.Task;
Expand Down

0 comments on commit 2fe4c4c

Please sign in to comment.