Skip to content

Commit

Permalink
Fix a possible crash when disposing ADS1115 device (#2345)
Browse files Browse the repository at this point in the history
* Fix a possible crash when disposing ADS1115 device

* Add extra sleep before retry
  • Loading branch information
pgrawehr authored Aug 23, 2024
1 parent 376398a commit 3f2c387
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 14 deletions.
46 changes: 33 additions & 13 deletions src/devices/Ads1115/Ads1115.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Device;
using System.Device.I2c;
using System.Device.Gpio;
using System.IO;
using UnitsNet;
using UnitsNet.Units;

Expand Down Expand Up @@ -261,19 +262,38 @@ private void SetConfig()
/// </summary>
private void DisableAlertReadyPin()
{
_comparatorQueue = ComparatorQueue.Disable;
SetConfig();
// Reset to defaults
Span<byte> writeBuff = stackalloc byte[3]
{
(byte)Register.ADC_CONFIG_REG_LO_THRESH, 0x80, 0
};
_i2cDevice.Write(writeBuff);
writeBuff = stackalloc byte[3]
{
(byte)Register.ADC_CONFIG_REG_HI_THRESH, 0x7F, 0xFF
};
_i2cDevice.Write(writeBuff);
bool success = false;
int retries = 3;
Span<byte> writeBuff = stackalloc byte[3];
while (!success)
{
// Retry this a few times, otherwise Dispose() may throw an exception, which is ugly.
try
{
_comparatorQueue = ComparatorQueue.Disable;
SetConfig();
// Reset to defaults
writeBuff[0] = (byte)Register.ADC_CONFIG_REG_LO_THRESH;
writeBuff[1] = 0x80;
writeBuff[2] = 0;
_i2cDevice.Write(writeBuff);
writeBuff[0] = (byte)Register.ADC_CONFIG_REG_HI_THRESH;
writeBuff[1] = 0x7F;
writeBuff[2] = 0xFF;
_i2cDevice.Write(writeBuff);
success = true;
}
catch (IOException)
{
if (retries-- < 0)
{
throw;
}

Thread.Sleep(100);
}
}

if (_gpioController is object)
{
_gpioController.UnregisterCallbackForPinValueChangedEvent(_gpioInterruptPin, ConversionReadyCallback);
Expand Down
2 changes: 1 addition & 1 deletion src/devices/Common/Iot/Device/Common/AngleExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public static Angle Normalize(this Angle self, bool toFullCircle)
/// <param name="currentTrack">First angle, actual direction</param>
/// <param name="destinationTrack">Second angle, desired direction</param>
/// <returns>The normalized result of <paramref name="currentTrack"/>-<paramref name="destinationTrack"/>. The value is negative if
/// the current track is to port (left) of the the desired track and positive otherwise</returns>
/// the current track is to port (left) of the desired track and positive otherwise</returns>
public static Angle Difference(Angle currentTrack, Angle destinationTrack)
{
double val = currentTrack.Radians - destinationTrack.Radians;
Expand Down

0 comments on commit 3f2c387

Please sign in to comment.