Skip to content

Commit

Permalink
feat: add utility methods to send and wait for message asynchronously
Browse files Browse the repository at this point in the history
  • Loading branch information
Marco Bacis committed Jul 6, 2023
1 parent b6a9c7c commit 8bafa90
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 15 deletions.
70 changes: 61 additions & 9 deletions WeArtClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using System.Threading.Tasks;
using WeArt.Messages;
Expand Down Expand Up @@ -153,22 +154,26 @@ public Task Start(TrackingType trackingType = TrackingType.WEART_HAND)

// Send the request to start
SendMessage(new StartFromClientMessage { TrackingType = trackingType });

await Task.Delay(1000);

SendMessage(new GetMiddlewareStatusMessage());
SendMessage(new GetDevicesStatusMessage());

// Message receiving loop
while (!_cancellation.IsCancellationRequested)
{
if (ReceiveMessages(out var messages))
foreach (var message in messages)
OnMessageReceived(message);
}
}
catch (Exception e)
{
// Error handling and connection stop
OnError?.Invoke(ErrorType.ConnectionError, e);
StopConnection();
}

// Message receiving loop
while (!_cancellation.IsCancellationRequested)
{
if (ReceiveMessages(out var messages))
foreach (var message in messages)
OnMessageReceived(message);
}
}
}

// Connection stop
Expand All @@ -185,6 +190,7 @@ public Task Start(TrackingType trackingType = TrackingType.WEART_HAND)
public async Task<bool> Stop()
{
SendMessage(new StopFromClientMessage());
await SendAndWaitForMessage(new GetMiddlewareStatusMessage(), (MiddlewareStatusMessage msg) => msg.Status == MiddlewareStatus.IDLE, 3000);
StopConnection();
return true;
}
Expand Down Expand Up @@ -237,6 +243,52 @@ public void AskDevicesStatusUpdate()
SendMessage(new GetDevicesStatusMessage());
}

public async Task<T> SendAndWaitForMessage<T>(IWeArtMessage message, int timeoutMs)
{
return await SendAndWaitForMessage<T>(message, (T msg) => true, timeoutMs);
}

public async Task<T> SendAndWaitForMessage<T>(IWeArtMessage message, Func<T, bool> predicate, int timeoutMs)
{
// Write Pack and wait for responses (of a certain type) with a given timeout
CancellationTokenSource source = new CancellationTokenSource();

T receivedMessage = default(T);
Action<MessageType, IWeArtMessage> onMessageReceived = (MessageType type, IWeArtMessage msg) =>
{
if (type != MessageType.MessageReceived) return;
if (msg is T castedMessage)
{
if (predicate(castedMessage))
{
receivedMessage = castedMessage;
source.Cancel();
}
}
};

OnMessage += onMessageReceived;

SendMessage(message);

// Wait to receive message
try
{
await Task.Delay(timeoutMs, source.Token);
throw new TimeoutException();
}
catch (OperationCanceledException)
{
// Canceled operation means we received the correct message
}
finally
{
OnMessage -= onMessageReceived;
}

return receivedMessage;
}

/// <summary>
/// Waits for any message with the given type for the given timeout
/// </summary>
Expand Down
12 changes: 6 additions & 6 deletions WeArtMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -395,17 +395,17 @@ public enum MiddlewareStatus
public class MiddlewareStatusMessage : WeArtJsonMessage
{
[JsonConverter(typeof(StringEnumConverter))]
public MiddlewareStatus Status { get; set; }
public MiddlewareStatus Status { get; set; } = MiddlewareStatus.DISCONNECTED;

public string Version { get; set; }
public string Version { get; set; } = "";

public int StatusCode { get; set; }
public int StatusCode { get; set; } = 0;

public string ErrorDesc { get; set; }
public string ErrorDesc { get; set; } = "";

public bool ActuationsEnabled { get; set; }
public bool ActuationsEnabled { get; set; } = false;

public List<MiddlewareConnectedDevice> ConnectedDevices { get; set; }
public List<MiddlewareConnectedDevice> ConnectedDevices { get; set; } = new List<MiddlewareConnectedDevice>();

public override string ToString()
{
Expand Down

0 comments on commit 8bafa90

Please sign in to comment.