Skip to content

Commit

Permalink
Handle disconnects (#12)
Browse files Browse the repository at this point in the history
* fix autoconnect doing a disconnect if already connected

* Handle disconnections of the Arduino

* try to reconnect to CLS2Sim

* change version to 2.7.1

Co-authored-by: jmriego <[email protected]>
  • Loading branch information
jmriego and jmriego authored May 29, 2022
1 parent 6eb9c9e commit 8e55c88
Show file tree
Hide file tree
Showing 6 changed files with 93 additions and 42 deletions.
6 changes: 3 additions & 3 deletions BrunnerDX.Setup/BrunnerDX.Setup.vdproj
Original file line number Diff line number Diff line change
Expand Up @@ -5318,15 +5318,15 @@
{
"Name" = "8:Microsoft Visual Studio"
"ProductName" = "8:BrunnerDX.Setup"
"ProductCode" = "8:{A47FD9C1-5DA4-4B79-9F29-C6C174D472BE}"
"PackageCode" = "8:{217E8FC4-A469-4B3E-B9A9-135DB622D374}"
"ProductCode" = "8:{620C4BB5-5699-4D58-8207-75209A21C92A}"
"PackageCode" = "8:{D03D7947-19FC-4F11-A733-AB96F543FBE5}"
"UpgradeCode" = "8:{19C84E63-0F40-4FE1-8013-8E31D467EB4F}"
"AspNetVersion" = "8:2.0.50727.0"
"RestartWWWService" = "11:FALSE"
"RemovePreviousVersions" = "11:TRUE"
"DetectNewerInstalledVersion" = "11:TRUE"
"InstallAllUsers" = "11:FALSE"
"ProductVersion" = "8:2.7.0"
"ProductVersion" = "8:2.7.1"
"Manufacturer" = "8:jmriego"
"ARPHELPTELEPHONE" = "8:"
"ARPHELPLINK" = "8:https://github.com/jmriego/brunnerdx/issues"
Expand Down
60 changes: 39 additions & 21 deletions BrunnerDX/Arduino/RobustSerial.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.IO.Ports;

using NLog;
using System.Diagnostics;

namespace BrunnerDX
{
Expand All @@ -30,7 +31,7 @@ public class RobustSerial : IDisposable
Logger logger = LogManager.GetCurrentClassLogger();

SerialPort arduinoPort;
private bool _connected = false;
private bool _ready = false;
private int _semaphore = 10;

MessageReceivedEventHandler OnMessageReceived;
Expand All @@ -46,7 +47,6 @@ public RobustSerial(string port, MessageReceivedEventHandler onMessageReceived)
//arduinoPort.DtrEnable = true;

this.OnMessageReceived = onMessageReceived;
arduinoPort.DataReceived += DataReceivedHandler;
}

public void Dispose()
Expand All @@ -58,56 +58,74 @@ public void Dispose()

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
while (arduinoPort.BytesToRead > 0)
try
{
lock (arduinoPort)
while (arduinoPort.BytesToRead > 0)
{
Order ord = ReadOrder();
//logger.Debug($"Received order {ord}");
switch (ord)
{
case Order.HELLO:
case Order.ALREADY_CONNECTED:
_connected = true;
_ready = true;
break;
case Order.RECEIVED:
Interlocked.Increment(ref _semaphore);
break;
default:
try
lock (arduinoPort)
{
this.OnMessageReceived(ord, this);
}
catch (Exception ex)
{
logger.Error(ex, ex.Message);
}
break;
}
}
}
catch (Exception ex)
{
logger.Error(ex, ex.StackTrace);
logger.Error(ex, ex.Message);
}
}

public bool connected => _connected;
public int semaphore => _semaphore;
public bool ready => _ready; // This field indicates we have the COM port open and we have received a HELLO/ALREADY_CONNECTED from the Arduino
public int semaphore => _semaphore; // How many orders we can send before a RECEIVED confirmation
public bool IsOpen => arduinoPort.IsOpen;

public void WaitForConnection()
public void WaitForConnection(int timeout=1000)
{
lock (arduinoPort)
var awaitingArduinoWatch = new Stopwatch();
awaitingArduinoWatch.Start();
while (!arduinoPort.IsOpen)
{
if (!arduinoPort.IsOpen)
try
{
arduinoPort.Open();
}

logger.Info("Waiting for device...");
while (_connected)
catch (Exception ex) when (ex is System.IO.IOException)
{
WriteOrder(Order.HELLO);
System.Threading.Thread.Sleep(500);
if (awaitingArduinoWatch.ElapsedMilliseconds >= timeout) throw;
System.Threading.Thread.Sleep(1000);
}
logger.Info("Connected to device");
}

logger.Info("Waiting for device...");
arduinoPort.DataReceived += DataReceivedHandler;
while (!_ready) // Keep on sending HELLO until we receive a confirmation that will be read by DataReceivedHandler
{
WriteOrder(Order.HELLO);
System.Threading.Thread.Sleep(500);
}
logger.Info("Connected to device");
}

public void Close()
{
lock (arduinoPort)
{
_ready = false;
arduinoPort.Close();
}
}

Expand Down
46 changes: 34 additions & 12 deletions BrunnerDX/BrunnerDX.cs
Original file line number Diff line number Diff line change
Expand Up @@ -279,22 +279,44 @@ private void Communicate(RobustSerial arduinoPort, Cls2SimSocket brunnerSocket)
}

