From 3f2c38725a70df7cdea02f2a7f8788a46eb32f93 Mon Sep 17 00:00:00 2001 From: Patrick Grawehr Date: Fri, 23 Aug 2024 08:05:12 +0200 Subject: [PATCH] Fix a possible crash when disposing ADS1115 device (#2345) * Fix a possible crash when disposing ADS1115 device * Add extra sleep before retry --- src/devices/Ads1115/Ads1115.cs | 46 +++++++++++++------ .../Iot/Device/Common/AngleExtensions.cs | 2 +- 2 files changed, 34 insertions(+), 14 deletions(-) diff --git a/src/devices/Ads1115/Ads1115.cs b/src/devices/Ads1115/Ads1115.cs index 54302550fa..d102a4d5f5 100644 --- a/src/devices/Ads1115/Ads1115.cs +++ b/src/devices/Ads1115/Ads1115.cs @@ -7,6 +7,7 @@ using System.Device; using System.Device.I2c; using System.Device.Gpio; +using System.IO; using UnitsNet; using UnitsNet.Units; @@ -261,19 +262,38 @@ private void SetConfig() /// private void DisableAlertReadyPin() { - _comparatorQueue = ComparatorQueue.Disable; - SetConfig(); - // Reset to defaults - Span 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 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); diff --git a/src/devices/Common/Iot/Device/Common/AngleExtensions.cs b/src/devices/Common/Iot/Device/Common/AngleExtensions.cs index 8cc75e1432..f20e9948d6 100644 --- a/src/devices/Common/Iot/Device/Common/AngleExtensions.cs +++ b/src/devices/Common/Iot/Device/Common/AngleExtensions.cs @@ -71,7 +71,7 @@ public static Angle Normalize(this Angle self, bool toFullCircle) /// First angle, actual direction /// Second angle, desired direction /// The normalized result of -. The value is negative if - /// the current track is to port (left) of the the desired track and positive otherwise + /// the current track is to port (left) of the desired track and positive otherwise public static Angle Difference(Angle currentTrack, Angle destinationTrack) { double val = currentTrack.Radians - destinationTrack.Radians;