From 79bc5f47830f67d4f29da63db8ae02776ee49152 Mon Sep 17 00:00:00 2001 From: Alexis Christoforides Date: Wed, 23 Oct 2024 11:34:58 -0400 Subject: [PATCH 1/4] Resolve debugger connection initialization issues --- .../SerialConnection.ListenerProc.cs | 64 ++++++++++------ .../Connections/SerialConnection.cs | 4 +- .../Debugging/DebuggingServer.ActiveClient.cs | 74 ++++++++----------- .../Meadow.HCom/Debugging/DebuggingServer.cs | 28 ++++--- 4 files changed, 85 insertions(+), 85 deletions(-) diff --git a/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs b/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs index 1b449d9c..d9c8a5d3 100644 --- a/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs +++ b/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs @@ -1,4 +1,4 @@ -namespace Meadow.Hcom +namespace Meadow.Hcom { public partial class SerialConnection { @@ -52,6 +52,34 @@ private async Task ListenerProc() var delimiter = new byte[] { 0x00 }; var receivedLength = 0; + async Task ReOpen() // local function + { + Debug.WriteLine($"Device reset detected"); + + var timeout = 20; + try { _port.Close(); } catch { } + + while (!_port.IsOpen) + { + await Task.Delay(500); + + if (timeout-- < 0) + { + return; + } + + try + { + Open(); + Debug.WriteLine($"Port re-opened"); + } + catch + { + Debug.WriteLine($"Failed to re-open port"); + } + } + } + while (!_isDisposed) { if (_port.IsOpen) @@ -64,32 +92,20 @@ private async Task ListenerProc() try { receivedLength = _port.Read(readBuffer, 0, readBuffer.Length); + if (receivedLength == 0) + { + Debug.WriteLine($"Received 0 bytes"); + throw new OperationCanceledException(); + } } catch (OperationCanceledException) { - Debug.WriteLine($"Device reset detected"); - - var timeout = 20; - - while (!_port.IsOpen) - { - await Task.Delay(500); - - if (timeout-- < 0) - { - return; - } - - try - { - Open(); - Debug.WriteLine($"Port re-opened"); - } - catch - { - Debug.WriteLine($"Failed to re-open port"); - } - } + await ReOpen(); + goto read; + } + catch (InvalidOperationException) + { + await ReOpen(); goto read; } diff --git a/Source/v2/Meadow.HCom/Connections/SerialConnection.cs b/Source/v2/Meadow.HCom/Connections/SerialConnection.cs index 452d93eb..ef37f8b5 100755 --- a/Source/v2/Meadow.HCom/Connections/SerialConnection.cs +++ b/Source/v2/Meadow.HCom/Connections/SerialConnection.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; using System.IO.Ports; using System.Security.Cryptography; @@ -1254,7 +1254,7 @@ public override async Task StartDebuggingSession(int port, ILog var debuggingServer = new DebuggingServer(this, port, logger); logger?.LogDebug("Tell the Debugging Server to Start Listening"); - _ = debuggingServer.StartListening(cancellationToken); + await debuggingServer.StartListening(cancellationToken); logger?.LogDebug($"Start Debugging on port: {port}"); await Device.StartDebugging(port, logger, cancellationToken); diff --git a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs index ce6cb7a2..9cdc77f1 100644 --- a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs +++ b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs @@ -1,4 +1,4 @@ -using System.Buffers; +using System.Buffers; using System.Collections.Concurrent; using System.Net.Sockets; using System.Security.Cryptography; @@ -10,17 +10,16 @@ public partial class DebuggingServer private class ActiveClient : IDisposable { private readonly IMeadowConnection _connection; - private readonly TcpClient _tcpClient; - private readonly NetworkStream _networkStream; + private TcpClient _tcpClient; + private NetworkStream _networkStream; private readonly CancellationTokenSource _cts; - private readonly Task _receiveVsDebugDataTask; - private readonly Task _receiveMeadowDebugDataTask; + private Task _receiveVsDebugDataTask; + private Task _receiveMeadowDebugDataTask; private readonly ILogger? _logger; private bool _disposed; private readonly BlockingCollection _debuggerMessages = new(); - private readonly AutoResetEvent _vsDebugDataReady = new(false); - internal ActiveClient(IMeadowConnection connection, TcpClient tcpClient, ILogger? logger, CancellationToken? cancellationToken) + internal ActiveClient(IMeadowConnection connection, ILogger? logger, CancellationToken? cancellationToken) { _cts = cancellationToken != null ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken.Value) @@ -28,13 +27,15 @@ internal ActiveClient(IMeadowConnection connection, TcpClient tcpClient, ILogger _logger = logger; _connection = connection; - _tcpClient = tcpClient; - _networkStream = tcpClient.GetStream(); + _connection.DebuggerMessageReceived += MeadowConnection_DebuggerMessageReceived; + } + public async Task Start(TcpListener tcpListener) + { + _tcpClient = await tcpListener.AcceptTcpClientAsync(); + _networkStream = _tcpClient.GetStream(); + _logger?.LogDebug("Starting receive task"); - - _connection.DebuggerMessageReceived += MeadowConnection_DebuggerMessageReceived; - _receiveVsDebugDataTask = Task.Factory.StartNew(SendToMeadowAsync, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); _receiveMeadowDebugDataTask = Task.Factory.StartNew(SendToVisualStudio, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } @@ -42,7 +43,6 @@ internal ActiveClient(IMeadowConnection connection, TcpClient tcpClient, ILogger private void MeadowConnection_DebuggerMessageReceived(object sender, byte[] e) { _debuggerMessages.Add(e); - _vsDebugDataReady.Set(); } private const int RECEIVE_BUFFER_SIZE = 256; @@ -51,9 +51,7 @@ private async Task SendToMeadowAsync() { try { - using var md5 = MD5.Create(); var receiveBuffer = ArrayPool.Shared.Rent(RECEIVE_BUFFER_SIZE); - var meadowBuffer = Array.Empty(); while (!_cts.Token.IsCancellationRequested) { @@ -69,13 +67,12 @@ private async Task SendToMeadowAsync() continue; } - var destIndex = meadowBuffer.Length; - Array.Resize(ref meadowBuffer, destIndex + bytesRead); - Array.Copy(receiveBuffer, 0, meadowBuffer, destIndex, bytesRead); + var meadowBuffer = new byte[bytesRead]; + Array.Copy(receiveBuffer, 0, meadowBuffer, 0, bytesRead); _logger?.LogTrace("Received {count} bytes from VS, will forward to HCOM/Meadow. {hash}", meadowBuffer.Length, - BitConverter.ToString(md5.ComputeHash(meadowBuffer)) + BitConverter.ToString(meadowBuffer) .Replace("-", string.Empty) .ToLowerInvariant()); @@ -83,7 +80,6 @@ private async Task SendToMeadowAsync() Debug.WriteLine($"ToMeadow: {BitConverter.ToString(meadowBuffer)}"); - meadowBuffer = Array.Empty(); } while (_networkStream.DataAvailable); } else @@ -96,12 +92,10 @@ private async Task SendToMeadowAsync() catch (IOException ioe) { _logger?.LogInformation("Visual Studio has Disconnected"); - _logger?.LogTrace(ioe, "Visual Studio has Disconnected"); } catch (ObjectDisposedException ode) { _logger?.LogInformation("Visual Studio has stopped debugging"); - _logger?.LogTrace(ode, "Visual Studio has stopped debugging"); } catch (Exception ex) { @@ -114,33 +108,25 @@ private async Task SendToVisualStudio() { try { - while (!_cts.Token.IsCancellationRequested) + while (!_cts.IsCancellationRequested) { - if (_networkStream != null && _networkStream.CanWrite) + byte[] byteData = null; + if (!_debuggerMessages.TryTake(out byteData, 500, _cts.Token)) { - _vsDebugDataReady.WaitOne(500); - - while (_debuggerMessages.Count > 0) - { - var byteData = _debuggerMessages.Take(_cts.Token); - - _logger?.LogTrace("Received {count} bytes from Meadow, will forward to VS", byteData.Length); - if (!_tcpClient.Connected) - { - _logger?.LogDebug("Cannot forward data, Visual Studio is not connected"); - return; - } - - await _networkStream.WriteAsync(byteData, 0, byteData.Length, _cts.Token); - _logger?.LogTrace("Forwarded {count} bytes to VS", byteData.Length); - - Debug.WriteLine($"ToVisStu: {BitConverter.ToString(byteData)}"); - } + Console.WriteLine("No data from Meadow"); + continue; } - else + + _logger?.LogTrace("Received {count} bytes from Meadow, will forward to VS", byteData.Length); + if (!_tcpClient.Connected || _networkStream == null || !_networkStream.CanWrite) { - _logger?.LogInformation("Unable to Write Data from Visual Studio"); + _logger?.LogDebug("Cannot forward data, Visual Studio is not connected"); + break; } + + await _networkStream.WriteAsync(byteData, 0, byteData.Length, _cts.Token); + _logger?.LogTrace("Forwarded {count} bytes to VS", byteData.Length); + Debug.WriteLine($"ToVisStu: {BitConverter.ToString(byteData)}"); } } catch (OperationCanceledException oce) diff --git a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.cs b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.cs index 1b359759..62418990 100644 --- a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.cs +++ b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.cs @@ -1,4 +1,4 @@ -using System.Net; +using System.Net; using System.Net.Sockets; namespace Meadow.Hcom; @@ -50,8 +50,7 @@ public async Task StartListening(CancellationToken cancellationToken) _logger?.LogInformation($"Listening for Visual Studio to connect"); // This call will wait for the client to connect, before continuing. - var tcpClient = await _listener.AcceptTcpClientAsync(); - _activeClient = CreateActiveClient(tcpClient); + _activeClient = await CreateActiveClient(_listener); } /// @@ -70,23 +69,22 @@ public async Task StopListening() } } - private ActiveClient? CreateActiveClient(TcpClient tcpClient) + private async Task CreateActiveClient(TcpListener listener) { try { - lock (_lck) + if (_activeClient != null) { - _logger?.LogInformation("Visual Studio has Connected" + Environment.NewLine); - - if (_activeClient != null) - { - _logger?.LogDebug("Closing active client"); - _activeClient?.Dispose(); - _activeClient = null; - } - - return new ActiveClient(_connection, tcpClient, _logger, _cancellationTokenSource?.Token); + _logger?.LogDebug("Closing active client"); + _activeClient?.Dispose(); + _activeClient = null; } + + + var client = new ActiveClient(_connection, _logger, _cancellationTokenSource?.Token); + await client.Start(listener); + _logger?.LogInformation("Debugger has connected" + Environment.NewLine); + return client; } catch (Exception ex) { From 29a4614f4141e834e7601cb61e6cb0d97035eb87 Mon Sep 17 00:00:00 2001 From: Adrian Stevens Date: Wed, 23 Oct 2024 13:44:23 -0700 Subject: [PATCH 2/4] Minor cleanup --- .../Debugging/DebuggingServer.ActiveClient.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs index 9cdc77f1..13dd559d 100644 --- a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs +++ b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs @@ -1,7 +1,6 @@ using System.Buffers; using System.Collections.Concurrent; using System.Net.Sockets; -using System.Security.Cryptography; namespace Meadow.Hcom; @@ -13,13 +12,13 @@ private class ActiveClient : IDisposable private TcpClient _tcpClient; private NetworkStream _networkStream; private readonly CancellationTokenSource _cts; - private Task _receiveVsDebugDataTask; - private Task _receiveMeadowDebugDataTask; + private Task _receiveVsDebugDataTask; + private Task _receiveMeadowDebugDataTask; private readonly ILogger? _logger; private bool _disposed; private readonly BlockingCollection _debuggerMessages = new(); - internal ActiveClient(IMeadowConnection connection, ILogger? logger, CancellationToken? cancellationToken) + internal ActiveClient(IMeadowConnection connection, ILogger? logger, CancellationToken? cancellationToken) { _cts = cancellationToken != null ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken.Value) @@ -27,14 +26,14 @@ internal ActiveClient(IMeadowConnection connection, ILogger? logger, Cancellati _logger = logger; _connection = connection; - _connection.DebuggerMessageReceived += MeadowConnection_DebuggerMessageReceived; + _connection.DebuggerMessageReceived += MeadowConnection_DebuggerMessageReceived; } public async Task Start(TcpListener tcpListener) { _tcpClient = await tcpListener.AcceptTcpClientAsync(); _networkStream = _tcpClient.GetStream(); - + _logger?.LogDebug("Starting receive task"); _receiveVsDebugDataTask = Task.Factory.StartNew(SendToMeadowAsync, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); _receiveMeadowDebugDataTask = Task.Factory.StartNew(SendToVisualStudio, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); From db60cbce97e3f08f0c31a4dd6c11df2a12bc8c60 Mon Sep 17 00:00:00 2001 From: Adrian Stevens Date: Fri, 25 Oct 2024 08:32:45 -0700 Subject: [PATCH 3/4] Bump version to v2.0.60.0 --- Source/v2/Meadow.Cli/Meadow.CLI.csproj | 2 +- Source/v2/Meadow.Cli/Properties/AssemblyInfo.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/v2/Meadow.Cli/Meadow.CLI.csproj b/Source/v2/Meadow.Cli/Meadow.CLI.csproj index af8572bb..7fad0a2f 100644 --- a/Source/v2/Meadow.Cli/Meadow.CLI.csproj +++ b/Source/v2/Meadow.Cli/Meadow.CLI.csproj @@ -10,7 +10,7 @@ Wilderness Labs, Inc Wilderness Labs, Inc true - 2.0.58.0 + 2.0.60.0 AnyCPU http://developer.wildernesslabs.co/Meadow/Meadow.CLI/ https://github.com/WildernessLabs/Meadow.CLI diff --git a/Source/v2/Meadow.Cli/Properties/AssemblyInfo.cs b/Source/v2/Meadow.Cli/Properties/AssemblyInfo.cs index dcd1693f..873026bf 100644 --- a/Source/v2/Meadow.Cli/Properties/AssemblyInfo.cs +++ b/Source/v2/Meadow.Cli/Properties/AssemblyInfo.cs @@ -6,5 +6,5 @@ namespace Meadow.CLI; public static class Constants { - public const string CLI_VERSION = "2.0.58.0"; + public const string CLI_VERSION = "2.0.60.0"; } \ No newline at end of file From 7a61ee8a8e30ca2e252d47fd1c8712e26ad39f00 Mon Sep 17 00:00:00 2001 From: Alexis Christoforides Date: Fri, 25 Oct 2024 13:01:44 -0400 Subject: [PATCH 4/4] More fixup --- .../Meadow.HCom/Connections/SerialConnection.ListenerProc.cs | 2 +- .../v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs b/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs index d9c8a5d3..e7433e33 100644 --- a/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs +++ b/Source/v2/Meadow.HCom/Connections/SerialConnection.ListenerProc.cs @@ -57,7 +57,7 @@ async Task ReOpen() // local function Debug.WriteLine($"Device reset detected"); var timeout = 20; - try { _port.Close(); } catch { } + try { _port.Close(); } catch { } // Swallow any exceptions on close - there is nothing we can do about it while (!_port.IsOpen) { diff --git a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs index 13dd559d..f25cb25d 100644 --- a/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs +++ b/Source/v2/Meadow.HCom/Debugging/DebuggingServer.ActiveClient.cs @@ -109,10 +109,8 @@ private async Task SendToVisualStudio() { while (!_cts.IsCancellationRequested) { - byte[] byteData = null; - if (!_debuggerMessages.TryTake(out byteData, 500, _cts.Token)) + if (!_debuggerMessages.TryTake(out var byteData, 500, _cts.Token)) { - Console.WriteLine("No data from Meadow"); continue; }