// send the current position to the Arduino
if (arduinoPort.semaphore >= 1 && ticksToNextPositionChange <= 0)
if (arduinoPort.ready)
{
arduinoPort.WriteOrder(Order.POSITION);
arduinoPort.WriteInt16(this.position[0]);
arduinoPort.WriteInt16(this.position[1]);
Interlocked.Exchange(ref ticksToNextPositionChange, (forcedArduinoCalculation / timerMs) + 1);
axisHasMoved[0] = false;
axisHasMoved[1] = false;
}
if (arduinoPort.semaphore >= 1 && ticksToNextPositionChange <= 0)
{
arduinoPort.WriteOrder(Order.POSITION);
arduinoPort.WriteInt16(this.position[0]);
arduinoPort.WriteInt16(this.position[1]);
Interlocked.Exchange(ref ticksToNextPositionChange, (forcedArduinoCalculation / timerMs) + 1);
axisHasMoved[0] = false;
axisHasMoved[1] = false;
}

if (arduinoPort.semaphore >= 1)
{
arduinoPort.WriteOrder(Order.FORCES);
if (arduinoPort.semaphore >= 1)
{
arduinoPort.WriteOrder(Order.FORCES);
}
}
}
}
catch (Exception ex) when (ex is System.IO.IOException)
{
logger.Error(ex, ex.StackTrace);
logger.Error(ex, ex.Message);
_isArduinoConnected = false;
arduinoPort.Close();
logger.Warn("Arduino disconnected. Trying to reconnect...");
arduinoPort.WaitForConnection(timeout: 5000);
_isArduinoConnected = true;
}
catch (Exception ex) when (ex is System.Net.Sockets.SocketException)
{
logger.Error(ex, ex.StackTrace);
logger.Error(ex, ex.Message);
_isBrunnerConnected = false;
logger.Warn("CLS2Sim disconnected. Trying to reconnect...");
_isBrunnerConnected = brunnerSocket.WaitForResponse(5);
if (!isBrunnerConnected) throw;
}
catch (Exception ex)
{
logger.Error(ex, ex.StackTrace);
Expand Down Expand Up @@ -375,7 +397,7 @@ public void loop()
var awaitingBrunnerWatch = new Stopwatch();
awaitingBrunnerWatch.Start();

while (arduinoPort.IsOpen && !stopExecuting)
while (!stopExecuting)
{
if (!_isBrunnerConnected && awaitingBrunnerWatch.IsRunning)
{
Expand Down
16 changes: 11 additions & 5 deletions BrunnerDX/BrunnerDXGui.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ private void BrunnerDXGui_Load(object sender, EventArgs e)

private void ConnectToggleBrunnerDX()
{
this.connectCountdownTicks = -1;
brunnerDX.cls2SimHost = this.options.ip;
brunnerDX.cls2SimPort = this.options.port;
brunnerDX.arduinoPortName = this.options.comPort;
Expand Down Expand Up @@ -432,18 +433,25 @@ private void refreshTimer_Tick(object sender, EventArgs e)
if (this.positionChart.Series[0].Points.Count > 1)
this.positionChart.Series[0].Points.RemoveAt(1);

if (brunnerDX.stopExecuting)
{
this.connectButton.Text = "Connect";
}
else
{
this.connectButton.Text = "Disconnect";
}

if (brunnerDX.isArduinoConnected)
{
this.arduinoStatus.BackColor = Color.Green;
this.forceChart.Series[0].Points.AddXY(brunnerDX.force[0], (double)-brunnerDX.force[1]);
this.connectButton.Text = "Disconnect";
if (this.waitingForMappingState != "") RemapBrunnerDXButton();
this.prevButtonsPressed = brunnerDX.buttons;
}
else
{
this.arduinoStatus.BackColor = brunnerDX.stopExecuting ? Color.Transparent : Color.Red;
this.connectButton.Text = "Connect";
}

if (brunnerDX.isBrunnerConnected)
Expand All @@ -464,9 +472,7 @@ private void refreshTimer_Tick(object sender, EventArgs e)
{
ConnectToggleBrunnerDX();
}
}

if (brunnerDX.stopExecuting &&
} else if (brunnerDX.stopExecuting &&
connectCountdownTicks < 0 &&
!brunnerDX.isArduinoConnected)
{
Expand Down
2 changes: 1 addition & 1 deletion BrunnerDX/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.7.0")]
[assembly: AssemblyVersion("2.7.1")]
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

## [2.7.1]

### Changed
- Automatically try to reconnect if there's any hiccup in the connection

## [2.7.0]

### Changed
Expand Down

0 comments on commit 8e55c88

Please sign in to comment.