Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Commit

Permalink
Make sure client returns error when network is lost (#144)
Browse files Browse the repository at this point in the history
  • Loading branch information
helto4real authored Jan 21, 2022
1 parent 783a3fc commit f32d105
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
"profiles": {
"HassClient.Performance.Tests": {
"commandName": "Project",
"commandLineArgs": "-c --ip 192.168.1.7 --port 8123 --events true --token \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIzY2U4ZDdmMjg5NTc0MDY4YjA5Nzk2ZGMyZmNjYWI3NCIsImlhdCI6MTU3OTY3MTA2MywiZXhwIjoxODk1MDMxMDYzfQ.MuQTEYy9HDkV62GzY6fX9ECn_U8vFd5ffashw3sz_3M\""
"commandLineArgs": "-c --ip 192.168.1.7 --port 8123 --events true --token \"token\"",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT":"Development"
},
}
}
}
7 changes: 4 additions & 3 deletions src/HassClient/Client/HassClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -798,10 +798,11 @@ public async Task<IReadOnlyCollection<HassEntity>> GetEntities()
/// </remarks>
internal virtual async Task ProcessNextMessage()
{
if (_messagePipeline is null)
if (_messagePipeline is null || !_messagePipeline.IsValid)
{
_logger.LogWarning("Processing message with no {Pipeline} set! returning.", nameof(_messagePipeline));
return;
if (!CancelSource.IsCancellationRequested)
CancelSource.Cancel(); // Cancels all operations on a faulty pipeline
throw new InvalidOperationException($"Processing message fail.");
}

try
Expand Down
21 changes: 20 additions & 1 deletion src/HassClient/Client/internal/WebSocketMessagePipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,24 @@ private async Task ReadMessagePump()
// Canceled the thread just leave
break;
}
catch (Exception e)
{
_logger.LogTrace(e, "Websocket error");
try
{
await _ws.CloseAsync(WebSocketCloseStatus.EndpointUnavailable, "Remote disconnected",
_internalCancelToken).ConfigureAwait(false);
}
catch
{
// Suppress any error
}
finally
{
_internalCancellationSource.Cancel();
}
break;
}
finally
{
// Always make sure the pipe is reset and ready to use next process message
Expand Down Expand Up @@ -326,7 +344,8 @@ async Task ReadFromClientSocket()
await SendCloseFrameToWebSocket().ConfigureAwait(false);

// Cancel so the write thread is canceled before pipe is complete
_internalCancellationSource.Cancel();
if (!_internalCancellationSource.IsCancellationRequested)
_internalCancellationSource.Cancel();
}

// Continue reading next part of websocket message
Expand Down

0 comments on commit f32d105

Please sign in to comment.