diff --git a/src/devices/Ads1115/Ads1115.cs b/src/devices/Ads1115/Ads1115.cs
index 766d95e6fa..54302550fa 100644
--- a/src/devices/Ads1115/Ads1115.cs
+++ b/src/devices/Ads1115/Ads1115.cs
@@ -47,8 +47,8 @@ public class Ads1115 : IDisposable
/// Programmable Gain Amplifier
/// Data Rate
/// Initial device mode
- public Ads1115(I2cDevice i2cDevice, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096, DataRate dataRate = DataRate.SPS128,
- DeviceMode deviceMode = DeviceMode.Continuous)
+ public Ads1115(I2cDevice i2cDevice, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096,
+ DataRate dataRate = DataRate.SPS128, DeviceMode deviceMode = DeviceMode.Continuous)
{
_i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_inputMultiplexer = inputMultiplexer;
@@ -61,7 +61,6 @@ public Ads1115(I2cDevice i2cDevice, InputMultiplexer inputMultiplexer = InputMul
_comparatorPolarity = ComparatorPolarity.Low;
_comparatorLatching = ComparatorLatching.NonLatching;
_comparatorQueue = ComparatorQueue.Disable;
- _shouldDispose = false;
SetConfig();
DisableAlertReadyPin();
@@ -79,18 +78,18 @@ public Ads1115(I2cDevice i2cDevice, InputMultiplexer inputMultiplexer = InputMul
/// Data Rate
/// Initial device mode
public Ads1115(I2cDevice i2cDevice,
- GpioController gpioController, int gpioInterruptPin, bool shouldDispose = true, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096, DataRate dataRate = DataRate.SPS128,
- DeviceMode deviceMode = DeviceMode.Continuous)
+ GpioController? gpioController, int gpioInterruptPin, bool shouldDispose = true, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096,
+ DataRate dataRate = DataRate.SPS128, DeviceMode deviceMode = DeviceMode.Continuous)
: this(i2cDevice, inputMultiplexer, measuringRange, dataRate, deviceMode)
{
- _gpioController = gpioController ?? throw new ArgumentNullException(nameof(gpioController));
- if (gpioInterruptPin < 0 || gpioInterruptPin >= gpioController.PinCount)
+ _gpioController = gpioController ?? new GpioController();
+ if (gpioInterruptPin < 0 || gpioInterruptPin >= _gpioController.PinCount)
{
throw new ArgumentOutOfRangeException(nameof(gpioInterruptPin), $"The given GPIO Controller has no pin number {gpioInterruptPin}");
}
_gpioInterruptPin = gpioInterruptPin;
- _shouldDispose = shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
}
///
@@ -164,11 +163,7 @@ public DeviceMode DeviceMode
/// Comparator mode.
/// Only relevant if the comparator trigger event is set up and is changed by .
///
- public ComparatorMode ComparatorMode
- {
- get;
- private set;
- }
+ public ComparatorMode ComparatorMode { get; private set; }
///
/// Comparator polarity. Indicates whether the rising or the falling edge of the ALRT/RDY Pin is relevant.
@@ -208,13 +203,7 @@ public ComparatorLatching ComparatorLatching
/// Minimum number of samples exceeding the lower/upper threshold before the ALRT pin is asserted.
/// This can only be set with .
///
- public ComparatorQueue ComparatorQueue
- {
- get
- {
- return _comparatorQueue;
- }
- }
+ public ComparatorQueue ComparatorQueue => _comparatorQueue;
///
/// This event fires when a new value is available (in conversion ready mode) or the comparator threshold is exceeded.
@@ -285,7 +274,7 @@ private void DisableAlertReadyPin()
(byte)Register.ADC_CONFIG_REG_HI_THRESH, 0x7F, 0xFF
};
_i2cDevice.Write(writeBuff);
- if (_gpioController != null)
+ if (_gpioController is object)
{
_gpioController.UnregisterCallbackForPinValueChangedEvent(_gpioInterruptPin, ConversionReadyCallback);
_gpioController.ClosePin(_gpioInterruptPin);
@@ -319,7 +308,7 @@ private void WriteComparatorRegisters(short loThreshold, short hiThreshold)
/// for interrupt handling.
public void EnableConversionReady()
{
- if (_gpioController == null)
+ if (_gpioController is null)
{
throw new InvalidOperationException("Must have provided a GPIO Controller for interrupt handling.");
}
@@ -349,7 +338,7 @@ public void EnableConversionReady()
private void ConversionReadyCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
{
- if (AlertReadyAsserted != null)
+ if (AlertReadyAsserted is object)
{
AlertReadyAsserted();
}
@@ -368,10 +357,7 @@ private void ConversionReadyCallback(object sender, PinValueChangedEventArgs pin
/// Minimum number of samples that must exceed the threshold to trigger the event
/// The GPIO Controller for the interrupt handler has not been set up
public void EnableComparator(ElectricPotential lowerValue, ElectricPotential upperValue, ComparatorMode mode,
- ComparatorQueue queueLength)
- {
- EnableComparator(VoltageToRaw(lowerValue), VoltageToRaw(upperValue), mode, queueLength);
- }
+ ComparatorQueue queueLength) => EnableComparator(VoltageToRaw(lowerValue), VoltageToRaw(upperValue), mode, queueLength);
///
/// Enable comparator callback mode.
@@ -388,7 +374,7 @@ public void EnableComparator(ElectricPotential lowerValue, ElectricPotential upp
public void EnableComparator(short lowerValue, short upperValue, ComparatorMode mode,
ComparatorQueue queueLength)
{
- if (_gpioController == null)
+ if (_gpioController is null)
{
throw new InvalidOperationException("GPIO Controller must have been provided in constructor for this operation to work");
}
@@ -444,7 +430,7 @@ private ushort ReadConfigRegister()
/// This method must only be called in powerdown mode, otherwise it would timeout, since the busy bit never changes.
/// Due to that, we always write the configuration first in power down mode and then enable the continuous bit.
///
- /// A timeout occured waiting for the ADC to finish the conversion
+ /// A timeout occurred waiting for the ADC to finish the conversion
private void WaitWhileBusy()
{
// In powerdown-mode, wait until the busy bit goes high
@@ -502,10 +488,7 @@ private short ReadRawInternal()
/// For performance reasons, it is advised to use this method if quick readings with different input channels are required,
/// instead of setting all the properties first and then calling .
///
- public short ReadRaw(InputMultiplexer inputMultiplexer)
- {
- return ReadRaw(inputMultiplexer, MeasuringRange, DataRate);
- }
+ public short ReadRaw(InputMultiplexer inputMultiplexer) => ReadRaw(inputMultiplexer, MeasuringRange, DataRate);
///
/// Reads the next raw value, first switching to the given input and ranges.
@@ -590,30 +573,16 @@ public short VoltageToRaw(ElectricPotential voltage)
/// An electric potential (voltage).
public ElectricPotential MaxVoltageFromMeasuringRange(MeasuringRange measuringRange)
{
- double voltage;
- switch (measuringRange)
- {
- case MeasuringRange.FS6144:
- voltage = 6.144;
- break;
- case MeasuringRange.FS4096:
- voltage = 4.096;
- break;
- case MeasuringRange.FS2048:
- voltage = 2.048;
- break;
- case MeasuringRange.FS1024:
- voltage = 1.024;
- break;
- case MeasuringRange.FS0512:
- voltage = 0.512;
- break;
- case MeasuringRange.FS0256:
- voltage = 0.256;
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(measuringRange), "Unknown measuring range used");
- }
+ double voltage = measuringRange switch
+ {
+ MeasuringRange.FS6144 => 6.144,
+ MeasuringRange.FS4096 => 4.096,
+ MeasuringRange.FS2048 => 2.048,
+ MeasuringRange.FS1024 => 1.024,
+ MeasuringRange.FS0512 => 0.512,
+ MeasuringRange.FS0256 => 0.256,
+ _ => throw new ArgumentOutOfRangeException(nameof(measuringRange), "Unknown measuring range used")
+ };
return ElectricPotential.FromVolts(voltage);
}
@@ -623,30 +592,18 @@ public ElectricPotential MaxVoltageFromMeasuringRange(MeasuringRange measuringRa
///
/// One of the enumeration members.
/// A frequency, in Hertz
- public double FrequencyFromDataRate(DataRate dataRate)
+ public double FrequencyFromDataRate(DataRate dataRate) => dataRate switch
{
- switch (dataRate)
- {
- case DataRate.SPS008:
- return 8.0;
- case DataRate.SPS016:
- return 16.0;
- case DataRate.SPS032:
- return 32.0;
- case DataRate.SPS064:
- return 64.0;
- case DataRate.SPS128:
- return 128.0;
- case DataRate.SPS250:
- return 250.0;
- case DataRate.SPS475:
- return 475.0;
- case DataRate.SPS860:
- return 860.0;
- default:
- throw new ArgumentOutOfRangeException(nameof(dataRate), "Unknown data rate used");
- }
- }
+ DataRate.SPS008 => 8.0,
+ DataRate.SPS016 => 16.0,
+ DataRate.SPS032 => 32.0,
+ DataRate.SPS064 => 64.0,
+ DataRate.SPS128 => 128.0,
+ DataRate.SPS250 => 250.0,
+ DataRate.SPS475 => 475.0,
+ DataRate.SPS860 => 860.0,
+ _ => throw new ArgumentOutOfRangeException(nameof(dataRate), "Unknown data rate used")
+ };
///
/// Cleanup.
@@ -654,19 +611,18 @@ public double FrequencyFromDataRate(DataRate dataRate)
///
public void Dispose()
{
- if (_i2cDevice != null)
+ if (_i2cDevice is object)
{
DisableAlertReadyPin();
- _i2cDevice?.Dispose();
+ _i2cDevice.Dispose();
_i2cDevice = null!;
}
- if (_shouldDispose && _gpioController != null)
+ if (_shouldDispose)
{
- _gpioController.Dispose();
+ _gpioController?.Dispose();
+ _gpioController = null;
}
-
- _gpioController = null;
}
}
}
diff --git a/src/devices/Adxl345/Adxl345.cs b/src/devices/Adxl345/Adxl345.cs
index fa70f944ab..31c4a264ad 100644
--- a/src/devices/Adxl345/Adxl345.cs
+++ b/src/devices/Adxl345/Adxl345.cs
@@ -45,27 +45,16 @@ public class Adxl345 : IDisposable
/// Gravity Measurement Range
public Adxl345(SpiDevice sensor, GravityRange gravityRange)
{
- if (gravityRange == GravityRange.Range02)
+ _sensor = sensor ?? throw new ArgumentNullException(nameof(sensor));
+ _range = gravityRange switch
{
- _range = 4;
- }
- else if (gravityRange == GravityRange.Range04)
- {
- _range = 8;
- }
- else if (gravityRange == GravityRange.Range08)
- {
- _range = 16;
- }
- else if (gravityRange == GravityRange.Range16)
- {
- _range = 32;
- }
-
+ GravityRange.Range02 => 4,
+ GravityRange.Range04 => 8,
+ GravityRange.Range08 => 16,
+ GravityRange.Range16 => 32,
+ _ => 0
+ };
_gravityRangeByte = (byte)gravityRange;
-
- _sensor = sensor;
-
Initialize();
}
@@ -119,7 +108,7 @@ private Vector3 ReadAcceleration()
///
public void Dispose()
{
- if (_sensor != null)
+ if (_sensor is object)
{
_sensor.Dispose();
_sensor = null!;
diff --git a/src/devices/Adxl345/samples/Program.cs b/src/devices/Adxl345/samples/Program.cs
index a0bc5c3f77..969b97a582 100644
--- a/src/devices/Adxl345/samples/Program.cs
+++ b/src/devices/Adxl345/samples/Program.cs
@@ -9,14 +9,13 @@
SpiConnectionSettings settings = new (0, 0)
{
- ClockFrequency = Iot.Device.Adxl345.Adxl345.SpiClockFrequency,
- Mode = Iot.Device.Adxl345.Adxl345.SpiMode
+ ClockFrequency = Adxl345.SpiClockFrequency,
+ Mode = Adxl345.SpiMode
};
using SpiDevice device = SpiDevice.Create(settings);
-
// set gravity measurement range ±4G
-using Iot.Device.Adxl345.Adxl345 sensor = new Iot.Device.Adxl345.Adxl345(device, GravityRange.Range04);
+using Adxl345 sensor = new Adxl345(device, GravityRange.Range04);
while (true)
{
// read data
diff --git a/src/devices/Ags01db/Ags01db.cs b/src/devices/Ags01db/Ags01db.cs
index f6eaed4f2f..221c186363 100644
--- a/src/devices/Ags01db/Ags01db.cs
+++ b/src/devices/Ags01db/Ags01db.cs
@@ -18,17 +18,17 @@ public class Ags01db : IDisposable
private const byte CRC_INIT = 0xFF;
private I2cDevice _i2cDevice;
- private int _lastMeasurment = 0;
+ private int _lastMeasurement = 0;
///
/// ASG01DB VOC (Volatile Organic Compounds) Gas Concentration (ppm)
///
- public double Concentration { get => GetConcentration(); }
+ public double Concentration => GetConcentration();
///
/// ASG01DB Version
///
- public byte Version { get => GetVersion(); }
+ public byte Version => GetVersion();
///
/// ASG01DB Default I2C Address
@@ -41,16 +41,7 @@ public class Ags01db : IDisposable
/// The I2C device used for communication.
public Ags01db(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
- }
-
- ///
- /// Cleanup
- ///
- public void Dispose()
- {
- _i2cDevice?.Dispose();
- _i2cDevice = null!;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
}
///
@@ -60,9 +51,9 @@ public void Dispose()
private double GetConcentration()
{
// The time of two measurements should be more than 2s.
- while (Environment.TickCount - _lastMeasurment < 2000)
+ while (Environment.TickCount - _lastMeasurement < 2000)
{
- Thread.Sleep(TimeSpan.FromMilliseconds(Environment.TickCount - _lastMeasurment));
+ Thread.Sleep(Environment.TickCount - _lastMeasurement);
}
// Details in the Datasheet P5
@@ -77,7 +68,7 @@ private double GetConcentration()
_i2cDevice.Write(writeBuff);
_i2cDevice.Read(readBuff);
- _lastMeasurment = Environment.TickCount;
+ _lastMeasurement = Environment.TickCount;
// CRC check error
if (!CheckCrc8(readBuff.Slice(0, 2), 2, readBuff[2]))
@@ -154,5 +145,14 @@ private bool CheckCrc8(ReadOnlySpan data, int length, byte crc8)
return false;
}
}
+
+ ///
+ /// Cleanup
+ ///
+ public void Dispose()
+ {
+ _i2cDevice?.Dispose();
+ _i2cDevice = null!;
+ }
}
}
diff --git a/src/devices/Ahtxx/AhtBase.cs b/src/devices/Ahtxx/AhtBase.cs
index 8874af3cbb..2ab5a306f1 100644
--- a/src/devices/Ahtxx/AhtBase.cs
+++ b/src/devices/Ahtxx/AhtBase.cs
@@ -134,27 +134,17 @@ private void Initialize()
private byte GetStatus()
{
_i2cDevice.WriteByte(0x71);
- // whithout this delay the reading the status fails often.
+ // without this delay the reading the status fails often.
Thread.Sleep(10);
- byte status = _i2cDevice.ReadByte();
- return status;
+ return _i2cDevice.ReadByte();
}
- private bool IsBusy()
- {
- return (GetStatus() & (byte)StatusBit.Busy) == (byte)StatusBit.Busy;
- }
-
- private bool IsCalibrated()
- {
- return (GetStatus() & (byte)StatusBit.Calibrated) == (byte)StatusBit.Calibrated;
- }
+ private bool IsBusy() => (GetStatus() & (byte)StatusBit.Busy) == (byte)StatusBit.Busy;
- ///
- public void Dispose() => Dispose(true);
+ private bool IsCalibrated() => (GetStatus() & (byte)StatusBit.Calibrated) == (byte)StatusBit.Calibrated;
///
- protected virtual void Dispose(bool disposing)
+ public void Dispose()
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
diff --git a/src/devices/Ak8963/Ak8963.cs b/src/devices/Ak8963/Ak8963.cs
index ec942a3a84..1bf085c3ec 100644
--- a/src/devices/Ak8963/Ak8963.cs
+++ b/src/devices/Ak8963/Ak8963.cs
@@ -20,7 +20,7 @@ public sealed class Ak8963 : IDisposable
private OutputBitMode _outputBitMode;
private bool _selfTest = false;
private Ak8963I2cBase _ak8963Interface;
- private bool _autodispose = true;
+ private bool _shouldDispose = true;
///
/// Default I2C address for the AK8963
@@ -40,18 +40,18 @@ public Ak8963(I2cDevice i2CDevice)
/// Constructor to use if AK8963 is behind another element and need a special I2C protocol like
/// when used with the MPU9250
///
- /// The I2C device
+ /// The I2C device
/// The specific interface to communicate with the AK8963
- /// True to dispose the I2C device when class is disposed
- public Ak8963(I2cDevice i2CDevice, Ak8963I2cBase ak8963Interface, bool autoDispose = true)
+ /// True to dispose the I2C device when class is disposed
+ public Ak8963(I2cDevice i2cDevice, Ak8963I2cBase ak8963Interface, bool shouldDispose = true)
{
- _i2cDevice = i2CDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_ak8963Interface = ak8963Interface;
// Initialize the default modes
_measurementMode = MeasurementMode.PowerDown;
_outputBitMode = OutputBitMode.Output14bit;
_selfTest = false;
- _autodispose = autoDispose;
+ _shouldDispose = shouldDispose;
byte mode = (byte)((byte)_measurementMode | ((byte)_outputBitMode << 4));
WriteRegister(Register.CNTL, mode);
if (!IsVersionCorrect())
@@ -77,10 +77,7 @@ public void Reset()
/// Get the device information
///
/// The device information
- public byte GetDeviceInfo()
- {
- return ReadByte(Register.INFO);
- }
+ public byte GetDeviceInfo() => ReadByte(Register.INFO);
///
/// Get the magnetometer bias
@@ -280,7 +277,6 @@ public Vector3 ReadMagnetometer(bool waitForData, TimeSpan timeout)
public bool MageneticFieldGeneratorEnabled
{
get => _selfTest;
-
set
{
byte mode = value ? (byte)0b01000_0000 : (byte)0b0000_0000;
@@ -295,7 +291,6 @@ public bool MageneticFieldGeneratorEnabled
public MeasurementMode MeasurementMode
{
get => _measurementMode;
-
set
{
byte mode = (byte)((byte)value | ((byte)_outputBitMode << 4));
@@ -313,7 +308,6 @@ public MeasurementMode MeasurementMode
public OutputBitMode OutputBitMode
{
get => _outputBitMode;
-
set
{
byte mode = (byte)(((byte)value << 4) | (byte)_measurementMode);
@@ -333,7 +327,7 @@ public OutputBitMode OutputBitMode
///
public void Dispose()
{
- if (_autodispose)
+ if (_shouldDispose)
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
diff --git a/src/devices/Ak8963/samples/Program.cs b/src/devices/Ak8963/samples/Program.cs
index ff25c3df8d..64ffa8915d 100644
--- a/src/devices/Ak8963/samples/Program.cs
+++ b/src/devices/Ak8963/samples/Program.cs
@@ -5,13 +5,14 @@
using System.Device.I2c;
using System.IO;
using System.Threading;
+using System.Numerics;
using Iot.Device.Magnetometer;
I2cConnectionSettings mpui2CConnectionSettingmpus = new (1, Ak8963.DefaultI2cAddress);
-var ak8963 = new Ak8963(I2cDevice.Create(mpui2CConnectionSettingmpus));
+using Ak8963 ak8963 = new Ak8963(I2cDevice.Create(mpui2CConnectionSettingmpus));
Console.WriteLine(
"Magnetometer calibration is taking couple of seconds, move your sensor in all possible directions! Make sure you don't have a magnet or phone close by.");
-var mag = ak8963.CalibrateMagnetometer();
+Vector3 mag = ak8963.CalibrateMagnetometer();
Console.WriteLine($"Bias:");
Console.WriteLine($"Mag X = {mag.X}");
Console.WriteLine($"Mag Y = {mag.Y}");
@@ -22,7 +23,7 @@
while (!Console.KeyAvailable)
{
- var magne = ak8963.ReadMagnetometer(true, TimeSpan.FromMilliseconds(11));
+ Vector3 magne = ak8963.ReadMagnetometer(true, TimeSpan.FromMilliseconds(11));
Console.WriteLine($"Mag X = {magne.X,15}");
Console.WriteLine($"Mag Y = {magne.Y,15}");
Console.WriteLine($"Mag Z = {magne.Z,15}");
diff --git a/src/devices/Apa102/Apa102.cs b/src/devices/Apa102/Apa102.cs
index fe94bdb4c6..e398d65104 100644
--- a/src/devices/Apa102/Apa102.cs
+++ b/src/devices/Apa102/Apa102.cs
@@ -17,18 +17,18 @@ public class Apa102 : IDisposable
///
public Span Pixels => _pixels;
- private SpiDevice _spi;
+ private SpiDevice _spiDevice;
private Color[] _pixels;
private byte[] _buffer;
///
/// Initializes a new instance of the APA102 device.
///
- /// The SPI device used for communication.
+ /// The SPI device used for communication.
/// Number of LEDs
- public Apa102(SpiDevice spi, int length)
+ public Apa102(SpiDevice spiDevice, int length)
{
- _spi = spi ?? throw new ArgumentNullException(nameof(spi));
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_pixels = new Color[length];
_buffer = new byte[(length + 2) * 4];
@@ -50,14 +50,14 @@ public void Flush()
pixel[3] = _pixels[i].R; // red
}
- _spi.Write(_buffer);
+ _spiDevice.Write(_buffer);
}
///
public void Dispose()
{
- _spi.Dispose();
- _spi = null!;
+ _spiDevice?.Dispose();
+ _spiDevice = null!;
_pixels = null!;
_buffer = null!;
}
diff --git a/src/devices/Apa102/samples/Program.cs b/src/devices/Apa102/samples/Program.cs
index 231472ef8c..6e6fb06280 100644
--- a/src/devices/Apa102/samples/Program.cs
+++ b/src/devices/Apa102/samples/Program.cs
@@ -15,7 +15,7 @@
DataFlow = DataFlow.MsbFirst,
Mode = SpiMode.Mode0 // ensure data is ready at clock rising edge
});
-var apa102 = new Apa102(spiDevice, 16);
+using Apa102 apa102 = new Apa102(spiDevice, 16);
while (true)
{
diff --git a/src/devices/Bh1750fvi/Bh1750fvi.cs b/src/devices/Bh1750fvi/Bh1750fvi.cs
index b7c8474c07..ce7c470746 100644
--- a/src/devices/Bh1750fvi/Bh1750fvi.cs
+++ b/src/devices/Bh1750fvi/Bh1750fvi.cs
@@ -50,7 +50,7 @@ public double LightTransmittance
/// BH1750FVI Light Transmittance, from 27.20% to 222.50%
public Bh1750fvi(I2cDevice i2cDevice, MeasuringMode measuringMode = MeasuringMode.ContinuouslyHighResolutionMode, double lightTransmittance = 1)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_i2cDevice.WriteByte((byte)Command.PowerOn);
_i2cDevice.WriteByte((byte)Command.Reset);
@@ -59,15 +59,6 @@ public Bh1750fvi(I2cDevice i2cDevice, MeasuringMode measuringMode = MeasuringMod
MeasuringMode = measuringMode;
}
- ///
- /// Cleanup
- ///
- public void Dispose()
- {
- _i2cDevice?.Dispose();
- _i2cDevice = null!;
- }
-
///
/// Set BH1750FVI Light Transmittance
///
@@ -112,5 +103,14 @@ private Illuminance GetIlluminance()
return Illuminance.FromLux(result);
}
+
+ ///
+ /// Cleanup
+ ///
+ public void Dispose()
+ {
+ _i2cDevice?.Dispose();
+ _i2cDevice = null!;
+ }
}
}
diff --git a/src/devices/Bh1750fvi/samples/Program.cs b/src/devices/Bh1750fvi/samples/Program.cs
index 6870e99221..0e2c2ad024 100644
--- a/src/devices/Bh1750fvi/samples/Program.cs
+++ b/src/devices/Bh1750fvi/samples/Program.cs
@@ -7,8 +7,7 @@
using Iot.Device.Bh1750fvi;
I2cConnectionSettings settings = new (busId: 1, (int)I2cAddress.AddPinLow);
-I2cDevice device = I2cDevice.Create(settings);
-
+using I2cDevice device = I2cDevice.Create(settings);
using Bh1750fvi sensor = new Bh1750fvi(device);
while (true)
{
diff --git a/src/devices/Bmp180/Bmp180.cs b/src/devices/Bmp180/Bmp180.cs
index 241b59bc9e..9cf2a0a11c 100644
--- a/src/devices/Bmp180/Bmp180.cs
+++ b/src/devices/Bmp180/Bmp180.cs
@@ -32,7 +32,7 @@ public class Bmp180 : IDisposable
/// I2C device used to communicate with the device
public Bmp180(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_calibrationData = new CalibrationData();
// Read the coefficients table
_calibrationData.ReadFromDevice(this);
@@ -43,10 +43,7 @@ public Bmp180(I2cDevice i2cDevice)
/// Sets sampling to the given value
///
/// Sampling Mode
- public void SetSampling(Sampling mode)
- {
- _mode = mode;
- }
+ public void SetSampling(Sampling mode) => _mode = mode;
///
/// Reads the temperature from the sensor
@@ -54,10 +51,7 @@ public void SetSampling(Sampling mode)
///
/// Temperature in degrees celsius
///
- public Temperature ReadTemperature()
- {
- return Temperature.FromDegreesCelsius((CalculateTrueTemperature() + 8) / 160.0);
- }
+ public Temperature ReadTemperature() => Temperature.FromDegreesCelsius((CalculateTrueTemperature() + 8) / 160.0);
///
/// Reads the pressure from the sensor
@@ -92,10 +86,7 @@ public Pressure ReadPressure()
///
/// Height above sea level
///
- public Length ReadAltitude(Pressure seaLevelPressure)
- {
- return WeatherHelper.CalculateAltitude(ReadPressure(), seaLevelPressure, ReadTemperature());
- }
+ public Length ReadAltitude(Pressure seaLevelPressure) => WeatherHelper.CalculateAltitude(ReadPressure(), seaLevelPressure, ReadTemperature());
///
/// Calculates the altitude in meters from the mean sea-level pressure.
@@ -103,10 +94,7 @@ public Length ReadAltitude(Pressure seaLevelPressure)
///
/// Height in meters above sea level
///
- public Length ReadAltitude()
- {
- return ReadAltitude(WeatherHelper.MeanSeaLevel);
- }
+ public Length ReadAltitude() => ReadAltitude(WeatherHelper.MeanSeaLevel);
///
/// Calculates the pressure at sea level when given a known altitude
@@ -117,10 +105,7 @@ public Length ReadAltitude()
///
/// Pressure
///
- public Pressure ReadSeaLevelPressure(Length altitude)
- {
- return WeatherHelper.CalculateSeaLevelPressure(ReadPressure(), altitude, ReadTemperature());
- }
+ public Pressure ReadSeaLevelPressure(Length altitude) => WeatherHelper.CalculateSeaLevelPressure(ReadPressure(), altitude, ReadTemperature());
///
/// Calculates the pressure at sea level, when the current altitude is 0.
@@ -128,10 +113,7 @@ public Pressure ReadSeaLevelPressure(Length altitude)
///
/// Pressure
///
- public Pressure ReadSeaLevelPressure()
- {
- return ReadSeaLevelPressure(Length.Zero);
- }
+ public Pressure ReadSeaLevelPressure() => ReadSeaLevelPressure(Length.Zero);
///
/// Calculate true temperature
diff --git a/src/devices/Bmp180/samples/Program.cs b/src/devices/Bmp180/samples/Program.cs
index 0c16cde905..140c471ea1 100644
--- a/src/devices/Bmp180/samples/Program.cs
+++ b/src/devices/Bmp180/samples/Program.cs
@@ -23,12 +23,12 @@
// read values
Temperature tempValue = i2cBmp280.ReadTemperature();
Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
-var preValue = i2cBmp280.ReadPressure();
+Pressure preValue = i2cBmp280.ReadPressure();
Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
// Note that if you already have the pressure value and the temperature, you could also calculate altitude by
// calling WeatherHelper.CalculateAltitude(preValue, Pressure.MeanSeaLevel, tempValue) which would be more performant.
-var altValue = i2cBmp280.ReadAltitude(WeatherHelper.MeanSeaLevel);
+Length altValue = i2cBmp280.ReadAltitude(WeatherHelper.MeanSeaLevel);
Console.WriteLine($"Altitude: {altValue:0.##}m");
Thread.Sleep(1000);
diff --git a/src/devices/Bmxx80/Bmx280Base.cs b/src/devices/Bmxx80/Bmx280Base.cs
index e1873b84ec..0588db65c7 100644
--- a/src/devices/Bmxx80/Bmx280Base.cs
+++ b/src/devices/Bmxx80/Bmx280Base.cs
@@ -205,10 +205,7 @@ public bool TryReadAltitude(Pressure seaLevelPressure, out Length altitude)
/// Contains otherwise.
///
/// true
if pressure measurement was not skipped, otherwise false
.
- public bool TryReadAltitude(out Length altitude)
- {
- return TryReadAltitude(WeatherHelper.MeanSeaLevel, out altitude);
- }
+ public bool TryReadAltitude(out Length altitude) => TryReadAltitude(WeatherHelper.MeanSeaLevel, out altitude);
///
/// Get the current status of the device.
@@ -253,10 +250,7 @@ public void SetPowerMode(Bmx280PowerMode powerMode)
/// Gets the required time in ms to perform a measurement with the current sampling modes.
///
/// The time it takes for the chip to read data in milliseconds rounded up.
- public virtual int GetMeasurementDuration()
- {
- return s_osToMeasCycles[(int)PressureSampling] + s_osToMeasCycles[(int)TemperatureSampling];
- }
+ public virtual int GetMeasurementDuration() => s_osToMeasCycles[(int)PressureSampling] + s_osToMeasCycles[(int)TemperatureSampling];
///
/// Sets the default configuration for the sensor.
diff --git a/src/devices/Bmxx80/Bmxx80Base.cs b/src/devices/Bmxx80/Bmxx80Base.cs
index 5adb82df59..f27ebd1b01 100644
--- a/src/devices/Bmxx80/Bmxx80Base.cs
+++ b/src/devices/Bmxx80/Bmxx80Base.cs
@@ -52,11 +52,7 @@ public enum CommunicationProtocol
/// The variable TemperatureFine carries a fine resolution temperature value over to the
/// pressure compensation formula and could be implemented as a global variable.
///
- protected double TemperatureFine
- {
- get;
- set;
- }
+ protected double TemperatureFine { get; set; }
///
/// The temperature calibration factor.
diff --git a/src/devices/Bmxx80/samples/Bme280.sample.cs b/src/devices/Bmxx80/samples/Bme280.sample.cs
index 3c0c74bd7f..dacd736791 100644
--- a/src/devices/Bmxx80/samples/Bme280.sample.cs
+++ b/src/devices/Bmxx80/samples/Bme280.sample.cs
@@ -15,34 +15,36 @@
// bus id on the raspberry pi 3
const int busId = 1;
// set this to the current sea level pressure in the area for correct altitude readings
-var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
+Pressure defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
-var i2cSettings = new I2cConnectionSettings(busId, Bme280.DefaultI2cAddress);
-var i2cDevice = I2cDevice.Create(i2cSettings);
-using var i2CBmpe80 = new Bme280(i2cDevice);
-
-while (true)
+I2cConnectionSettings i2cSettings = new (busId, Bme280.DefaultI2cAddress);
+using I2cDevice i2cDevice = I2cDevice.Create(i2cSettings);
+using Bme280 bme80 = new Bme280(i2cDevice)
{
// set higher sampling
- i2CBmpe80.TemperatureSampling = Sampling.LowPower;
- i2CBmpe80.PressureSampling = Sampling.UltraHighResolution;
- i2CBmpe80.HumiditySampling = Sampling.Standard;
+ TemperatureSampling = Sampling.LowPower,
+ PressureSampling = Sampling.UltraHighResolution,
+ HumiditySampling = Sampling.Standard,
+
+};
- // set mode forced so device sleeps after read
- i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced);
+// set mode forced so device sleeps after read
+bme80.SetPowerMode(Bmx280PowerMode.Forced);
+while (true)
+{
// wait for measurement to be performed
- var measurementTime = i2CBmpe80.GetMeasurementDuration();
+ var measurementTime = bme80.GetMeasurementDuration();
Thread.Sleep(measurementTime);
// read values
- i2CBmpe80.TryReadTemperature(out var tempValue);
- i2CBmpe80.TryReadPressure(out var preValue);
- i2CBmpe80.TryReadHumidity(out var humValue);
+ bme80.TryReadTemperature(out var tempValue);
+ bme80.TryReadPressure(out var preValue);
+ bme80.TryReadHumidity(out var humValue);
// Note that if you already have the pressure value and the temperature, you could also calculate altitude by using
// var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant.
- i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out var altValue);
+ bme80.TryReadAltitude(defaultSeaLevelPressure, out var altValue);
Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
@@ -55,26 +57,26 @@
Thread.Sleep(1000);
// change sampling and filter
- i2CBmpe80.TemperatureSampling = Sampling.UltraHighResolution;
- i2CBmpe80.PressureSampling = Sampling.UltraLowPower;
- i2CBmpe80.HumiditySampling = Sampling.UltraLowPower;
- i2CBmpe80.FilterMode = Bmx280FilteringMode.X2;
+ bme80.TemperatureSampling = Sampling.UltraHighResolution;
+ bme80.PressureSampling = Sampling.UltraLowPower;
+ bme80.HumiditySampling = Sampling.UltraLowPower;
+ bme80.FilterMode = Bmx280FilteringMode.X2;
// set mode forced and read again
- i2CBmpe80.SetPowerMode(Bmx280PowerMode.Forced);
+ bme80.SetPowerMode(Bmx280PowerMode.Forced);
// wait for measurement to be performed
- measurementTime = i2CBmpe80.GetMeasurementDuration();
+ measurementTime = bme80.GetMeasurementDuration();
Thread.Sleep(measurementTime);
// read values
- i2CBmpe80.TryReadTemperature(out tempValue);
- i2CBmpe80.TryReadPressure(out preValue);
- i2CBmpe80.TryReadHumidity(out humValue);
+ bme80.TryReadTemperature(out tempValue);
+ bme80.TryReadPressure(out preValue);
+ bme80.TryReadHumidity(out humValue);
// Note that if you already have the pressure value and the temperature, you could also calculate altitude by using
// var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue) which would be more performant.
- i2CBmpe80.TryReadAltitude(defaultSeaLevelPressure, out altValue);
+ bme80.TryReadAltitude(defaultSeaLevelPressure, out altValue);
Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
diff --git a/src/devices/Bmxx80/samples/Bme680.sample.cs b/src/devices/Bmxx80/samples/Bme680.sample.cs
index 605fb804ef..042f45e154 100644
--- a/src/devices/Bmxx80/samples/Bme680.sample.cs
+++ b/src/devices/Bmxx80/samples/Bme680.sample.cs
@@ -14,12 +14,12 @@
// The I2C bus ID on the Raspberry Pi 3.
const int busId = 1;
// set this to the current sea level pressure in the area for correct altitude readings
-var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
+Pressure defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
-var i2cSettings = new I2cConnectionSettings(busId, Bme680.DefaultI2cAddress);
-var i2cDevice = I2cDevice.Create(i2cSettings);
+I2cConnectionSettings i2cSettings = new (busId, Bme680.DefaultI2cAddress);
+I2cDevice i2cDevice = I2cDevice.Create(i2cSettings);
-using var bme680 = new Bme680(i2cDevice, Temperature.FromDegreesCelsius(20.0));
+using Bme680 bme680 = new Bme680(i2cDevice, Temperature.FromDegreesCelsius(20.0));
while (true)
{
diff --git a/src/devices/Bmxx80/samples/Bmp280.sample.cs b/src/devices/Bmxx80/samples/Bmp280.sample.cs
index 04cdcf016d..e1911607ce 100644
--- a/src/devices/Bmxx80/samples/Bmp280.sample.cs
+++ b/src/devices/Bmxx80/samples/Bmp280.sample.cs
@@ -17,10 +17,10 @@
// bus id on the raspberry pi 3 and 4
const int busId = 1;
// set this to the current sea level pressure in the area for correct altitude readings
-var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
+Pressure defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
-var i2cSettings = new I2cConnectionSettings(busId, Bmp280.DefaultI2cAddress);
-var i2cDevice = I2cDevice.Create(i2cSettings);
+I2cConnectionSettings i2cSettings = new (busId, Bmp280.DefaultI2cAddress);
+I2cDevice i2cDevice = I2cDevice.Create(i2cSettings);
using var i2CBmp280 = new Bmp280(i2cDevice);
while (true)
diff --git a/src/devices/Bno055/Bno055Sensor.cs b/src/devices/Bno055/Bno055Sensor.cs
index 870b3aed3b..0ad3f63b3f 100644
--- a/src/devices/Bno055/Bno055Sensor.cs
+++ b/src/devices/Bno055/Bno055Sensor.cs
@@ -27,7 +27,7 @@ public class Bno055Sensor : IDisposable
public const byte SecondI2cAddress = 0x29;
private const byte DeviceId = 0xA0;
- private readonly bool _autoDispoable;
+ private readonly bool _shouldDispose;
private I2cDevice _i2cDevice;
private OperationMode _operationMode;
private Units _units;
@@ -37,10 +37,7 @@ public class Bno055Sensor : IDisposable
///
public OperationMode OperationMode
{
- get
- {
- return _operationMode;
- }
+ get => _operationMode;
set
{
_operationMode = value;
@@ -55,10 +52,7 @@ public OperationMode OperationMode
///
public PowerMode PowerMode
{
- get
- {
- return (PowerMode)ReadByte(Registers.PWR_MODE);
- }
+ get => (PowerMode)ReadByte(Registers.PWR_MODE);
set
{
SetConfigMode(true);
@@ -72,10 +66,7 @@ public PowerMode PowerMode
///
public TemperatureSource TemperatureSource
{
- get
- {
- return (TemperatureSource)ReadByte(Registers.TEMP_SOURCE);
- }
+ get => (TemperatureSource)ReadByte(Registers.TEMP_SOURCE);
set
{
SetConfigMode(true);
@@ -89,10 +80,7 @@ public TemperatureSource TemperatureSource
///
public Units Units
{
- get
- {
- return (Units)ReadByte(Registers.UNIT_SEL);
- }
+ get => (Units)ReadByte(Registers.UNIT_SEL);
set
{
SetConfigMode(true);
@@ -105,20 +93,20 @@ public Units Units
///
/// Get the information about various sensor system versions and ID
///
- public Info Info { get; internal set; }
+ public Info Info { get; private set; }
///
/// Create an BNO055 sensor
///
/// The I2C Device
/// The operation mode to setup
- /// true to dispose the I2C device at dispose
+ /// true to dispose the I2C device at dispose
public Bno055Sensor(I2cDevice i2cDevice,
OperationMode operationMode = OperationMode.AccelerometerMagnetometerGyroscopeRelativeOrientation,
- bool autoDispoable = true)
+ bool shouldDispose = true)
{
- _i2cDevice = i2cDevice ?? throw new ArgumentException($"{nameof(i2cDevice)} can't be null");
- _autoDispoable = autoDispoable;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
+ _shouldDispose = shouldDispose;
// A first write to initate the device
WriteReg(Registers.PAGE_ID, 0);
@@ -219,7 +207,7 @@ public void SetExternalCrystal(bool external)
///
/// Get the latest error
///
- /// eturns the latest error
+ /// Returns the latest error
public Error GetError() => (Error)ReadByte(Registers.SYS_ERR);
///
@@ -252,8 +240,8 @@ public TestResult RunSelfTest()
public Vector4 GetAccelerometerCalibrationData()
{
SetConfigMode(true);
- var vect = GetVectorData(Registers.ACCEL_OFFSET_X_LSB);
- var radius = ReadInt16(Registers.ACCEL_RADIUS_LSB);
+ Vector3 vect = GetVectorData(Registers.ACCEL_OFFSET_X_LSB);
+ short radius = ReadInt16(Registers.ACCEL_RADIUS_LSB);
SetConfigMode(false);
return new Vector4(vect, radius);
}
@@ -284,8 +272,8 @@ public void SetAccelerometerCalibrationData(Vector4 calibrationData)
public Vector4 GetMagnetometerCalibrationData()
{
SetConfigMode(true);
- var vect = GetVectorData(Registers.MAG_OFFSET_X_LSB);
- var radius = ReadInt16(Registers.MAG_RADIUS_LSB);
+ Vector3 vect = GetVectorData(Registers.MAG_OFFSET_X_LSB);
+ short radius = ReadInt16(Registers.MAG_RADIUS_LSB);
SetConfigMode(false);
return new Vector4(vect, radius);
}
@@ -316,7 +304,7 @@ public void SetMagnetometerCalibrationData(Vector4 calibrationData)
public Vector3 GetGyroscopeCalibrationData()
{
SetConfigMode(true);
- var vect = GetVectorData(Registers.GYRO_OFFSET_X_LSB);
+ Vector3 vect = GetVectorData(Registers.GYRO_OFFSET_X_LSB);
SetConfigMode(false);
return vect;
}
@@ -378,7 +366,7 @@ public Vector3 Orientation
{
get
{
- var retVect = GetVectorData(Registers.EULER_H_LSB);
+ Vector3 retVect = GetVectorData(Registers.EULER_H_LSB);
// If unit is MeterG, then divide by 900, otherwise divide by 16
if (_units.HasFlag(Units.EulerAnglesRadians))
{
@@ -403,7 +391,7 @@ public Vector3 Gyroscope
{
get
{
- var retVect = GetVectorData(Registers.GYRO_DATA_X_LSB);
+ Vector3 retVect = GetVectorData(Registers.GYRO_DATA_X_LSB);
if ((_units & Units.AngularRateRotationPerSecond) == Units.AngularRateRotationPerSecond)
{
return retVect / 900;
@@ -425,7 +413,7 @@ public Vector3 Accelerometer
{
get
{
- var retVect = GetVectorData(Registers.ACCEL_DATA_X_LSB);
+ Vector3 retVect = GetVectorData(Registers.ACCEL_DATA_X_LSB);
// If unit is MeterG, then no convertion, otherwise divide by 100
if ((_units & Units.AccelerationMeterG) == Units.AccelerationMeterG)
{
@@ -448,7 +436,7 @@ public Vector3 LinearAcceleration
{
get
{
- var retVect = GetVectorData(Registers.LINEAR_ACCEL_DATA_X_LSB);
+ Vector3 retVect = GetVectorData(Registers.LINEAR_ACCEL_DATA_X_LSB);
// If unit is MeterG, then no convertion, otherwise divide by 100
if ((_units & Units.AccelerationMeterG) == Units.AccelerationMeterG)
{
@@ -471,7 +459,7 @@ public Vector3 Gravity
{
get
{
- var retVect = GetVectorData(Registers.GRAVITY_DATA_X_LSB);
+ Vector3 retVect = GetVectorData(Registers.GRAVITY_DATA_X_LSB);
// If unit is MeterG, then no convertion, otherwise divide by 100
if ((_units & Units.AccelerationMeterG) == Units.AccelerationMeterG)
{
@@ -548,17 +536,14 @@ private void SetConfigMode(bool mode)
///
public void Dispose()
{
- if (_autoDispoable)
+ if (_shouldDispose)
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
}
}
- private void WriteReg(Registers reg, byte param)
- {
- _i2cDevice.Write(new byte[] { (byte)reg, param });
- }
+ private void WriteReg(Registers reg, byte param) => _i2cDevice.Write(new byte[] { (byte)reg, param });
private byte ReadByte(Registers reg)
{
diff --git a/src/devices/Bno055/samples/Program.cs b/src/devices/Bno055/samples/Program.cs
index bdf680c658..2b2158f0ed 100644
--- a/src/devices/Bno055/samples/Program.cs
+++ b/src/devices/Bno055/samples/Program.cs
@@ -9,7 +9,7 @@
Console.WriteLine("Hello BNO055!");
using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(1, Bno055Sensor.DefaultI2cAddress));
-using Bno055Sensor bno055Sensor = new Bno055Sensor(i2cDevice);
+using Bno055Sensor bno055Sensor = new (i2cDevice);
Console.WriteLine(
$"Id: {bno055Sensor.Info.ChipId}, AccId: {bno055Sensor.Info.AcceleratorId}, GyroId: {bno055Sensor.Info.GyroscopeId}, MagId: {bno055Sensor.Info.MagnetometerId}");
Console.WriteLine(
@@ -19,12 +19,10 @@
Console.WriteLine($"Powermode: {bno055Sensor.PowerMode}");
Console.WriteLine(
"Checking the magnetometer calibration, move the sensor up to the calibration will be complete if needed");
-var calibrationStatus = bno055Sensor.GetCalibrationStatus();
-while ((calibrationStatus & CalibrationStatus.MagnetometerSuccess) !=
+while ((bno055Sensor.GetCalibrationStatus() & CalibrationStatus.MagnetometerSuccess) !=
(CalibrationStatus.MagnetometerSuccess))
{
Console.Write($".");
- calibrationStatus = bno055Sensor.GetCalibrationStatus();
Thread.Sleep(200);
}
@@ -33,21 +31,21 @@
while (!Console.KeyAvailable)
{
Console.Clear();
- var magneto = bno055Sensor.Magnetometer;
+ Vector3 magneto = bno055Sensor.Magnetometer;
Console.WriteLine($"Magnetomer X: {magneto.X} Y: {magneto.Y} Z: {magneto.Z}");
- var gyro = bno055Sensor.Gyroscope;
+ Vector3 gyro = bno055Sensor.Gyroscope;
Console.WriteLine($"Gyroscope X: {gyro.X} Y: {gyro.Y} Z: {gyro.Z}");
- var accele = bno055Sensor.Accelerometer;
+ Vector3 accele = bno055Sensor.Accelerometer;
Console.WriteLine($"Acceleration X: {accele.X} Y: {accele.Y} Z: {accele.Z}");
- var orien = bno055Sensor.Orientation;
- Console.WriteLine($"Orientation Heading: {orien.X} Roll: {orien.Y} Pitch: {orien.Z}");
- var line = bno055Sensor.LinearAcceleration;
+ Vector3 orientation = bno055Sensor.Orientation;
+ Console.WriteLine($"Orientation Heading: {orientation.X} Roll: {orientation.Y} Pitch: {orientation.Z}");
+ Vector3 line = bno055Sensor.LinearAcceleration;
Console.WriteLine($"Linear acceleration X: {line.X} Y: {line.Y} Z: {line.Z}");
- var gravity = bno055Sensor.Gravity;
+ Vector3 gravity = bno055Sensor.Gravity;
Console.WriteLine($"Gravity X: {gravity.X} Y: {gravity.Y} Z: {gravity.Z}");
- var qua = bno055Sensor.Quaternion;
+ Vector4 qua = bno055Sensor.Quaternion;
Console.WriteLine($"Quaternion X: {qua.X} Y: {qua.Y} Z: {qua.Z} W: {qua.W}");
- var temp = bno055Sensor.Temperature.DegreesCelsius;
+ double temp = bno055Sensor.Temperature.DegreesCelsius;
Console.WriteLine($"Temperature: {temp} °C");
Thread.Sleep(100);
}
diff --git a/src/devices/BoardLed/BoardLed.cs b/src/devices/BoardLed/BoardLed.cs
index 3772b053f3..db21723ac3 100644
--- a/src/devices/BoardLed/BoardLed.cs
+++ b/src/devices/BoardLed/BoardLed.cs
@@ -38,17 +38,25 @@ public class BoardLed : IDisposable
/// If you want to operate the LED, you need to remove the trigger, which is to set its trigger to none.
/// Use to get all triggers.
///
- public string Trigger { get => GetTrigger(); set => SetTrigger(value); }
+ public string Trigger
+ {
+ get => GetTrigger();
+ set => SetTrigger(value);
+ }
///
/// The current brightness of the LED.
///
- public int Brightness { get => GetBrightness(); set => SetBrightness(value); }
+ public int Brightness
+ {
+ get => GetBrightness();
+ set => SetBrightness(value);
+ }
///
/// The max brightness of the LED.
///
- public int MaxBrightness { get => GetMaxBrightness(); }
+ public int MaxBrightness => GetMaxBrightness();
///
/// Creates a new instance of the BoardLed.
@@ -97,44 +105,22 @@ public static IEnumerable EnumerateLeds()
.Select(x => new BoardLed(x.Name));
}
- ///
- /// Cleanup
- ///
- public void Dispose()
- {
- _brightnessReader?.Dispose();
- _brightnessWriter?.Dispose();
- _triggerReader?.Dispose();
- _triggerWriter?.Dispose();
- _maxBrightnessReader?.Dispose();
-
- _brightnessReader = null!;
- _brightnessWriter = null!;
- _triggerReader = null!;
- _triggerWriter = null!;
- _maxBrightnessReader = null!;
- }
-
private int GetBrightness()
{
_brightnessReader.BaseStream.Position = 0;
-
return int.Parse(_brightnessReader.ReadToEnd());
}
private int GetMaxBrightness()
{
_maxBrightnessReader.BaseStream.Position = 0;
-
return int.Parse(_maxBrightnessReader.ReadToEnd());
}
private void SetBrightness(int value)
{
value = Math.Clamp(value, 0, 255);
-
_brightnessWriter.BaseStream.SetLength(0);
-
_brightnessWriter.Write(value);
_brightnessWriter.Flush();
}
@@ -142,7 +128,6 @@ private void SetBrightness(int value)
private string GetTrigger()
{
_triggerReader.BaseStream.Position = 0;
-
return Regex.Match(_triggerReader.ReadToEnd(), @"(?<=\[)(.*)(?=\])").Value;
}
@@ -152,11 +137,10 @@ private void SetTrigger(string name)
if (!triggers.Contains(name))
{
- throw new ArgumentException($"System does not contain a trigger called {name}.");
+ throw new Exception($"System does not contain a trigger called {name}.");
}
_triggerWriter.BaseStream.SetLength(0);
-
_triggerWriter.Write(name);
_triggerWriter.Flush();
}
@@ -173,8 +157,25 @@ private void Initialize()
FileStream triggerStream = File.Open($"{DefaultDevicePath}/{Name}/trigger", FileMode.Open);
_triggerReader = new StreamReader(stream: triggerStream, encoding: Encoding.ASCII, detectEncodingFromByteOrderMarks: false, bufferSize: 512, leaveOpen: true);
_triggerWriter = new StreamWriter(stream: triggerStream, encoding: Encoding.ASCII, bufferSize: 512, leaveOpen: false);
-
_maxBrightnessReader = new StreamReader(File.Open($"{DefaultDevicePath}/{Name}/max_brightness", FileMode.Open, FileAccess.Read));
}
+
+ ///
+ /// Cleanup
+ ///
+ public void Dispose()
+ {
+ _brightnessReader?.Dispose();
+ _brightnessWriter?.Dispose();
+ _triggerReader?.Dispose();
+ _triggerWriter?.Dispose();
+ _maxBrightnessReader?.Dispose();
+
+ _brightnessReader = null!;
+ _brightnessWriter = null!;
+ _triggerReader = null!;
+ _triggerWriter = null!;
+ _maxBrightnessReader = null!;
+ }
}
}
diff --git a/src/devices/BoardLed/samples/Program.cs b/src/devices/BoardLed/samples/Program.cs
index 3778eccd83..2f4926b351 100644
--- a/src/devices/BoardLed/samples/Program.cs
+++ b/src/devices/BoardLed/samples/Program.cs
@@ -5,7 +5,7 @@
using Iot.Device.BoardLed;
// Open the green led on Raspberry Pi.
-using BoardLed led = new BoardLed("led0");
+using BoardLed led = new ("led0");
string defaultTrigger = led.Trigger;
diff --git a/src/devices/BrickPi3/Extensions/EnumExtension.cs b/src/devices/BrickPi3/Extensions/EnumExtension.cs
index bd24a9a6b0..65c430ddec 100644
--- a/src/devices/BrickPi3/Extensions/EnumExtension.cs
+++ b/src/devices/BrickPi3/Extensions/EnumExtension.cs
@@ -15,7 +15,7 @@ public static T Next(this T src)
{
if (!typeof(T).IsEnum)
{
- throw new ArgumentException($"Argumnent {typeof(T).FullName} is not an Enum");
+ throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum");
}
T[] arr = (T[])Enum.GetValues(src.GetType());
@@ -28,7 +28,7 @@ public static T Previous(this T src)
{
if (!typeof(T).IsEnum)
{
- throw new ArgumentException($"Argumnent {typeof(T).FullName} is not an Enum");
+ throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum");
}
T[] arr = (T[])Enum.GetValues(src.GetType());
diff --git a/src/devices/BrickPi3/Movement/Vehicle.cs b/src/devices/BrickPi3/Movement/Vehicle.cs
index 5be8f4ea65..8ea892d171 100644
--- a/src/devices/BrickPi3/Movement/Vehicle.cs
+++ b/src/devices/BrickPi3/Movement/Vehicle.cs
@@ -160,7 +160,7 @@ public bool DirectionOpposite
private void RunMotorSyncTime(BrickPortMotor[] ports, int[] speeds, int timeout)
{
- if ((ports == null) || (speeds == null))
+ if ((ports is null) || (speeds is null))
{
return;
}
@@ -171,7 +171,7 @@ private void RunMotorSyncTime(BrickPortMotor[] ports, int[] speeds, int timeout)
}
// create a timer for the needed time to run
- if (_timer == null)
+ if (_timer is null)
{
_timer = new Timer(RunUntil, ports, TimeSpan.FromMilliseconds(timeout), Timeout.InfiniteTimeSpan);
}
@@ -201,7 +201,7 @@ private void RunMotorSyncTime(BrickPortMotor[] ports, int[] speeds, int timeout)
private void RunUntil(object? state)
{
- if (state == null)
+ if (state is null)
{
return;
}
@@ -230,7 +230,7 @@ private void StartMotor(int port, int speed)
private void RunMotorSyncDegrees(BrickPortMotor[] ports, int[] speeds, int[] degrees)
{
- if ((ports == null) || (speeds == null) || degrees == null)
+ if ((ports is null) || (speeds is null) || degrees is null)
{
return;
}
diff --git a/src/devices/BrickPi3/Sensors/EV3ColorSensor.cs b/src/devices/BrickPi3/Sensors/EV3ColorSensor.cs
index fa8c0223e2..0c4bc6538e 100644
--- a/src/devices/BrickPi3/Sensors/EV3ColorSensor.cs
+++ b/src/devices/BrickPi3/Sensors/EV3ColorSensor.cs
@@ -100,30 +100,15 @@ public int PeriodRefresh
}
}
- private SensorType GetEV3Mode(ColorSensorMode mode)
+ private SensorType GetEV3Mode(ColorSensorMode mode) => mode switch
{
- SensorType ret = SensorType.EV3ColorReflected;
- switch (mode)
- {
- case ColorSensorMode.Color:
- ret = SensorType.EV3ColorColor;
- break;
- case ColorSensorMode.Reflection:
- ret = SensorType.EV3ColorReflected;
- break;
- case ColorSensorMode.Green:
- ret = SensorType.EV3ColorRawReflected;
- break;
- case ColorSensorMode.Blue:
- ret = SensorType.EV3ColorColorComponents;
- break;
- case ColorSensorMode.Ambient:
- ret = SensorType.EV3ColorAmbient;
- break;
- }
-
- return ret;
- }
+ ColorSensorMode.Color => SensorType.EV3ColorColor,
+ ColorSensorMode.Reflection => SensorType.EV3ColorReflected,
+ ColorSensorMode.Green => SensorType.EV3ColorRawReflected,
+ ColorSensorMode.Blue => SensorType.EV3ColorColorComponents,
+ ColorSensorMode.Ambient => SensorType.EV3ColorAmbient,
+ _ => SensorType.EV3ColorReflected,
+ };
///
/// Set or get the color mode
diff --git a/src/devices/BrickPi3/samples/MotorTests.cs b/src/devices/BrickPi3/samples/MotorTests.cs
index 198fc0e3df..0141788278 100644
--- a/src/devices/BrickPi3/samples/MotorTests.cs
+++ b/src/devices/BrickPi3/samples/MotorTests.cs
@@ -126,12 +126,12 @@ private static void TestMotorEvents()
private static void Motor_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
string count = sender is Motor m ? m.TachoCount.ToString() : string.Empty;
- Console.WriteLine($"Event raised, endoer changed: {e.PropertyName}; {count}");
+ Console.WriteLine($"Event raised, encoder changed: {e.PropertyName}; {count}");
}
- private static void TestVehicule()
+ private static void TestVehicle()
{
- Console.WriteLine("Vehicule drive test using Motor A for left, Motor D for right, not inverted direction");
+ Console.WriteLine("Vehicle drive test using Motor A for left, Motor D for right, not inverted direction");
Vehicle veh = new Vehicle(_brick, BrickPortMotor.PortA, BrickPortMotor.PortD);
veh.DirectionOpposite = true;
Console.WriteLine("Driving backward");
diff --git a/src/devices/BrickPi3/samples/Program.cs b/src/devices/BrickPi3/samples/Program.cs
index 8773948252..4648564a62 100644
--- a/src/devices/BrickPi3/samples/Program.cs
+++ b/src/devices/BrickPi3/samples/Program.cs
@@ -89,7 +89,7 @@ public static void Main(string[] args)
if (args.Contains(VehiculeTest))
{
- TestVehicule();
+ TestVehicle();
}
// Test using high level classes for sensors
@@ -196,7 +196,7 @@ private static void TestMotorEncoder()
private static void TestBrickDetails()
{
- // Get the details abourt the brick
+ // Get the details about the brick
var brickinfo = _brick.BrickPi3Info;
Console.WriteLine($"Manufacturer: {brickinfo.Manufacturer}");
Console.WriteLine($"Board: {brickinfo.Board}");
@@ -245,7 +245,7 @@ private static void TestSensors()
_brick.SetSensorType((byte)SensorPort.Port3, SensorType.EV3UltrasonicCentimeter);
for (int i = 0; i < 100; i++)
{
- Console.WriteLine($"Iterration {i}");
+ Console.WriteLine($"Iteration {i}");
try
{
var sensordata = _brick.GetSensor((byte)SensorPort.Port3);
@@ -266,7 +266,7 @@ private static void TestSensors()
_brick.SetSensorType((byte)SensorPort.Port4, SensorType.EV3Touch);
for (int i = 0; i < 100; i++)
{
- Console.WriteLine($"Iterration {i}");
+ Console.WriteLine($"Iteration {i}");
try
{
var sensordata = _brick.GetSensor((byte)SensorPort.Port4);
@@ -287,7 +287,7 @@ private static void TestSensors()
_brick.SetSensorType((byte)SensorPort.Port1, SensorType.NXTTouch);
for (int i = 0; i < 100; i++)
{
- Console.WriteLine($"Iterration {i}");
+ Console.WriteLine($"Iteration {i}");
try
{
var sensordata = _brick.GetSensor((byte)SensorPort.Port1);
@@ -308,7 +308,7 @@ private static void TestSensors()
_brick.SetSensorType((byte)SensorPort.Port2, SensorType.EV3ColorColor);
for (int i = 0; i < 100; i++)
{
- Console.WriteLine($"Iterration {i}");
+ Console.WriteLine($"Iteration {i}");
try
{
var sensordata = _brick.GetSensor((byte)SensorPort.Port2);
diff --git a/src/devices/Buzzer/Buzzer.cs b/src/devices/Buzzer/Buzzer.cs
index d614af91c4..0ca6d7c793 100644
--- a/src/devices/Buzzer/Buzzer.cs
+++ b/src/devices/Buzzer/Buzzer.cs
@@ -38,10 +38,7 @@ public Buzzer(int chip, int channel)
/// Create Buzzer class instance with output on specified pin with specified channel using passed PWM controller.
///
/// The PWM controller to use during work.
- public Buzzer(PwmChannel pwmChannel)
- {
- _pwmChannel = pwmChannel;
- }
+ public Buzzer(PwmChannel pwmChannel) => _pwmChannel = pwmChannel;
///
/// Set new or overwrite previously set frequency and start playing the sound.
@@ -56,10 +53,7 @@ public void StartPlaying(double frequency)
///
/// Stop playing tone.
///
- public void StopPlaying()
- {
- _pwmChannel.Stop();
- }
+ public void StopPlaying() => _pwmChannel.Stop();
///
/// Play tone of specific frequency for specified duration.
diff --git a/src/devices/Buzzer/samples/MelodyElement.cs b/src/devices/Buzzer/samples/MelodyElement.cs
index 0d570b750b..ff36f25a2a 100644
--- a/src/devices/Buzzer/samples/MelodyElement.cs
+++ b/src/devices/Buzzer/samples/MelodyElement.cs
@@ -13,9 +13,6 @@ internal abstract class MelodyElement
///
public Duration Duration { get; set; }
- public MelodyElement(Duration duration)
- {
- Duration = duration;
- }
+ public MelodyElement(Duration duration) => Duration = duration;
}
}
diff --git a/src/devices/Buzzer/samples/MelodyPlayer.cs b/src/devices/Buzzer/samples/MelodyPlayer.cs
index 344acfebce..fad2ab8cec 100644
--- a/src/devices/Buzzer/samples/MelodyPlayer.cs
+++ b/src/devices/Buzzer/samples/MelodyPlayer.cs
@@ -20,43 +20,39 @@ internal class MelodyPlayer : IDisposable
/// Create MelodyPlayer.
///
/// Buzzer instance to be played on.
- public MelodyPlayer(Buzzer buzzer)
- {
- _buzzer = buzzer;
- }
+ public MelodyPlayer(Buzzer buzzer) => _buzzer = buzzer;
///
/// Play melody elements sequecne.
///
/// Sequence of pauses and notes elements to be played.
/// Tempo of melody playing.
- /// Tones to transpose
- public void Play(IList sequence, int tempo, int tonesToTransponse = 0)
+ /// Tones to transpose
+ public void Play(IList sequence, int tempo, int tonesToTranspose = 0)
{
_wholeNoteDurationInMilliseconds = GetWholeNoteDurationInMilliseconds(tempo);
- sequence = TransposeSequence(sequence, tonesToTransponse);
+ sequence = TransposeSequence(sequence, tonesToTranspose);
foreach (var element in sequence)
{
PlayElement(element);
}
}
- private static IList TransposeSequence(IList sequence, int tonesToTransponse)
+ private static IList TransposeSequence(IList sequence, int tonesToTranspose)
{
- if (tonesToTransponse == 0)
+ if (tonesToTranspose == 0)
{
return sequence;
}
return sequence
- .Select(element => TransposeElement(element, tonesToTransponse))
+ .Select(element => TransposeElement(element, tonesToTranspose))
.ToList();
}
private static MelodyElement TransposeElement(MelodyElement element, int tonesToTransponse)
{
- var noteElement = element as NoteElement;
- if (noteElement == null)
+ if (element is not NoteElement noteElement)
{
return element;
}
@@ -80,17 +76,11 @@ private static MelodyElement TransposeElement(MelodyElement element, int tonesTo
return noteElement;
}
- public void Dispose()
- {
- _buzzer.Dispose();
- }
-
private void PlayElement(MelodyElement element)
{
var durationInMilliseconds = _wholeNoteDurationInMilliseconds / (int)element.Duration;
- var noteElement = element as NoteElement;
- if (noteElement == null)
+ if (element is not NoteElement noteElement)
{
// In case it's a pause element we have only just wait desired time.
Thread.Sleep(durationInMilliseconds);
@@ -121,13 +111,10 @@ private static readonly Dictionary notesOfEightOctaveToFrequencies
{ Note.B, 7902.13 }
};
- private static int GetWholeNoteDurationInMilliseconds(int tempo)
- {
- // In music tempo defines amount of quarter notes per minute.
- // Dividing minute (60 * 1000) by tempo we get duration of quarter note.
- // Whole note duration equals to four quarters.
- return 4 * 60 * 1000 / tempo;
- }
+ // In music tempo defines amount of quarter notes per minute.
+ // Dividing minute (60 * 1000) by tempo we get duration of quarter note.
+ // Whole note duration equals to four quarters.
+ private static int GetWholeNoteDurationInMilliseconds(int tempo) => 4 * 60 * 1000 / tempo;
private static double GetFrequency(Note note, Octave octave)
{
@@ -142,13 +129,14 @@ private static double GetFrequency(Note note, Octave octave)
private static double GetNoteFrequencyOfEightOctave(Note note)
{
- double result;
- if (notesOfEightOctaveToFrequenciesMap.TryGetValue(note, out result))
+ if (notesOfEightOctaveToFrequenciesMap.TryGetValue(note, out double result))
{
return result;
}
return 0;
}
+
+ public void Dispose() => _buzzer?.Dispose();
}
}
diff --git a/src/devices/Card/Card.sln b/src/devices/Card/Card.sln
index 89ee904820..d970a9aa02 100644
--- a/src/devices/Card/Card.sln
+++ b/src/devices/Card/Card.sln
@@ -5,6 +5,10 @@ VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CardRfid", "CardRfid.csproj", "{2B97523A-956B-4C88-8931-28C1AF88012C}"
EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreditCardProcessing", "CreditCard\CreditCardProcessing.csproj", "{A9AC5868-77E7-4742-AF7E-E140F2CFF79B}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mifare", "Mifare\Mifare.csproj", "{81A964D2-BA4B-4769-A630-084D8C4BEBDA}"
+EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -30,5 +34,29 @@ Global
{2B97523A-956B-4C88-8931-28C1AF88012C}.Release|x64.Build.0 = Release|Any CPU
{2B97523A-956B-4C88-8931-28C1AF88012C}.Release|x86.ActiveCfg = Release|Any CPU
{2B97523A-956B-4C88-8931-28C1AF88012C}.Release|x86.Build.0 = Release|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Debug|x64.Build.0 = Debug|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Debug|x86.Build.0 = Debug|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Release|Any CPU.Build.0 = Release|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Release|x64.ActiveCfg = Release|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Release|x64.Build.0 = Release|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Release|x86.ActiveCfg = Release|Any CPU
+ {A9AC5868-77E7-4742-AF7E-E140F2CFF79B}.Release|x86.Build.0 = Release|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Debug|x64.Build.0 = Debug|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Debug|x86.Build.0 = Debug|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|Any CPU.Build.0 = Release|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x64.ActiveCfg = Release|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x64.Build.0 = Release|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x86.ActiveCfg = Release|Any CPU
+ {81A964D2-BA4B-4769-A630-084D8C4BEBDA}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
diff --git a/src/devices/Card/CreditCard/CreditCard.cs b/src/devices/Card/CreditCard/CreditCard.cs
index dff7ad500a..b885a96d92 100644
--- a/src/devices/Card/CreditCard/CreditCard.cs
+++ b/src/devices/Card/CreditCard/CreditCard.cs
@@ -79,7 +79,7 @@ public ErrorType ProcessExternalAuthentication(Span issuerAuthenticationDa
{
if ((issuerAuthenticationData.Length < 8) || (issuerAuthenticationData.Length > 16))
{
- throw new ArgumentException($"{nameof(issuerAuthenticationData)} needs to be more than 8 and less than 16 length");
+ throw new ArgumentException(nameof(issuerAuthenticationData), "Data needs to be more than 8 and less than 16 bytes length");
}
Span toSend = stackalloc byte[5 + issuerAuthenticationData.Length];
@@ -113,7 +113,7 @@ public ErrorType GetChallenge(Span unpredictableNumber)
{
if (unpredictableNumber.Length < 8)
{
- throw new ArgumentException($"{nameof(GetChallenge)}: {nameof(unpredictableNumber)} has to be at least 8 byte long.");
+ throw new ArgumentException(nameof(unpredictableNumber), "Data has to be at least 8 bytes long.");
}
Span toSend = stackalloc byte[5];
@@ -142,7 +142,7 @@ public ErrorType VerifyPin(ReadOnlySpan pindigits)
// Pin can only be 4 to C length
if ((pindigits.Length < 0x04) && (pindigits.Length > 0x0C))
{
- throw new ArgumentException($"{nameof(VerifyPin)}: {nameof(pindigits)} can only be between 4 and 12 digits");
+ throw new ArgumentException(nameof(pindigits), "Data can only be between 4 and 12 digits");
}
// Encode the pin
@@ -258,7 +258,7 @@ private void FillTagList(List tags, ReadOnlySpan span, uint parent =
// If it is a template or composed, then we need to split it
if ((TagList.Tags.Where(m => m.TagNumber == tag.TagNumber).FirstOrDefault()?.IsTemplate == true) || tag.IsConstructed)
{
- if (tag.Tags == null)
+ if (tag.Tags is null)
{
tag.Tags = new List();
}
@@ -271,7 +271,7 @@ private void FillTagList(List tags, ReadOnlySpan span, uint parent =
// Of the object
if (TagList.Tags.Where(m => m.TagNumber == tag.TagNumber).FirstOrDefault()?.IsDol == true)
{
- if (tag.Tags == null)
+ if (tag.Tags is null)
{
tag.Tags = new List();
}
@@ -335,7 +335,7 @@ public void ReadCreditCardInformation()
// Search for all tags with entries
var entries = Tag.SearchTag(Tags, 0x9F4D).FirstOrDefault();
- if (entries != null)
+ if (entries is object)
{
// SFI entries is first byte and number of records is second one
ReadLogEntries(entries.Data[0], entries.Data[1]);
@@ -363,7 +363,7 @@ private bool FillTags()
Tag? appPriotity = Tag.SearchTag(app.Tags, 0x87).FirstOrDefault();
// As it is not mandatory, some cards will have only 1
// application and this may not be present
- if (appPriotity == null)
+ if (appPriotity is null)
{
appPriotity = new Tag() { Data = new byte[1] { 0 } };
}
@@ -376,15 +376,15 @@ private bool FillTags()
// We need to select the Template 0x6F where the Tag 0x84 contains the same App Id and where we have a template A5 attached.
var templates = Tags
.Where(m => m.TagNumber == 0x6F)
- .Where(m => m.Tags.Where(t => t.TagNumber == 0x84).Where(t => t.Data.SequenceEqual(appIdentifier.Data)) != null)
- .Where(m => m.Tags.Where(t => t.TagNumber == 0xA5) != null);
+ .Where(m => m.Tags.Where(t => t.TagNumber == 0x84).Where(t => t.Data.SequenceEqual(appIdentifier.Data)) is object)
+ .Where(m => m.Tags.Where(t => t.TagNumber == 0xA5) is object);
// Only here we may find a PDOL tag 0X9F38
Tag? pdol = null;
foreach (var temp in templates)
{
// We are sure to have 0xA5, so select it and search for PDOL
pdol = Tag.SearchTag(temp.Tags, 0xA5).FirstOrDefault()?.Tags.Where(m => m.TagNumber == 0x9F38).FirstOrDefault();
- if (pdol != null)
+ if (pdol is object)
{
break;
}
@@ -393,7 +393,7 @@ private bool FillTags()
Span received = new byte[260];
byte sumDol = 0;
// Do we have a PDOL?
- if (pdol != null)
+ if (pdol is object)
{
// So we need to send as may bytes as it request
foreach (var dol in pdol.Tags)
@@ -410,7 +410,7 @@ private bool FillTags()
// If we have a PDOL, then we need to fill it properly
// Some fields are mandatory
int index = 2;
- if (pdol != null)
+ if (pdol is object)
{
foreach (var dol in pdol.Tags)
{
@@ -481,7 +481,7 @@ private bool FillTags()
}
}
- if ((ret == ErrorType.ProcessCompletedNormal) && (appLocator != null))
+ if ((ret == ErrorType.ProcessCompletedNormal) && (appLocator is object))
{
// Now decode the appLocator
// Format is SFI - start - stop - number of records
@@ -543,7 +543,7 @@ private bool FillTags()
{
// It's the old way, so looking for tag 0x88
var appSfi = Tag.SearchTag(Tags, 0x88).FirstOrDefault();
- if (appSfi != null)
+ if (appSfi is object)
{
LogInfo.Log($"AppSFI: {appSfi.Data[0]}", LogLevel.Debug);
for (byte record = 1; record < 10; record++)
diff --git a/src/devices/Card/CreditCard/README.md b/src/devices/Card/CreditCard/README.md
index dd9fbcfc4e..d46ac723f8 100644
--- a/src/devices/Card/CreditCard/README.md
+++ b/src/devices/Card/CreditCard/README.md
@@ -27,20 +27,20 @@ static void ReadCreditCard(Pn532 pn532)
while ((!Console.KeyAvailable))
{
retData = pn532.AutoPoll(5, 300, new PollingType[] { PollingType.Passive106kbpsISO144443_4B });
- if (retData != null)
+ if (retData is object)
if (retData.Length >= 3)
break;
// Give time to PN532 to process
Thread.Sleep(200);
}
- if (retData == null)
+ if (retData is null)
return;
// Check how many cards and the type
Console.WriteLine($"Num tags: {retData[0]}, Type: {(PollingType)retData[1]}");
var decrypted = pn532.TryDecodeData106kbpsTypeB(retData.AsSpan().Slice(3));
- if (decrypted != null)
+ if (decrypted is object)
{
Console.WriteLine($"{decrypted.TargetNumber}, Serial: {BitConverter.ToString(decrypted.NfcId)}, App Data: {BitConverter.ToString(decrypted.ApplicationData)}, " +
$"{decrypted.ApplicationType}, Bit Rates: {decrypted.BitRates}, CID {decrypted.CidSupported}, Command: {decrypted.Command}, FWT: {decrypted.FrameWaitingTime}, " +
@@ -53,7 +53,7 @@ static void ReadCreditCard(Pn532 pn532)
DisplayTags(creditCard.Tags, 0);
// Display Log Entries
var format = Tag.SearchTag(creditCard.Tags, 0x9F4F).FirstOrDefault();
- if (format != null)
+ if (format is object)
DisplayLogEntries(creditCard.LogEntries, format.Tags);
}
}
diff --git a/src/devices/Card/CreditCard/Tag.cs b/src/devices/Card/CreditCard/Tag.cs
index cc9ec498ff..0fcda58a13 100644
--- a/src/devices/Card/CreditCard/Tag.cs
+++ b/src/devices/Card/CreditCard/Tag.cs
@@ -31,7 +31,7 @@ public Tag(uint tagNumber, byte[] data, uint parent = 0, List? tags = null)
TagNumber = tagNumber;
Data = data;
Parent = parent;
- if (tags != null)
+ if (tags is object)
{
Tags = tags;
}
diff --git a/src/devices/Card/CreditCard/TagDetails.cs b/src/devices/Card/CreditCard/TagDetails.cs
index 90b4b678cd..ba0581a8a9 100644
--- a/src/devices/Card/CreditCard/TagDetails.cs
+++ b/src/devices/Card/CreditCard/TagDetails.cs
@@ -31,7 +31,7 @@ public TagDetails(Tag tag)
Parent = tag.Parent;
Tags = tag.Tags;
var ret = TagList.Tags.Where(m => m.TagNumber == TagNumber).FirstOrDefault();
- if (ret != null)
+ if (ret is object)
{
TagTemplateParent = ret.TagTemplateParent;
IsTemplate = ret.IsTemplate;
diff --git a/src/devices/Card/CreditCard/TagList.cs b/src/devices/Card/CreditCard/TagList.cs
index 45888ddbc0..37d1cb02be 100644
--- a/src/devices/Card/CreditCard/TagList.cs
+++ b/src/devices/Card/CreditCard/TagList.cs
@@ -14,7 +14,7 @@ public class TagList
/// List of Tags description, source, conversion for display as well as if they are templates or contain Data Object Link
/// This list is coming from the EMV documentation, see EMV book 3, Annexe A
///
- public static List Tags = new List()
+ public static List Tags = new ()
{
new TagDetails() { TagNumber = 0x06, Source = Source.Icc, Decoder = ConversionType.ByteArray, Description = "Object Identifier (OID)", IsTemplate = false, IsDol = false },
new TagDetails() { TagNumber = 0x41, Source = Source.Icc, Decoder = ConversionType.ByteArray, Description = "Country code and national data", IsTemplate = false, IsDol = false },
diff --git a/src/devices/Card/Mifare/MifareCard.cs b/src/devices/Card/Mifare/MifareCard.cs
index 2a4f224293..81b58a01dd 100644
--- a/src/devices/Card/Mifare/MifareCard.cs
+++ b/src/devices/Card/Mifare/MifareCard.cs
@@ -449,7 +449,7 @@ public AccessType BlockAccess(byte blockNumber, byte[] sectorData)
{
if (accessTypes.Length != 3)
{
- throw new ArgumentException($"{nameof(accessTypes)} can only be array of 3");
+ throw new ArgumentException(nameof(accessTypes), "Array must have 3 elements.");
}
var tupleRes = EncodeSectorTailer(accessSector);
@@ -471,10 +471,7 @@ public AccessType BlockAccess(byte blockNumber, byte[] sectorData)
/// Encode with default value the access sector and tailer blocks
///
///
- public (byte b6, byte b7, byte b8) EncodeDefaultSectorAndBlockTailer()
- {
- return (0xFF, 0x07, 0x80);
- }
+ public (byte b6, byte b7, byte b8) EncodeDefaultSectorAndBlockTailer() => (0xFF, 0x07, 0x80);
///
/// From the ATAQ ans SAK data find common card capacity
@@ -511,26 +508,13 @@ public void SetCapacity(ushort ATAQ, byte SAK)
///
/// Input block number
/// True if it is a sector block
- public bool IsSectorBlock(byte blockNumber)
+ public bool IsSectorBlock(byte blockNumber) => Capacity switch
{
- switch (Capacity)
- {
- default:
- case MifareCardCapacity.Mifare300:
- case MifareCardCapacity.Mifare1K:
- case MifareCardCapacity.Mifare2K:
- return blockNumber % 4 == 3;
- case MifareCardCapacity.Mifare4K:
- if (blockNumber < 128)
- {
- return blockNumber % 4 == 3;
- }
- else
- {
- return blockNumber % 16 == 15;
- }
- }
- }
+ MifareCardCapacity.Mifare300 | MifareCardCapacity.Mifare1K | MifareCardCapacity.Mifare2K => blockNumber % 4 == 3,
+ MifareCardCapacity.Mifare4K when blockNumber < 128 => blockNumber % 4 == 3,
+ MifareCardCapacity.Mifare4K => blockNumber % 16 == 15,
+ _ => blockNumber % 4 == 3,
+ };
///
/// Depending on the command, serialize the needed data
diff --git a/src/devices/Card/Mifare/README.md b/src/devices/Card/Mifare/README.md
index ea998ba96f..95f572ad5e 100644
--- a/src/devices/Card/Mifare/README.md
+++ b/src/devices/Card/Mifare/README.md
@@ -11,18 +11,18 @@ byte[] retData = null;
while (!Console.KeyAvailable)
{
retData = pn532.ListPassiveTarget(MaxTarget.One, TargetBaudRate.B106kbpsTypeA);
- if (retData != null)
+ if (retData is object)
break;
// Give time to PN532 to process
Thread.Sleep(200);
}
-if (retData == null)
+if (retData is null)
return;
var decrypted = pn532.Decode106kbpsTypeA(retData.AsSpan().Slice(1));
-if (decrypted != null)
+if (decrypted is object)
{
Console.WriteLine($"Tg: {decrypted.TargetNumber}, ATQA: {decrypted.Atqa} SAK: {decrypted.Sak}, NFCID: {BitConverter.ToString(decrypted.NfcId)}");
- if (decrypted.Ats != null)
+ if (decrypted.Ats is object)
Console.WriteLine($", ATS: {BitConverter.ToString(decrypted.Ats)}");
MifareCard mifareCard = new MifareCard(pn532, decrypted.TargetNumber) { BlockNumber = 0, Command = MifareCardCommand.AuthenticationA };
mifareCard.SetCapacity(decrypted.Atqa, decrypted.Sak);
diff --git a/src/devices/Ccs811/Ccs811Sensor.cs b/src/devices/Ccs811/Ccs811Sensor.cs
index 748aeeca2b..8dc8876f2a 100644
--- a/src/devices/Ccs811/Ccs811Sensor.cs
+++ b/src/devices/Ccs811/Ccs811Sensor.cs
@@ -70,15 +70,14 @@ public class Ccs811Sensor : IDisposable
/// Should the GPIO controller be disposed at the end
public Ccs811Sensor(I2cDevice i2cDevice, GpioController? gpioController = null, int pinWake = -1, int pinInterruption = -1, int pinReset = -1, bool shouldDispose = true)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_pinWake = pinWake;
_pinInterruption = pinInterruption;
_pinReset = pinReset;
- _shouldDispose = shouldDispose;
// We need a GPIO controller only if we are using any of the pin
if ((_pinInterruption >= 0) || (_pinReset >= 0) || (_pinWake >= 0))
{
- _shouldDispose = _shouldDispose || gpioController == null;
+ _shouldDispose = _shouldDispose || gpioController is null;
_controller = gpioController ?? new GpioController();
}
@@ -356,7 +355,7 @@ public void SetEnvironmentData(Temperature temperature, Ratio humidity)
{
if ((humidity.Percent < 0) || (humidity.Percent > 100))
{
- throw new ArgumentException($"Humidity can only be between 0 and 100.");
+ throw new ArgumentException(nameof(humidity), "Humidity can only be between 0 and 100.");
}
Span environment = stackalloc byte[4];
@@ -401,12 +400,12 @@ public bool SetThreshold(VolumeConcentration lowEquivalentCO2, VolumeConcentrati
if (!IsPpmValidThreshold(lowEquivalentCO2))
{
- throw new ArgumentException($"{lowEquivalentCO2} can only be between 0 and {ushort.MaxValue}");
+ throw new ArgumentException(nameof(lowEquivalentCO2), $"Value can only be between 0 and {ushort.MaxValue}.");
}
if (!IsPpmValidThreshold(highEquivalentCO2))
{
- throw new ArgumentException($"{highEquivalentCO2} can only be between 0 and {ushort.MaxValue}");
+ throw new ArgumentException(nameof(highEquivalentCO2), $"Value can only be between 0 and {ushort.MaxValue}.");
}
if (lowEquivalentCO2 > highEquivalentCO2)
@@ -418,7 +417,7 @@ public bool SetThreshold(VolumeConcentration lowEquivalentCO2, VolumeConcentrati
if (highEquivalentCO2 - lowEquivalentCO2 < VolumeConcentration.FromPartsPerMillion(50))
{
- throw new ArgumentException($"{highEquivalentCO2}-{lowEquivalentCO2} should be more than 50");
+ throw new ArgumentException(nameof(lowEquivalentCO2), $"value of {nameof(highEquivalentCO2)}-{nameof(lowEquivalentCO2)} must be more than 50.");
}
Span toSend = stackalloc byte[4];
diff --git a/src/devices/Ccs811/samples/Program.cs b/src/devices/Ccs811/samples/Program.cs
index 48312351b0..4c4938177c 100644
--- a/src/devices/Ccs811/samples/Program.cs
+++ b/src/devices/Ccs811/samples/Program.cs
@@ -9,66 +9,66 @@
using Iot.Device.Ccs811;
using Iot.Device.Ft4222;
using UnitsNet;
+using static System.Console;
-Ccs811Sensor ccs811;
-
-Console.WriteLine("Hello CCS811!");
+WriteLine("Hello CCS811!");
// Simple menu to select native I2C/GPIO or thru FT4222, with GPIO pins and specific features to test
-Console.WriteLine("Select which platform I2C/GPIO you want to use:");
-Console.WriteLine(" 1. Native I2C/GPIO");
-Console.WriteLine(" 2. FT4222");
-var platformChoice = Console.ReadKey();
-Console.WriteLine();
-Console.WriteLine("Which I2C address do you want to use? Use the first one if Address pin is to ground, use the second one if to VCC.");
-Console.WriteLine($" 1. First 0x{Ccs811Sensor.I2cFirstAddress:X2}");
-Console.WriteLine($" 2. Second 0x{Ccs811Sensor.I2cSecondAddress:X2}");
-var addressChoice = Console.ReadKey();
-Console.WriteLine();
-Console.WriteLine("Do you want to the interrupt pin and events?");
-Console.WriteLine("(Y)es,(N)o");
-var pinChoice = Console.ReadKey();
-Console.WriteLine();
+WriteLine("Select which platform I2C/GPIO you want to use:");
+WriteLine(" 1. Native I2C/GPIO");
+WriteLine(" 2. FT4222");
+ConsoleKeyInfo platformChoice = ReadKey();
+WriteLine();
+WriteLine("Which I2C address do you want to use? Use the first one if Address pin is to ground, use the second one if to VCC.");
+WriteLine($" 1. First 0x{Ccs811Sensor.I2cFirstAddress:X2}");
+WriteLine($" 2. Second 0x{Ccs811Sensor.I2cSecondAddress:X2}");
+ConsoleKeyInfo addressChoice = ReadKey();
+WriteLine();
+WriteLine("Do you want to the interrupt pin and events?");
+WriteLine("(Y)es,(N)o");
+ConsoleKeyInfo pinChoice = ReadKey();
+WriteLine();
int pinInterrupt = CheckAndAskPinNumber(pinChoice.KeyChar);
-Console.WriteLine($"Do you want to use the Wake pin?");
-Console.WriteLine("(Y)es,(N)o");
-pinChoice = Console.ReadKey();
-Console.WriteLine();
+WriteLine($"Do you want to use the Wake pin?");
+WriteLine("(Y)es,(N)o");
+pinChoice = ReadKey();
+WriteLine();
int pinWake = CheckAndAskPinNumber(pinChoice.KeyChar);
-Console.WriteLine($"Do you want to use the Reset pin?");
-Console.WriteLine("(Y)es,(N)o");
-pinChoice = Console.ReadKey();
-Console.WriteLine();
+WriteLine($"Do you want to use the Reset pin?");
+WriteLine("(Y)es,(N)o");
+pinChoice = ReadKey();
+WriteLine();
int pinReset = CheckAndAskPinNumber(pinChoice.KeyChar);
+Ccs811Sensor ccs811;
if (platformChoice.KeyChar == '1')
{
- Console.WriteLine("Creating an instance of a CCS811 using the platform drivers.");
+ WriteLine("Creating an instance of a CCS811 using the platform drivers.");
ccs811 = new Ccs811Sensor(I2cDevice.Create(new I2cConnectionSettings(3, addressChoice.KeyChar == '1' ? Ccs811Sensor.I2cFirstAddress : Ccs811Sensor.I2cSecondAddress)), pinWake: pinWake, pinInterruption: pinInterrupt, pinReset: pinReset);
}
else if (platformChoice.KeyChar == '2')
{
- Console.WriteLine("Creating an instance of a CCS811 using FT4222 drivers.");
+ WriteLine("Creating an instance of a CCS811 using FT4222 drivers.");
var ftdiI2C = new Ft4222I2c(new I2cConnectionSettings(0, addressChoice.KeyChar == '1' ? Ccs811Sensor.I2cFirstAddress : Ccs811Sensor.I2cSecondAddress));
var gpioController = new GpioController(PinNumberingScheme.Board, new Ft4222Gpio());
ccs811 = new Ccs811Sensor(ftdiI2C, gpioController, pinWake, pinInterrupt, pinReset, false);
}
else
{
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Error: Invalid platform choice.");
- Console.ResetColor();
+ ForegroundColor = ConsoleColor.Red;
+ WriteLine("Error: Invalid platform choice.");
+ ResetColor();
return;
}
-Console.WriteLine("Choose your operation mode:");
+WriteLine("Choose your operation mode:");
int i = 0;
OperationMode operationMode = OperationMode.ConstantPower1Second;
foreach (var mode in Enum.GetValues(typeof(OperationMode)))
{
- Console.WriteLine($" {i++}. {mode}");
+ WriteLine($" {i++}. {mode}");
}
-var modeChoice = Console.ReadKey();
+var modeChoice = ReadKey();
try
{
// Converting the char to decimal, removing '0' = 0x30
@@ -79,42 +79,42 @@
}
else
{
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine($"Error selecting mode, default {operationMode} will be selected");
+ ForegroundColor = ConsoleColor.Red;
+ WriteLine($"Error selecting mode, default {operationMode} will be selected");
}
}
catch (StackOverflowException)
{
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine($"Error selecting mode, default {operationMode} will be selected");
+ ForegroundColor = ConsoleColor.Yellow;
+ WriteLine($"Error selecting mode, default {operationMode} will be selected");
}
-Console.ResetColor();
-DisplayBasicInformatio(ccs811);
-Console.WriteLine($"Current operating mode: {ccs811.OperationMode}, changing for {operationMode}");
+ResetColor();
+DisplayBasicInformation(ccs811);
+WriteLine($"Current operating mode: {ccs811.OperationMode}, changing for {operationMode}");
ccs811.OperationMode = operationMode;
-Console.WriteLine($"Current operating mode: {ccs811.OperationMode}");
-Console.ForegroundColor = ConsoleColor.Yellow;
-Console.WriteLine($"Warning: the sensor needs to run for 48h in operation mode {OperationMode.ConstantPower1Second} before getting accurate results. " +
+WriteLine($"Current operating mode: {ccs811.OperationMode}");
+ForegroundColor = ConsoleColor.Yellow;
+WriteLine($"Warning: the sensor needs to run for 48h in operation mode {OperationMode.ConstantPower1Second} before getting accurate results. " +
$"Also, every time you'll start the sensor, it will need approximately 20 minutes to get accurate results as well");
-Console.ResetColor();
+ResetColor();
if (pinInterrupt >= 0)
{
- Console.WriteLine("Interruption mode selected.");
- Console.WriteLine("Do you want to enable Threshold interruption?");
- Console.WriteLine("(Y)es,(N)o");
- var threshChoice = Console.ReadKey();
- Console.WriteLine();
+ WriteLine("Interruption mode selected.");
+ WriteLine("Do you want to enable Threshold interruption?");
+ WriteLine("(Y)es,(N)o");
+ var threshChoice = ReadKey();
+ WriteLine();
if (threshChoice.KeyChar is 'Y' or 'y')
{
TestThresholdAndInterrupt(ccs811);
}
else
{
- Console.Write(", once a measurement will be available, it will be displayed. Press any key to exit the program.");
+ Write(", once a measurement will be available, it will be displayed. Press any key to exit the program.");
ccs811.MeasurementReady += Ccs811MeasurementReady;
- while (!Console.KeyAvailable)
+ while (!KeyAvailable)
{
Thread.Sleep(10);
}
@@ -122,16 +122,16 @@
}
else
{
- Console.WriteLine("What to you want to test?");
- Console.WriteLine(" 1. Read and display gas information for 10 times.");
- Console.WriteLine(" 2. Read and display gas information for 1000 times.");
- Console.WriteLine(" 3. Read and display detailed gas information for 10 times.");
- Console.WriteLine(" 4. Read and display detailed gas information for 1000 times.");
- Console.WriteLine(" 5. Read, load and change back the baseline.");
- Console.WriteLine(" 6. Test temperature and humidity changes.");
- Console.WriteLine(" 7. Read and log gas information 10000 times.");
- var operationChoice = Console.ReadKey();
- Console.WriteLine();
+ WriteLine("What to you want to test?");
+ WriteLine(" 1. Read and display gas information for 10 times.");
+ WriteLine(" 2. Read and display gas information for 1000 times.");
+ WriteLine(" 3. Read and display detailed gas information for 10 times.");
+ WriteLine(" 4. Read and display detailed gas information for 1000 times.");
+ WriteLine(" 5. Read, load and change back the baseline.");
+ WriteLine(" 6. Test temperature and humidity changes.");
+ WriteLine(" 7. Read and log gas information 10000 times.");
+ var operationChoice = ReadKey();
+ WriteLine();
switch (operationChoice.KeyChar)
{
case '1':
@@ -153,38 +153,38 @@
TestTemperatureHumidityAdjustment(ccs811);
break;
case '7':
- Console.WriteLine("Result file will be log.csv. The file is flushed on the disk every 100 results.");
+ WriteLine("Result file will be log.csv. The file is flushed on the disk every 100 results.");
ReadAndLog(ccs811, 10000);
break;
default:
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Error: Sorry, didn't get your choice, program will now exit.");
- Console.ResetColor();
+ ForegroundColor = ConsoleColor.Red;
+ WriteLine("Error: Sorry, didn't get your choice, program will now exit.");
+ ResetColor();
break;
}
}
-Console.WriteLine($"Current operating mode: {ccs811.OperationMode}, changing for {OperationMode.Idle}");
+WriteLine($"Current operating mode: {ccs811.OperationMode}, changing for {OperationMode.Idle}");
ccs811.OperationMode = OperationMode.Idle;
-Console.WriteLine($"Current operating mode: {ccs811.OperationMode}");
+WriteLine($"Current operating mode: {ccs811.OperationMode}");
// Dispose the CCS811 sensor
ccs811.Dispose();
-int CheckAndAskPinNumber(char toCehck)
+int CheckAndAskPinNumber(char toCheck)
{
- if (toCehck is 'Y' or 'y')
+ if (toCheck is 'Y' or 'y')
{
- Console.WriteLine("Type the GPIO number with pin numbering scheme, you want to use:");
- var pinInterChoice = Console.ReadLine();
+ WriteLine("Type the GPIO number with pin numbering scheme, you want to use:");
+ var pinInterChoice = ReadLine();
try
{
return Convert.ToInt32(pinInterChoice);
}
catch (OverflowException)
{
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Error: Can't convert your pin number.");
- Console.ResetColor();
+ ForegroundColor = ConsoleColor.Red;
+ WriteLine("Error: Can't convert your pin number.");
+ ResetColor();
}
}
@@ -193,58 +193,58 @@ int CheckAndAskPinNumber(char toCehck)
void Ccs811MeasurementReady(object sender, MeasurementArgs args)
{
- Console.WriteLine($"Measurement Event: Success: {args.MeasurementSuccess}, eCO2: {args.EquivalentCO2.PartsPerMillion} ppm, " +
+ WriteLine($"Measurement Event: Success: {args.MeasurementSuccess}, eCO2: {args.EquivalentCO2.PartsPerMillion} ppm, " +
$"eTVOC: {args.EquivalentTotalVolatileOrganicCompound.PartsPerBillion} ppb, Current: {args.RawCurrentSelected.Microamperes} µA, " +
$"ADC: {args.RawAdcReading} = {args.RawAdcReading * 1.65 / 1023} V.");
}
-void DisplayBasicInformatio(Ccs811Sensor ccs811)
+void DisplayBasicInformation(Ccs811Sensor ccs811)
{
- Console.WriteLine($"Hardware identification: 0x{ccs811.HardwareIdentification:X2}, must be 0x81");
- Console.WriteLine($"Hardware version: 0x{ccs811.HardwareVersion:X2}, must be 0x1X where any X is valid");
- Console.WriteLine($"Application version: {ccs811.ApplicationVersion}");
- Console.WriteLine($"Boot loader version: {ccs811.BootloaderVersion}");
+ WriteLine($"Hardware identification: 0x{ccs811.HardwareIdentification:X2}, must be 0x81");
+ WriteLine($"Hardware version: 0x{ccs811.HardwareVersion:X2}, must be 0x1X where any X is valid");
+ WriteLine($"Application version: {ccs811.ApplicationVersion}");
+ WriteLine($"Boot loader version: {ccs811.BootloaderVersion}");
}
void TestBaseline(Ccs811Sensor ccs811)
{
var baseline = ccs811.BaselineAlgorithmCalculation;
- Console.WriteLine($"Baseline calculation value: {baseline}, changing baseline");
+ WriteLine($"Baseline calculation value: {baseline}, changing baseline");
// Please refer to documentation, baseline is not a human readable number
ccs811.BaselineAlgorithmCalculation = 50300;
- Console.WriteLine($"Baseline calculation value: {ccs811.BaselineAlgorithmCalculation}, changing baseline for the previous one");
+ WriteLine($"Baseline calculation value: {ccs811.BaselineAlgorithmCalculation}, changing baseline for the previous one");
ccs811.BaselineAlgorithmCalculation = baseline;
- Console.WriteLine($"Baseline calculation value: {ccs811.BaselineAlgorithmCalculation}");
+ WriteLine($"Baseline calculation value: {ccs811.BaselineAlgorithmCalculation}");
}
void TestTemperatureHumidityAdjustment(Ccs811Sensor ccs811)
{
- Console.WriteLine("Drastically change the temperature and humidity to see the impact on the calculation " +
+ WriteLine("Drastically change the temperature and humidity to see the impact on the calculation " +
"In real life, we'll get normal data and won't change them that often. " +
"The system does not react the best way when shake like this");
// First use with the default ones, no changes should appear
Temperature temp = Temperature.FromDegreesCelsius(25);
Ratio hum = Ratio.FromPercent(50);
- Console.WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
+ WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
ccs811.SetEnvironmentData(temp, hum);
ReadAndDisplayDetails(ccs811, 100);
// Changing with very different temperature
temp = Temperature.FromDegreesCelsius(70);
hum = Ratio.FromPercent(53.8);
- Console.WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
+ WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
ccs811.SetEnvironmentData(temp, hum);
ReadAndDisplayDetails(ccs811, 100);
temp = Temperature.FromDegreesCelsius(-25);
hum = Ratio.FromPercent(0.5);
- Console.WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
+ WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
ccs811.SetEnvironmentData(temp, hum);
ReadAndDisplayDetails(ccs811, 100);
// Back to normal which still can lead to different results than initially
// This is due to the baseline
temp = Temperature.FromDegreesCelsius(25);
hum = Ratio.FromPercent(50);
- Console.WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
+ WriteLine($"Changing temperature and humidity reference to {temp.DegreesCelsius:0.00} C, {hum.Percent:0.0} %, baseline for calculation: {ccs811.BaselineAlgorithmCalculation}");
ccs811.SetEnvironmentData(temp, hum);
ReadAndDisplayDetails(ccs811, 100);
}
@@ -253,9 +253,9 @@ void TestThresholdAndInterrupt(Ccs811Sensor ccs811)
{
if (!ccs811.InterruptEnable)
{
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Error: interrupt needs to be activated to run this test");
- Console.ResetColor();
+ ForegroundColor = ConsoleColor.Red;
+ WriteLine("Error: interrupt needs to be activated to run this test");
+ ResetColor();
return;
}
@@ -263,10 +263,10 @@ void TestThresholdAndInterrupt(Ccs811Sensor ccs811)
// Setting up a range where we will see something in a normal environment
VolumeConcentration low = VolumeConcentration.FromPartsPerMillion(400);
VolumeConcentration high = VolumeConcentration.FromPartsPerMillion(600);
- Console.WriteLine($"Setting up {low.PartsPerMillion}-{high.PartsPerMillion} range, in clear environment, that should raise interrupts. Wait 3 minutes and change mode. Blow on the sensor and wait a bit.");
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine("Warning: only the first measurement to cross the threshold is raised.");
- Console.ResetColor();
+ WriteLine($"Setting up {low.PartsPerMillion}-{high.PartsPerMillion} range, in clear environment, that should raise interrupts. Wait 3 minutes and change mode. Blow on the sensor and wait a bit.");
+ ForegroundColor = ConsoleColor.Yellow;
+ WriteLine("Warning: only the first measurement to cross the threshold is raised.");
+ ResetColor();
ccs811.SetThreshold(low, high);
DateTime dt = DateTime.Now.AddMinutes(3);
while (dt > DateTime.Now)
@@ -276,7 +276,7 @@ void TestThresholdAndInterrupt(Ccs811Sensor ccs811)
low = VolumeConcentration.FromPartsPerMillion(15000);
high = VolumeConcentration.FromPartsPerMillion(20000);
- Console.WriteLine($"Changing threshold for {low.PartsPerMillion}-{high.PartsPerMillion}, a non reachable range in clear environment. No measurement should appear in next 3 minutes");
+ WriteLine($"Changing threshold for {low.PartsPerMillion}-{high.PartsPerMillion}, a non reachable range in clear environment. No measurement should appear in next 3 minutes");
dt = DateTime.Now.AddMinutes(3);
ccs811.SetThreshold(low, high);
while (dt > DateTime.Now)
@@ -301,7 +301,7 @@ void ReadAndLog(Ccs811Sensor ccs811, int count = 10)
var error = ccs811.TryReadGasData(out VolumeConcentration eCO2, out VolumeConcentration eTVOC, out ElectricCurrent curr, out int adc);
toWrite = $"{DateTime.Now};{error};{eCO2.PartsPerMillion};{eTVOC.PartsPerBillion};{curr.Microamperes};{adc};{adc * 1.65 / 1023};{ccs811.BaselineAlgorithmCalculation}";
fl.WriteLine(toWrite);
- Console.WriteLine(toWrite);
+ WriteLine(toWrite);
if (i % 100 == 0)
{
fl.Flush();
@@ -319,7 +319,7 @@ void ReadAnDisplay(Ccs811Sensor ccs811, int count = 10)
}
var error = ccs811.TryReadGasData(out VolumeConcentration eCO2, out VolumeConcentration eTVOC);
- Console.WriteLine($"Success: {error}, eCO2: {eCO2.PartsPerMillion} ppm, eTVOC: {eTVOC.PartsPerBillion} ppb");
+ WriteLine($"Success: {error}, eCO2: {eCO2.PartsPerMillion} ppm, eTVOC: {eTVOC.PartsPerBillion} ppb");
}
}
@@ -333,6 +333,6 @@ void ReadAndDisplayDetails(Ccs811Sensor ccs811, int count = 10)
}
var error = ccs811.TryReadGasData(out VolumeConcentration eCO2, out VolumeConcentration eTVOC, out ElectricCurrent curr, out int adc);
- Console.WriteLine($"Success: {error}, eCO2: {eCO2.PartsPerMillion} ppm, eTVOC: {eTVOC.PartsPerBillion} ppb, Current: {curr.Microamperes} µA, ADC: {adc} = {adc * 1.65 / 1023} V.");
+ WriteLine($"Success: {error}, eCO2: {eCO2.PartsPerMillion} ppm, eTVOC: {eTVOC.PartsPerBillion} ppb, Current: {curr.Microamperes} µA, ADC: {adc} = {adc * 1.65 / 1023} V.");
}
}
diff --git a/src/devices/CharacterLcd/Hd44780.cs b/src/devices/CharacterLcd/Hd44780.cs
index 93a9daae9a..099455199a 100644
--- a/src/devices/CharacterLcd/Hd44780.cs
+++ b/src/devices/CharacterLcd/Hd44780.cs
@@ -22,8 +22,6 @@ namespace Iot.Device.CharacterLcd
///
public class Hd44780 : ICharacterLcd, IDisposable
{
- private bool _disposed;
-
///
/// Command which can be used to clear the display
///
@@ -164,55 +162,38 @@ public virtual bool BacklightOn
///
/// Rows to be initialized
/// Array of offsets
- protected virtual byte[] InitializeRowOffsets(int rows)
+ // In one-line mode DDRAM addresses go from 0 - 79 [0x00 - 0x4F]
+ //
+ // In two-line mode DDRAM addresses are laid out as follows:
+ //
+ // First row: 0 - 39 [0x00 - 0x27]
+ // Second row: 64 - 103 [0x40 - 0x67]
+ //
+ // (The address gap presumably is to allow all second row addresses to be
+ // identifiable with one bit? Not sure what the value of that is.)
+ //
+ // The chipset doesn't natively support more than two rows. For tested
+ // four row displays the two rows are split as follows:
+ //
+ // First row: 0 - 19 [0x00 - 0x13]
+ // Second row: 64 - 83 [0x40 - 0x53]
+ // Third row: 20 - 39 [0x14 - 0x27] (Continues first row)
+ // Fourth row: 84 - 103 [0x54 - 0x67] (Continues second row)
+ protected virtual byte[] InitializeRowOffsets(int rows) => rows switch
{
- // In one-line mode DDRAM addresses go from 0 - 79 [0x00 - 0x4F]
- //
- // In two-line mode DDRAM addresses are laid out as follows:
- //
- // First row: 0 - 39 [0x00 - 0x27]
- // Second row: 64 - 103 [0x40 - 0x67]
- //
- // (The address gap presumably is to allow all second row addresses to be
- // identifiable with one bit? Not sure what the value of that is.)
- //
- // The chipset doesn't natively support more than two rows. For tested
- // four row displays the two rows are split as follows:
- //
- // First row: 0 - 19 [0x00 - 0x13]
- // Second row: 64 - 83 [0x40 - 0x53]
- // Third row: 20 - 39 [0x14 - 0x27] (Continues first row)
- // Fourth row: 84 - 103 [0x54 - 0x67] (Continues second row)
- byte[] rowOffsets;
-
- switch (rows)
- {
- case 1:
- rowOffsets = new byte[1];
- break;
- case 2:
- rowOffsets = new byte[] { 0, 64 };
- break;
- case 4:
- rowOffsets = new byte[] { 0, 64, 20, 84 };
- break;
- default:
- // We don't support other rows, users can derive for odd cases.
- // (Three row LCDs exist, but aren't common.)
- throw new ArgumentOutOfRangeException(nameof(rows));
- }
-
- return rowOffsets;
- }
+ 1 => new byte[1],
+ 2 => new byte[] { 0, 64 },
+ 4 => new byte[] { 0, 64, 20, 84 },
+ // We don't support other rows, users can derive for odd cases.
+ // (Three row LCDs exist, but aren't common.)
+ _ => throw new ArgumentOutOfRangeException(nameof(rows)),
+ };
///
/// Wait for the device to not be busy.
///
/// Time to wait if checking busy state isn't possible/practical.
- protected void WaitForNotBusy(int microseconds)
- {
- _lcdInterface.WaitForNotBusy(microseconds);
- }
+ protected void WaitForNotBusy(int microseconds) => _lcdInterface.WaitForNotBusy(microseconds);
///
/// Clears the LCD, returning the cursor to home and unshifting if shifted.
@@ -421,32 +402,12 @@ public void Write(string text)
/// Used if character translation already took place
///
/// Text to print
- public void Write(ReadOnlySpan text)
- {
- SendData(text);
- }
+ public void Write(ReadOnlySpan text) => SendData(text);
///
/// Releases unmanaged resources used by Hd44780
/// and optionally release managed resources
///
- /// to release both managed and unmanaged resources; to release only unmanaged resources.
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- _lcdInterface?.Dispose();
- }
- }
-
- ///
- public void Dispose()
- {
- if (!_disposed)
- {
- Dispose(true);
- _disposed = true;
- }
- }
+ public virtual void Dispose() => _lcdInterface?.Dispose();
}
}
diff --git a/src/devices/CharacterLcd/LcdCharacterEncoding.cs b/src/devices/CharacterLcd/LcdCharacterEncoding.cs
index e4c65393df..58d1ccd7b2 100644
--- a/src/devices/CharacterLcd/LcdCharacterEncoding.cs
+++ b/src/devices/CharacterLcd/LcdCharacterEncoding.cs
@@ -62,31 +62,18 @@ public LcdCharacterEncoding(string cultureName, string readOnlyMemoryName, Dicti
///
/// The list of pixel maps for extra characters that are required for this culture.
///
- public virtual List ExtraCharacters
- {
- get
- {
- return _extraCharacters;
- }
- }
+ public virtual List ExtraCharacters => _extraCharacters;
///
/// This is internally set to false if we already know that we won't be able to display all required characters
///
- protected internal bool AllCharactersSupported
- {
- get;
- set;
- }
+ protected internal bool AllCharactersSupported { get; set; }
///
/// Specified Name of the hardcoded character memory set for which this Encoding is intended. An encoding shall only be loaded to
/// a matching display.
///
- public string ReadOnlyMemoryName
- {
- get;
- }
+ public string ReadOnlyMemoryName { get; }
///
public override int GetByteCount(char[] chars, int index, int count)
@@ -105,7 +92,7 @@ public override int GetBytes(char[] chars, int charIndex, int charCount, byte[]
for (int i = 0; i < charCount; i++)
{
byte b;
- if (_characterMapping == null)
+ if (_characterMapping is null)
{
bytes[byteIndex] = (byte)chars[charIndex];
}
@@ -126,30 +113,18 @@ public override int GetBytes(char[] chars, int charIndex, int charCount, byte[]
}
///
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return Math.Min(bytes.Length, count);
- }
+ public override int GetCharCount(byte[] bytes, int index, int count) => Math.Min(bytes.Length, count);
///
/// Reverse mapping is not supported for this encoding.
///
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
- {
- throw new NotSupportedException("Reverse conversion not supported");
- }
+ public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) => throw new NotSupportedException("Reverse conversion not supported");
///
- public override int GetMaxByteCount(int charCount)
- {
- // This encoder always does a 1:1 mapping
- return charCount;
- }
+ // This encoder always does a 1:1 mapping
+ public override int GetMaxByteCount(int charCount) => charCount;
///
- public override int GetMaxCharCount(int byteCount)
- {
- return byteCount;
- }
+ public override int GetMaxCharCount(int byteCount) => byteCount;
}
}
diff --git a/src/devices/CharacterLcd/LcdCharacterEncodingFactory.cs b/src/devices/CharacterLcd/LcdCharacterEncodingFactory.cs
index b90c092f80..adc61ddc2d 100644
--- a/src/devices/CharacterLcd/LcdCharacterEncodingFactory.cs
+++ b/src/devices/CharacterLcd/LcdCharacterEncodingFactory.cs
@@ -27,16 +27,295 @@ static LcdCharacterEncodingFactory()
DefaultCustomMap = new Dictionary();
// The character map A00 contains the most used european letters, some greek math symbols plus japanese letters.
// Compare with the HD44780 specification sheet, page 17
- DefaultA00Map = new Dictionary();
+ DefaultA00Map = new Dictionary()
+ {
+ // Now the japanese characters in the A00 rom map.
+ // They use the same order than described in https://de.wikipedia.org/wiki/Japanische_Schrift#F%C3%BCnfzig-Laute-Tafel Table "Katakana", so the mapping sounds reasonable.
+ // Small letters
+ { 'ヽ', 0b1010_0100 },
+ { '・', 0b1010_0101 },
+ { 'ァ', 0b1010_0111 },
+ { 'ィ', 0b1010_1000 },
+ { 'ゥ', 0b1010_1001 },
+ { 'ェ', 0b1010_1010 },
+ { 'ォ', 0b1010_1011 },
+ { 'ャ', 0b1010_1100 },
+ { 'ュ', 0b1010_1101 },
+ { 'ョ', 0b1010_1110 },
+ { 'ヮ', 0b1010_1111 }, // Not sure on this one
+ // Normal letters
+ { 'ー', 0b1011_0000 },
+ { 'ア', 0b1011_0001 },
+ { 'イ', 0b1011_0010 },
+ { 'ウ', 0b1011_0011 },
+ { 'エ', 0b1011_0100 },
+ { 'オ', 0b1011_0101 },
+ { 'カ', 0b1011_0110 },
+ { 'キ', 0b1011_0111 },
+ { 'ク', 0b1011_1000 },
+ { 'ケ', 0b1011_1001 },
+ { 'コ', 0b1011_1010 },
+ { 'サ', 0b1011_1011 },
+ { 'シ', 0b1011_1100 },
+ { 'ス', 0b1011_1101 },
+ { 'セ', 0b1011_1110 },
+ { 'ソ', 0b1011_1111 },
+ { 'タ', 0b1100_0000 },
+ { 'チ', 0b1100_0001 },
+ { 'ツ', 0b1100_0010 },
+ { 'テ', 0b1100_0011 },
+ { 'ト', 0b1100_0100 },
+ { 'ナ', 0b1100_0101 },
+ { 'ニ', 0b1100_0110 },
+ { 'ヌ', 0b1100_0111 },
+ { 'ネ', 0b1100_1000 },
+ { 'ノ', 0b1100_1001 },
+ { 'ハ', 0b1100_1010 },
+ { 'ヒ', 0b1100_1011 },
+ { 'フ', 0b1100_1100 },
+ { 'ヘ', 0b1100_1101 },
+ { 'ホ', 0b1100_1110 },
+ { 'マ', 0b1100_1111 },
+ { 'ミ', 0b1101_0000 },
+ { 'ム', 0b1101_0001 },
+ { 'メ', 0b1101_0010 },
+ { 'モ', 0b1101_0011 },
+ { 'ヤ', 0b1101_0100 },
+ { 'ユ', 0b1101_0101 },
+ { 'ヨ', 0b1101_0110 },
+ { 'ラ', 0b1101_0111 },
+ { 'リ', 0b1101_1000 },
+ { 'ル', 0b1101_1001 },
+ { 'レ', 0b1101_1010 },
+ { 'ロ', 0b1101_1011 },
+ { 'ワ', 0b1101_1100 },
+ { 'ン', 0b1101_1101 }, // Characters ヰ and ヱ seem not to exist, they are not used in current japanese and can be replaced by イ and エ
+ { 'ヰ', 0b1011_0010 },
+ { 'ヱ', 0b1011_0100 },
+ { 'ヲ', 0b1010_0110 }, // This one is out of sequence
+ { '゛', 0b1101_1110 },
+ { '゜', 0b1101_1111 },
+ // break in character type
+ { '¥', 92 },
+ { '{', 123 },
+ { '|', 124 },
+ { '}', 125 },
+ { '\u2192', 126 }, // right arrow
+ { '\u2190', 127 }, // left arrow
+ // Note: Several letters may point to the same character code
+ { '–', 0b1011_0000 },
+ { 'α', 224 },
+ { 'ä', 225 },
+ { 'β', 226 },
+ { 'ε', 227 },
+ { 'μ', 228 },
+ { 'δ', 229 },
+ { 'ρ', 230 },
+ // Character 231 looks like a small q, but what should it be?
+ { '√', 232 },
+ // What is the match for chars 233, 234 and 235?
+ { '¢', 236 },
+ { 'ñ', 238 },
+ { 'ö', 239 },
+ // 240 and 241 look like p and q again. What are they?
+ { 'θ', 242 },
+ { '∞', 243 },
+ { 'Ω', 244 },
+ { 'Ω', 244 },
+ { 'ü', 245 },
+ { '∑', 246 },
+ { 'π', 247 },
+ // Some unrecognized characters here as well
+ { '÷', 253 },
+ { '×', (byte)'x' },
+ { '█', 255 },
+ { '°', 0b1101_1111 },
+ };
// Character map A02 contains about all characters used in western european languages, a few greek math symbols and some symbols.
// Compare with the HD44780 specification sheet, page 18.
// Note especially that this character map really uses the 8 pixel height of the characters, while the A00 map leaves the lowest
// pixel row usually empty for the cursor. The added space at the top of the character helps by better supporting diacritical symbols.
- DefaultA02Map = new Dictionary();
+ DefaultA02Map = new Dictionary()
+ {
+ // This map contains wide arrow characters. They could be helpful for menus, but not sure where to map them.
+ { '{', 123 },
+ { '|', 124 },
+ { '}', 125 },
+ { '~', 126 },
+ { '→', 0b0001_1010 }, // right arrow
+ { '←', 0b0001_1011 }, // left arrow
+ { '↑', 0b0001_1000 },
+ { '↓', 0b0001_1001 },
+ { '↲', 0b0001_0111 },
+ { '≤', 0b0001_1100 },
+ { '≥', 0b0001_1101 },
+ { '°', 0b1011_0000 },
+ // Cyrillic script, capital letters (russian, slawic languages)
+ { 'А', (byte)'A' },
+ { 'Б', 0b1000_0000 },
+ { 'В', (byte)'B' },
+ { 'Г', 0b1001_0010 },
+ { 'Д', 0b1000_0001 },
+ { 'Е', (byte)'E' },
+ { 'Ж', 0b1000_0010 },
+ { 'З', 0b1000_0011 },
+ { 'И', 0b1000_0100 },
+ { 'Й', 0b1000_0101 },
+ { 'К', (byte)'K' },
+ { 'Л', 0b1000_0110 },
+ { 'М', (byte)'M' },
+ { 'Н', (byte)'H' },
+ { 'О', (byte)'O' },
+ { 'П', 0b1000_0111 },
+ { 'Р', (byte)'P' },
+ { 'С', (byte)'C' },
+ { 'Т', (byte)'T' },
+ { 'У', 0b1000_1000 },
+ { 'Ф', 0b1111_1000 },
+ { 'Х', (byte)'X' },
+ { 'Ц', 0b1000_1001 },
+ { 'Ч', 0b1000_1010 },
+ { 'Ш', 0b1000_1011 },
+ { 'Щ', 0b1000_1100 },
+ { 'Ъ', 0b1000_1101 },
+ { 'Ы', 0b1000_1110 },
+ { 'Ь', (byte)'b' },
+ { 'Э', 0b1000_1111 },
+ { 'Ю', 0b1010_1100 },
+ { 'Я', 0b1010_1101 },
+ { 'μ', 0b1011_0101 },
+ { '¡', 0b1010_0001 },
+ { '¿', 0b1011_1111 },
+ // Cyrillic script, special letters
+ { 'Ё', 0b1100_1011 },
+ // Not available in ROM: ЂЃЄ
+ { 'Ѕ', (byte)'S' },
+ { 'І', (byte)'I' },
+ { 'Ї', 0b1100_1111 },
+ { 'Ј', (byte)'J' },
+ // Not available in ROM: ЉЊЋЌЏ
+ { 'Ў', 0b1101_1101 },
+ { '–', 0b0010_1101 },
+ { 'α', 0b1001_0000 },
+ { 'ε', 0b1001_1110 },
+ { 'δ', 0b1001_1011 },
+ { 'σ', 0b1001_0101 },
+ // 240 and 241 look like p and q again. What are they?
+ { 'θ', 0b1001_1001 },
+ { 'Ω', 0b1001_1010 },
+ { 'Ω', 0b1001_1010 },
+ { '∑', 0b1001_0100 },
+ { 'π', 0b1001_0011 },
+ // West european diacritics (german, spanish, french, scandinavian languages)
+ { 'À', 0b1100_0000 },
+ { 'Á', 0b1100_0001 },
+ { 'Â', 0b1100_0010 },
+ { 'Ã', 0b1100_0011 },
+ { 'Å', 0b1100_0100 },
+ { 'Æ', 0b1100_0101 },
+ { 'Ç', 0b1100_0111 },
+ { 'È', 0b1100_1000 },
+ { 'É', 0b1100_1001 },
+ { 'Ê', 0b1100_1010 },
+ { 'Ë', 0b1100_1011 },
+ { 'Ì', 0b1100_1100 },
+ { 'Í', 0b1100_1101 },
+ { 'Î', 0b1100_1110 },
+ { 'Ï', 0b1100_1111 },
+ { 'Đ', 0b1101_0000 },
+ { 'Ñ', 0b1101_0001 },
+ { 'Ò', 0b1101_0010 },
+ { 'Ó', 0b1101_0011 },
+ { 'Ô', 0b1101_0100 },
+ { 'Õ', 0b1101_0101 },
+ { 'Ö', 0b1101_0110 },
+ { '×', 0b1101_0111 },
+ { 'Ø', 0b1101_1000 },
+ { 'Ù', 0b1101_1001 },
+ { 'Ú', 0b1101_1010 },
+ { 'Û', 0b1101_1011 },
+ { 'Ü', 0b1101_1100 },
+ { 'Ý', 0b1101_1101 },
+ { 'Þ', 0b1101_1110 },
+ { 'ß', 0b1101_1111 },
+ // break in characters
+ { 'à', 0b1110_0000 },
+ { 'á', 0b1110_0001 },
+ { 'â', 0b1110_0010 },
+ { 'ã', 0b1110_0011 },
+ { 'å', 0b1110_0100 },
+ { 'æ', 0b1110_0101 },
+ { 'ç', 0b1110_0111 },
+ { 'è', 0b1110_1000 },
+ { 'é', 0b1110_1001 },
+ { 'ê', 0b1110_1010 },
+ { 'ë', 0b1110_1011 },
+ { 'ì', 0b1110_1100 },
+ { 'í', 0b1110_1101 },
+ { 'î', 0b1110_1110 },
+ { 'ï', 0b1110_1111 },
+ // break in characters
+ { 'đ', 0b1111_0000 },
+ { 'ð', 0b1111_0000 },
+ { 'ñ', 0b1111_0001 },
+ { 'ò', 0b1111_0010 },
+ { 'ó', 0b1111_0011 },
+ { 'ô', 0b1111_0100 },
+ { 'ö', 0b1111_0101 },
+ { '÷', 0b1111_0111 },
+ { 'ø', 0b1111_1000 },
+ { 'ù', 0b1111_1001 },
+ { 'ú', 0b1111_1010 },
+ { 'û', 0b1111_1011 },
+ { 'ü', 0b1111_1100 },
+ { 'ý', 0b1111_1101 },
+ { 'þ', 0b1111_1110 },
+ { 'ÿ', 0b1111_1111 },
+ };
// This map for instance can be found here: https://www.microchip.com/forums/m977852.aspx
- DefaultSplC780Map = new Dictionary();
+ DefaultSplC780Map = new Dictionary()
+ {
+ // Map for the SplC780
+ { '{', 123 },
+ { '|', 124 },
+ { '}', 125 },
+ { '~', 0126 },
+ { 'Ç', 0128 },
+ { 'ü', 0129 },
+ { 'é', 0130 },
+ { 'â', 0131 },
+ { 'å', 0131 },
+ { 'ä', 0132 },
+ { 'à', 0133 },
+ { 'ả', 0134 },
+ { 'ç', 0135 },
+ { 'ê', 0136 },
+ { 'ë', 0137 },
+ { 'è', 0138 },
+ { 'ï', 0139 },
+ { 'î', 0140 },
+ { 'ì', 0141 },
+ { 'Ä', 0142 },
+ { 'Å', 0143 },
+ { 'φ', 0xCD },
+ // Complete the set of capital greek letters for those that look like latin letters (note that these are not identity assignments)
+ { 'Α', (byte)'A' },
+ { 'Β', (byte)'B' },
+ { 'Ε', (byte)'E' },
+ { 'Ζ', (byte)'Z' },
+ { 'Η', (byte)'H' },
+ { 'Ι', (byte)'I' },
+ { 'Κ', (byte)'K' },
+ { 'Μ', (byte)'M' },
+ { 'Ν', (byte)'N' },
+ { 'Ο', (byte)'O' },
+ { 'Ρ', (byte)'P' },
+ { 'Τ', (byte)'T' },
+ { 'Υ', (byte)'Y' },
+ { 'Χ', (byte)'X' },
+ };
// Inserts ASCII characters ' ' to 'z', which are common to most known character sets
for (char c = ' '; c <= 'z'; c++)
@@ -49,182 +328,6 @@ static LcdCharacterEncodingFactory()
DefaultA00Map.Remove('\\'); // Instead of the backspace, the Yen letter is in the map, but we can use char 164 instead
DefaultA00Map.Add('\\', 164);
- DefaultA00Map.Add('¥', 92);
- DefaultA00Map.Add('{', 123);
- DefaultA00Map.Add('|', 124);
- DefaultA00Map.Add('}', 125);
- DefaultA00Map.Add('\u2192', 126); // right arrow
- DefaultA00Map.Add('\u2190', 127); // left arrow
- // Note: Several letters may point to the same character code
- DefaultA00Map.Add('–', 0b1011_0000);
- DefaultA00Map.Add('α', 224);
- DefaultA00Map.Add('ä', 225);
- DefaultA00Map.Add('β', 226);
- DefaultA00Map.Add('ε', 227);
- DefaultA00Map.Add('μ', 228);
- DefaultA00Map.Add('δ', 229);
- DefaultA00Map.Add('ρ', 230);
- // Character 231 looks like a small q, but what should it be?
- DefaultA00Map.Add('√', 232);
- // What is the match for chars 233, 234 and 235?
- DefaultA00Map.Add('¢', 236);
- DefaultA00Map.Add('ñ', 238);
- DefaultA00Map.Add('ö', 239);
-
- // 240 and 241 look like p and q again. What are they?
- DefaultA00Map.Add('θ', 242);
- DefaultA00Map.Add('∞', 243);
- DefaultA00Map.Add('Ω', 244);
- DefaultA00Map.Add('Ω', 244);
- DefaultA00Map.Add('ü', 245);
- DefaultA00Map.Add('∑', 246);
- DefaultA00Map.Add('π', 247);
- // Some unrecognized characters here as well
- DefaultA00Map.Add('÷', 253);
- DefaultA00Map.Add('×', (byte)'x');
- DefaultA00Map.Add('█', 255);
- DefaultA00Map.Add('°', 0b1101_1111);
-
- // Now the japanese characters in the A00 rom map.
- // They use the same order than described in https://de.wikipedia.org/wiki/Japanische_Schrift#F%C3%BCnfzig-Laute-Tafel Table "Katakana", so the mapping sounds reasonable.
-
- // Small letters
- DefaultA00Map.Add('ヽ', 0b1010_0100);
- DefaultA00Map.Add('・', 0b1010_0101);
- DefaultA00Map.Add('ァ', 0b1010_0111);
- DefaultA00Map.Add('ィ', 0b1010_1000);
- DefaultA00Map.Add('ゥ', 0b1010_1001);
- DefaultA00Map.Add('ェ', 0b1010_1010);
- DefaultA00Map.Add('ォ', 0b1010_1011);
- DefaultA00Map.Add('ャ', 0b1010_1100);
- DefaultA00Map.Add('ュ', 0b1010_1101);
- DefaultA00Map.Add('ョ', 0b1010_1110);
- DefaultA00Map.Add('ヮ', 0b1010_1111); // Not sure on this one
- // Normal letters
- DefaultA00Map.Add('ー', 0b1011_0000);
- DefaultA00Map.Add('ア', 0b1011_0001);
- DefaultA00Map.Add('イ', 0b1011_0010);
- DefaultA00Map.Add('ウ', 0b1011_0011);
- DefaultA00Map.Add('エ', 0b1011_0100);
- DefaultA00Map.Add('オ', 0b1011_0101);
- DefaultA00Map.Add('カ', 0b1011_0110);
- DefaultA00Map.Add('キ', 0b1011_0111);
- DefaultA00Map.Add('ク', 0b1011_1000);
- DefaultA00Map.Add('ケ', 0b1011_1001);
- DefaultA00Map.Add('コ', 0b1011_1010);
- DefaultA00Map.Add('サ', 0b1011_1011);
- DefaultA00Map.Add('シ', 0b1011_1100);
- DefaultA00Map.Add('ス', 0b1011_1101);
- DefaultA00Map.Add('セ', 0b1011_1110);
- DefaultA00Map.Add('ソ', 0b1011_1111);
- DefaultA00Map.Add('タ', 0b1100_0000);
- DefaultA00Map.Add('チ', 0b1100_0001);
- DefaultA00Map.Add('ツ', 0b1100_0010);
- DefaultA00Map.Add('テ', 0b1100_0011);
- DefaultA00Map.Add('ト', 0b1100_0100);
- DefaultA00Map.Add('ナ', 0b1100_0101);
- DefaultA00Map.Add('ニ', 0b1100_0110);
- DefaultA00Map.Add('ヌ', 0b1100_0111);
- DefaultA00Map.Add('ネ', 0b1100_1000);
- DefaultA00Map.Add('ノ', 0b1100_1001);
- DefaultA00Map.Add('ハ', 0b1100_1010);
- DefaultA00Map.Add('ヒ', 0b1100_1011);
- DefaultA00Map.Add('フ', 0b1100_1100);
- DefaultA00Map.Add('ヘ', 0b1100_1101);
- DefaultA00Map.Add('ホ', 0b1100_1110);
- DefaultA00Map.Add('マ', 0b1100_1111);
- DefaultA00Map.Add('ミ', 0b1101_0000);
- DefaultA00Map.Add('ム', 0b1101_0001);
- DefaultA00Map.Add('メ', 0b1101_0010);
- DefaultA00Map.Add('モ', 0b1101_0011);
- DefaultA00Map.Add('ヤ', 0b1101_0100);
- DefaultA00Map.Add('ユ', 0b1101_0101);
- DefaultA00Map.Add('ヨ', 0b1101_0110);
- DefaultA00Map.Add('ラ', 0b1101_0111);
- DefaultA00Map.Add('リ', 0b1101_1000);
- DefaultA00Map.Add('ル', 0b1101_1001);
- DefaultA00Map.Add('レ', 0b1101_1010);
- DefaultA00Map.Add('ロ', 0b1101_1011);
- DefaultA00Map.Add('ワ', 0b1101_1100);
- DefaultA00Map.Add('ン', 0b1101_1101); // Characters ヰ and ヱ seem not to exist, they are not used in current japanese and can be replaced by イ and エ
- DefaultA00Map.Add('ヰ', 0b1011_0010);
- DefaultA00Map.Add('ヱ', 0b1011_0100);
- DefaultA00Map.Add('ヲ', 0b1010_0110); // This one is out of sequence
- DefaultA00Map.Add('゛', 0b1101_1110);
- DefaultA00Map.Add('゜', 0b1101_1111);
-
- // This map contains wide arrow characters. They could be helpful for menus, but not sure where to map them.
- DefaultA02Map.Add('{', 123);
- DefaultA02Map.Add('|', 124);
- DefaultA02Map.Add('}', 125);
- DefaultA02Map.Add('~', 126);
- DefaultA02Map.Add('→', 0b0001_1010); // right arrow
- DefaultA02Map.Add('←', 0b0001_1011); // left arrow
- DefaultA02Map.Add('↑', 0b0001_1000);
- DefaultA02Map.Add('↓', 0b0001_1001);
- DefaultA02Map.Add('↲', 0b0001_0111);
- DefaultA02Map.Add('≤', 0b0001_1100);
- DefaultA02Map.Add('≥', 0b0001_1101);
- DefaultA02Map.Add('°', 0b1011_0000);
-
- // Cyrillic script, capital letters (russian, slawic languages)
- DefaultA02Map.Add('А', (byte)'A');
- DefaultA02Map.Add('Б', 0b1000_0000);
- DefaultA02Map.Add('В', (byte)'B');
- DefaultA02Map.Add('Г', 0b1001_0010);
- DefaultA02Map.Add('Д', 0b1000_0001);
- DefaultA02Map.Add('Е', (byte)'E');
- DefaultA02Map.Add('Ж', 0b1000_0010);
- DefaultA02Map.Add('З', 0b1000_0011);
- DefaultA02Map.Add('И', 0b1000_0100);
- DefaultA02Map.Add('Й', 0b1000_0101);
- DefaultA02Map.Add('К', (byte)'K');
- DefaultA02Map.Add('Л', 0b1000_0110);
- DefaultA02Map.Add('М', (byte)'M');
- DefaultA02Map.Add('Н', (byte)'H');
- DefaultA02Map.Add('О', (byte)'O');
- DefaultA02Map.Add('П', 0b1000_0111);
- DefaultA02Map.Add('Р', (byte)'P');
- DefaultA02Map.Add('С', (byte)'C');
- DefaultA02Map.Add('Т', (byte)'T');
- DefaultA02Map.Add('У', 0b1000_1000);
- DefaultA02Map.Add('Ф', 0b1111_1000);
- DefaultA02Map.Add('Х', (byte)'X');
- DefaultA02Map.Add('Ц', 0b1000_1001);
- DefaultA02Map.Add('Ч', 0b1000_1010);
- DefaultA02Map.Add('Ш', 0b1000_1011);
- DefaultA02Map.Add('Щ', 0b1000_1100);
- DefaultA02Map.Add('Ъ', 0b1000_1101);
- DefaultA02Map.Add('Ы', 0b1000_1110);
- DefaultA02Map.Add('Ь', (byte)'b');
- DefaultA02Map.Add('Э', 0b1000_1111);
- DefaultA02Map.Add('Ю', 0b1010_1100);
- DefaultA02Map.Add('Я', 0b1010_1101);
- DefaultA02Map.Add('μ', 0b1011_0101);
- DefaultA02Map.Add('¡', 0b1010_0001);
- DefaultA02Map.Add('¿', 0b1011_1111);
- // Cyrillic script, special letters
- DefaultA02Map.Add('Ё', 0b1100_1011);
- // Not available in ROM: ЂЃЄ
- DefaultA02Map.Add('Ѕ', (byte)'S');
- DefaultA02Map.Add('І', (byte)'I');
- DefaultA02Map.Add('Ї', 0b1100_1111);
- DefaultA02Map.Add('Ј', (byte)'J');
- // Not available in ROM: ЉЊЋЌЏ
- DefaultA02Map.Add('Ў', 0b1101_1101);
-
- DefaultA02Map.Add('–', 0b0010_1101);
- DefaultA02Map.Add('α', 0b1001_0000);
- DefaultA02Map.Add('ε', 0b1001_1110);
- DefaultA02Map.Add('δ', 0b1001_1011);
- DefaultA02Map.Add('σ', 0b1001_0101);
-
- // 240 and 241 look like p and q again. What are they?
- DefaultA02Map.Add('θ', 0b1001_1001);
- DefaultA02Map.Add('Ω', 0b1001_1010);
- DefaultA02Map.Add('Ω', 0b1001_1010);
- DefaultA02Map.Add('∑', 0b1001_0100);
- DefaultA02Map.Add('π', 0b1001_0011);
string cyrillicLettersSmall = "абвгдежзийклмнопрстуфхцчшщъыьэюяёђѓєѕіїјљњћќўџ";
string cyrillicLettersCapital = "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯЁЂЃЄЅІЇЈЉЊЋЌЎЏ";
@@ -241,95 +344,6 @@ static LcdCharacterEncodingFactory()
}
}
- // West european diacritics (german, spanish, french, scandinavian languages)
- DefaultA02Map.Add('À', 0b1100_0000);
- DefaultA02Map.Add('Á', 0b1100_0001);
- DefaultA02Map.Add('Â', 0b1100_0010);
- DefaultA02Map.Add('Ã', 0b1100_0011);
- DefaultA02Map.Add('Å', 0b1100_0100);
- DefaultA02Map.Add('Æ', 0b1100_0101);
- DefaultA02Map.Add('Ç', 0b1100_0111);
- DefaultA02Map.Add('È', 0b1100_1000);
- DefaultA02Map.Add('É', 0b1100_1001);
- DefaultA02Map.Add('Ê', 0b1100_1010);
- DefaultA02Map.Add('Ë', 0b1100_1011);
- DefaultA02Map.Add('Ì', 0b1100_1100);
- DefaultA02Map.Add('Í', 0b1100_1101);
- DefaultA02Map.Add('Î', 0b1100_1110);
- DefaultA02Map.Add('Ï', 0b1100_1111);
- DefaultA02Map.Add('Đ', 0b1101_0000);
- DefaultA02Map.Add('Ñ', 0b1101_0001);
- DefaultA02Map.Add('Ò', 0b1101_0010);
- DefaultA02Map.Add('Ó', 0b1101_0011);
- DefaultA02Map.Add('Ô', 0b1101_0100);
- DefaultA02Map.Add('Õ', 0b1101_0101);
- DefaultA02Map.Add('Ö', 0b1101_0110);
- DefaultA02Map.Add('×', 0b1101_0111);
- DefaultA02Map.Add('Ø', 0b1101_1000);
- DefaultA02Map.Add('Ù', 0b1101_1001);
- DefaultA02Map.Add('Ú', 0b1101_1010);
- DefaultA02Map.Add('Û', 0b1101_1011);
- DefaultA02Map.Add('Ü', 0b1101_1100);
- DefaultA02Map.Add('Ý', 0b1101_1101);
- DefaultA02Map.Add('Þ', 0b1101_1110);
- DefaultA02Map.Add('ß', 0b1101_1111);
-
- DefaultA02Map.Add('à', 0b1110_0000);
- DefaultA02Map.Add('á', 0b1110_0001);
- DefaultA02Map.Add('â', 0b1110_0010);
- DefaultA02Map.Add('ã', 0b1110_0011);
- DefaultA02Map.Add('å', 0b1110_0100);
- DefaultA02Map.Add('æ', 0b1110_0101);
- DefaultA02Map.Add('ç', 0b1110_0111);
- DefaultA02Map.Add('è', 0b1110_1000);
- DefaultA02Map.Add('é', 0b1110_1001);
- DefaultA02Map.Add('ê', 0b1110_1010);
- DefaultA02Map.Add('ë', 0b1110_1011);
- DefaultA02Map.Add('ì', 0b1110_1100);
- DefaultA02Map.Add('í', 0b1110_1101);
- DefaultA02Map.Add('î', 0b1110_1110);
- DefaultA02Map.Add('ï', 0b1110_1111);
-
- DefaultA02Map.Add('đ', 0b1111_0000);
- DefaultA02Map.Add('ð', 0b1111_0000);
- DefaultA02Map.Add('ñ', 0b1111_0001);
- DefaultA02Map.Add('ò', 0b1111_0010);
- DefaultA02Map.Add('ó', 0b1111_0011);
- DefaultA02Map.Add('ô', 0b1111_0100);
- DefaultA02Map.Add('ö', 0b1111_0101);
- DefaultA02Map.Add('÷', 0b1111_0111);
- DefaultA02Map.Add('ø', 0b1111_1000);
- DefaultA02Map.Add('ù', 0b1111_1001);
- DefaultA02Map.Add('ú', 0b1111_1010);
- DefaultA02Map.Add('û', 0b1111_1011);
- DefaultA02Map.Add('ü', 0b1111_1100);
- DefaultA02Map.Add('ý', 0b1111_1101);
- DefaultA02Map.Add('þ', 0b1111_1110);
- DefaultA02Map.Add('ÿ', 0b1111_1111);
-
- // Map for the SplC780
- DefaultSplC780Map.Add('{', 123);
- DefaultSplC780Map.Add('|', 124);
- DefaultSplC780Map.Add('}', 125);
- DefaultSplC780Map.Add('~', 0126);
- DefaultSplC780Map.Add('Ç', 0128);
- DefaultSplC780Map.Add('ü', 0129);
- DefaultSplC780Map.Add('é', 0130);
- DefaultSplC780Map.Add('â', 0131);
- DefaultSplC780Map.Add('å', 0131);
- DefaultSplC780Map.Add('ä', 0132);
- DefaultSplC780Map.Add('à', 0133);
- DefaultSplC780Map.Add('ả', 0134);
- DefaultSplC780Map.Add('ç', 0135);
- DefaultSplC780Map.Add('ê', 0136);
- DefaultSplC780Map.Add('ë', 0137);
- DefaultSplC780Map.Add('è', 0138);
- DefaultSplC780Map.Add('ï', 0139);
- DefaultSplC780Map.Add('î', 0140);
- DefaultSplC780Map.Add('ì', 0141);
- DefaultSplC780Map.Add('Ä', 0142);
- DefaultSplC780Map.Add('Å', 0143);
-
// A bit easier like this...
string toAdd = "ÉæÆôöòûùÿÖÜñÑ ¿"
+ "áíóú₡£¥₧ ¡ÃãÕõØø"
@@ -349,24 +363,6 @@ static LcdCharacterEncodingFactory()
startIndex++;
}
-
- DefaultSplC780Map.Add('φ', 0xCD);
-
- // Complete the set of capital greek letters for those that look like latin letters (note that these are not identity assignments)
- DefaultSplC780Map.Add('Α', (byte)'A');
- DefaultSplC780Map.Add('Β', (byte)'B');
- DefaultSplC780Map.Add('Ε', (byte)'E');
- DefaultSplC780Map.Add('Ζ', (byte)'Z');
- DefaultSplC780Map.Add('Η', (byte)'H');
- DefaultSplC780Map.Add('Ι', (byte)'I');
- DefaultSplC780Map.Add('Κ', (byte)'K');
- DefaultSplC780Map.Add('Μ', (byte)'M');
- DefaultSplC780Map.Add('Ν', (byte)'N');
- DefaultSplC780Map.Add('Ο', (byte)'O');
- DefaultSplC780Map.Add('Ρ', (byte)'P');
- DefaultSplC780Map.Add('Τ', (byte)'T');
- DefaultSplC780Map.Add('Υ', (byte)'Y');
- DefaultSplC780Map.Add('Χ', (byte)'X');
}
///
@@ -383,30 +379,21 @@ static LcdCharacterEncodingFactory()
/// The character specified as unknownLetter must be part of the mapping.
public LcdCharacterEncoding Create(CultureInfo culture, string romName, char unknownLetter, int maxNumberOfCustomCharacters)
{
- if (culture == null)
+ if (culture is null)
{
throw new ArgumentNullException(nameof(culture));
}
- Dictionary newMap;
// Need to copy the static map, we must not update that
- switch (romName)
+ Dictionary newMap = romName switch
{
- case "A00":
- newMap = new Dictionary(DefaultA00Map);
- break;
- case "A02":
- newMap = new Dictionary(DefaultA02Map);
- break;
- case "SplC780":
- newMap = new Dictionary(DefaultSplC780Map);
- break;
- default:
- newMap = new Dictionary(DefaultCustomMap);
- break;
- }
+ "A00" => new (DefaultA00Map),
+ "A02" => new (DefaultA02Map),
+ "SplC780" => new (DefaultSplC780Map),
+ _ => new (DefaultCustomMap),
+ };
- List extraCharacters = new List();
+ List extraCharacters = new ();
bool supported = AssignLettersForCurrentCulture(newMap, culture, romName, extraCharacters, maxNumberOfCustomCharacters);
if (!newMap.ContainsKey(unknownLetter))
@@ -427,7 +414,6 @@ private bool AssignLettersForCurrentCulture(Dictionary characterMapp
string specialLetters = SpecialLettersForCulture(culture, characterMapping); // Special letters this language group uses, in order of importance
byte charPos = 0;
- bool retValue = true;
foreach (var c in specialLetters)
{
if (!characterMapping.ContainsKey(c))
@@ -436,7 +422,7 @@ private bool AssignLettersForCurrentCulture(Dictionary characterMapp
if (charPos < maxNumberOfCustomCharacters)
{
var pixelMap = CreateLetter(c, romName);
- if (pixelMap != null)
+ if (pixelMap is object)
{
extraCharacters.Add(pixelMap);
characterMapping.Add(c, charPos);
@@ -444,17 +430,17 @@ private bool AssignLettersForCurrentCulture(Dictionary characterMapp
}
else
{
- retValue = false;
+ return false;
}
}
else
{
- retValue = false;
+ return false;
}
}
}
- return retValue;
+ return true;
}
///
@@ -525,26 +511,14 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
/// Creates the given letter for the given ROM type.
/// Overwrite this only if an alternate ROM is used.
///
- protected virtual byte[]? CreateLetter(char character, string romName)
+ protected virtual byte[]? CreateLetter(char character, string romName) => romName switch
{
- if (romName == "A00")
- {
- return CreateLetterA00(character);
- }
-
- if (romName == "A02")
- {
- return CreateLetterA02(character);
- }
-
- if (romName == "SplC780")
- {
- // The font looks identical, so we can use the same lookup table
- return CreateLetterA00(character);
- }
-
- return null;
- }
+ "A00" => CreateLetterA00(character),
+ "A02" => CreateLetterA02(character),
+ // The font looks identical, so we can use the same lookup table
+ "SplC780" => CreateLetterA00(character),
+ _ => null,
+ };
///
/// Creates the given letter from a pixel map for Rom Type A00 (7-pixel high letters, bottom row empty)
@@ -554,12 +528,9 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
///
/// Currently requires the characters to be hardcoded here. Would be nice if we could generate the pixel maps from an existing font, such as Consolas
///
- protected virtual byte[]? CreateLetterA00(char character)
+ protected virtual byte[]? CreateLetterA00(char character) => character switch
{
- switch (character)
- {
- case '€':
- return CreateCustomCharacter(
+ '€' => CreateCustomCharacter(
0b_00111,
0b_01000,
0b_11111,
@@ -567,9 +538,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_01000,
0b_00111,
- 0b_00000);
- case '£':
- return CreateCustomCharacter(
+ 0b_00000),
+ '£' => CreateCustomCharacter(
0b_00110,
0b_01001,
0b_01000,
@@ -577,10 +547,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01000,
0b_01000,
0b_11111,
- 0b_00000);
-
- case 'Ä':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'Ä' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_00100,
@@ -588,10 +556,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10001,
0b_10001,
- 0b_00000);
-
- case 'Ö':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'Ö' => CreateCustomCharacter(
0b_01010,
0b_01110,
0b_10001,
@@ -599,10 +565,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_01110,
- 0b_00000);
-
- case 'Ü':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'Ü' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_10001,
@@ -610,10 +574,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_01110,
- 0b_00000);
-
- case 'ß':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ß' => CreateCustomCharacter(
0b_00000,
0b_00110,
0b_01001,
@@ -621,10 +583,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01001,
0b_01001,
0b_10110,
- 0b_00000);
-
- case 'Å':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'Å' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_00100,
@@ -632,10 +592,9 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10001,
0b_10001,
- 0b_00000);
-
- case 'Â': // Same as above, cannot really distinguish them in the 7-pixel font (but they would not normally be used by the same languages)
- return CreateCustomCharacter(
+ 0b_00000),
+ // Same as above, cannot really distinguish them in the 7-pixel font (but they would not normally be used by the same languages)
+ 'Â' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_00100,
@@ -643,10 +602,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10001,
0b_10001,
- 0b_00000);
-
- case 'æ':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'æ' => CreateCustomCharacter(
0b_00000,
0b_00000,
0b_11010,
@@ -654,10 +611,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01111,
0b_10100,
0b_01011,
- 0b_00000);
-
- case 'Æ':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'Æ' => CreateCustomCharacter(
0b_00111,
0b_00100,
0b_01100,
@@ -665,10 +620,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11100,
0b_10100,
0b_10111,
- 0b_00000);
-
- case 'ø':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ø' => CreateCustomCharacter(
0b_00000,
0b_00000,
0b_01110,
@@ -676,10 +629,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10101,
0b_11001,
0b_01110,
- 0b_00000);
-
- case 'Ø':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'Ø' => CreateCustomCharacter(
0b_01110,
0b_10011,
0b_10011,
@@ -687,10 +638,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10101,
0b_11001,
0b_01110,
- 0b_00000);
-
- case 'à':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'à' => CreateCustomCharacter(
0b_00100,
0b_00010,
0b_01110,
@@ -698,10 +647,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01111,
0b_10001,
0b_01111,
- 0b_00000);
-
- case 'á':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'á' => CreateCustomCharacter(
0b_00100,
0b_01000,
0b_01110,
@@ -709,10 +656,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01111,
0b_10001,
0b_01111,
- 0b_00000);
-
- case 'â':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'â' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_01110,
@@ -720,10 +665,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01111,
0b_10001,
0b_01111,
- 0b_00000);
-
- case 'ä':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ä' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_01110,
@@ -731,10 +674,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01111,
0b_10001,
0b_01111,
- 0b_00000);
-
- case 'å':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'å' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_01110,
@@ -742,10 +683,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_01111,
0b_10001,
0b_01111,
- 0b_00000);
-
- case 'ç':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ç' => CreateCustomCharacter(
0b_00000,
0b_00000,
0b_01110,
@@ -753,10 +692,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10000,
0b_01111,
0b_00010,
- 0b_00110);
-
- case 'é':
- return CreateCustomCharacter(
+ 0b_00110),
+ 'é' => CreateCustomCharacter(
0b_00100,
0b_01000,
0b_01110,
@@ -764,10 +701,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10000,
0b_01111,
- 0b_00000);
-
- case 'è':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'è' => CreateCustomCharacter(
0b_00100,
0b_00010,
0b_01110,
@@ -775,10 +710,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10000,
0b_01111,
- 0b_00000);
-
- case 'ê':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ê' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_01110,
@@ -786,10 +719,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10000,
0b_01111,
- 0b_00000);
-
- case 'ë':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ë' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_01110,
@@ -797,10 +728,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_11111,
0b_10000,
0b_01111,
- 0b_00000);
-
- case 'ï':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ï' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_01100,
@@ -808,10 +737,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_00100,
0b_00100,
0b_01110,
- 0b_00000);
-
- case 'ì':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ì' => CreateCustomCharacter(
0b_00100,
0b_00010,
0b_01100,
@@ -819,10 +746,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_00100,
0b_00100,
0b_01110,
- 0b_00000);
-
- case 'í':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'í' => CreateCustomCharacter(
0b_00100,
0b_01000,
0b_01100,
@@ -830,10 +755,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_00100,
0b_00100,
0b_01110,
- 0b_00000);
-
- case 'î':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'î' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_01100,
@@ -841,10 +764,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_00100,
0b_00100,
0b_01110,
- 0b_00000);
-
- case 'ñ':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ñ' => CreateCustomCharacter(
0b_01010,
0b_00101,
0b_10000,
@@ -852,10 +773,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_10001,
- 0b_00000);
-
- case 'ö':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ö' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_01110,
@@ -863,10 +782,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_01110,
- 0b_00000);
-
- case 'ô':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ô' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_01110,
@@ -874,10 +791,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_01110,
- 0b_00000);
-
- case 'ò':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ò' => CreateCustomCharacter(
0b_00100,
0b_00010,
0b_01110,
@@ -885,10 +800,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_01110,
- 0b_00000);
-
- case 'ó':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ó' => CreateCustomCharacter(
0b_00100,
0b_01000,
0b_01110,
@@ -896,10 +809,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10001,
0b_01110,
- 0b_00000);
-
- case 'ú':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ú' => CreateCustomCharacter(
0b_00100,
0b_01000,
0b_10001,
@@ -907,10 +818,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10011,
0b_01101,
- 0b_00000);
-
- case 'ù':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ù' => CreateCustomCharacter(
0b_00100,
0b_00010,
0b_10001,
@@ -918,10 +827,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10011,
0b_01101,
- 0b_00000);
-
- case 'û':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'û' => CreateCustomCharacter(
0b_00100,
0b_01010,
0b_10001,
@@ -929,10 +836,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10011,
0b_01101,
- 0b_00000);
-
- case 'ü':
- return CreateCustomCharacter(
+ 0b_00000),
+ 'ü' => CreateCustomCharacter(
0b_01010,
0b_00000,
0b_10001,
@@ -940,10 +845,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10001,
0b_10011,
0b_01101,
- 0b_00000);
-
- case '¡':
- return CreateCustomCharacter(
+ 0b_00000),
+ '¡' => CreateCustomCharacter(
0b_00100,
0b_00000,
0b_00100,
@@ -951,10 +854,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_00100,
0b_00100,
0b_00100,
- 0b_00000);
-
- case '¿':
- return CreateCustomCharacter(
+ 0b_00000),
+ '¿' => CreateCustomCharacter(
0b_00100,
0b_00000,
0b_00100,
@@ -962,12 +863,9 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
0b_10000,
0b_10001,
0b_01110,
- 0b_00000);
-
- }
-
- return null;
- }
+ 0b_00000),
+ _ => throw new Exception("Character encoding not supported"),
+ };
///
/// Creates the given letter from a pixel map for Rom Type A02 (7 or 8 Pixel high letters, bottom row filled)
@@ -977,11 +875,8 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
///
/// Currently requires the characters to be hardcoded here. Would be nice if we could generate the pixel maps from an existing font, such as Consolas
///
- protected virtual byte[]? CreateLetterA02(char character)
- {
- // TODO: Create letters for A02 map, but that one is a lot better equipped for european languages, so nothing to do for the currently supported languages
- return null;
- }
+ // TODO: Create letters for A02 map, but that one is a lot better equipped for european languages, so nothing to do for the currently supported languages
+ protected virtual byte[]? CreateLetterA02(char character) => null;
///
/// Combines a set of bytes into a pixel map
@@ -1000,9 +895,7 @@ protected virtual string SpecialLettersForCulture(CultureInfo culture, Dictionar
/// 0b_00000)
///
///
- protected byte[] CreateCustomCharacter(byte byte0, byte byte1, byte byte2, byte byte3, byte byte4, byte byte5, byte byte6, byte byte7)
- {
- return new byte[] { byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7 };
- }
+ protected byte[] CreateCustomCharacter(byte byte0, byte byte1, byte byte2, byte byte3, byte byte4, byte byte5, byte byte6, byte byte7) =>
+ new byte[] { byte0, byte1, byte2, byte3, byte4, byte5, byte6, byte7 };
}
}
diff --git a/src/devices/CharacterLcd/LcdConsole.cs b/src/devices/CharacterLcd/LcdConsole.cs
index 0cf6663fc1..c712ea4a10 100644
--- a/src/devices/CharacterLcd/LcdConsole.cs
+++ b/src/devices/CharacterLcd/LcdConsole.cs
@@ -63,21 +63,13 @@ public LcdConsole(ICharacterLcd lcd, string romType, bool shouldDispose = true)
/// Position of the cursor, from left.
/// Note: May be outside the bounds of the display.
///
- public int CursorLeft
- {
- get;
- private set;
- }
+ public int CursorLeft { get; private set; }
///
/// Position of the cursor, from top
/// Note: May be outside the bounds of the display.
///
- public int CursorTop
- {
- get;
- private set;
- }
+ public int CursorTop { get; private set; }
///
/// If this is larger than zero, an a wait is introduced each time the display wraps to the next line or scrolls up. Can be used to print long texts to the display,
@@ -85,11 +77,7 @@ public int CursorTop
///
public TimeSpan ScrollUpDelay
{
- get
- {
- return _scrollUpDelay;
- }
-
+ get => _scrollUpDelay;
set
{
if (value < TimeSpan.Zero)
@@ -149,10 +137,7 @@ public bool DisplayOn
///
public LineWrapMode LineFeedMode
{
- get
- {
- return _lineFeedMode;
- }
+ get => _lineFeedMode;
set
{
_lineFeedMode = value;
@@ -162,10 +147,7 @@ public LineWrapMode LineFeedMode
///
/// Size of the display
///
- public Size Size
- {
- get;
- }
+ public Size Size { get; }
private void ClearStringBuffer()
{
@@ -233,7 +215,7 @@ public void SetCursorPosition(int left, int top)
///
public void Write(string text)
{
- if (text == null)
+ if (text is null)
{
throw new ArgumentNullException(nameof(text));
}
@@ -476,15 +458,8 @@ private void WriteCurrentLine(string line)
/// The maximum number of custom characters supported by the hardware.
/// Character encoding factory that delivers the mapping of the Char type to the hardware ROM character codes. May add special characters into
/// the character ROM. Default: Null (Use internal factory)
- public static LcdCharacterEncoding CreateEncoding(CultureInfo culture, string romType, char unknownCharacter = '?', int maxNumberOfCustomCharacters = 8, LcdCharacterEncodingFactory? factory = null)
- {
- if (factory == null)
- {
- factory = new LcdCharacterEncodingFactory();
- }
-
- return factory.Create(culture, romType, unknownCharacter, maxNumberOfCustomCharacters);
- }
+ public static LcdCharacterEncoding CreateEncoding(CultureInfo culture, string romType, char unknownCharacter = '?', int maxNumberOfCustomCharacters = 8, LcdCharacterEncodingFactory? factory = null) =>
+ (factory ?? new LcdCharacterEncodingFactory()).Create(culture, romType, unknownCharacter, maxNumberOfCustomCharacters);
///
/// Loads the specified encoding.
@@ -495,8 +470,7 @@ public static LcdCharacterEncoding CreateEncoding(CultureInfo culture, string ro
/// See true if the encoding was correctly loaded.
public bool LoadEncoding(Encoding encoding)
{
- LcdCharacterEncoding? lcdCharacterEncoding = encoding as LcdCharacterEncoding;
- if (lcdCharacterEncoding != null)
+ if (encoding is LcdCharacterEncoding lcdCharacterEncoding)
{
return LoadEncoding(encoding);
}
@@ -520,14 +494,14 @@ public bool LoadEncoding(LcdCharacterEncoding encoding)
bool allCharactersLoaded = encoding.AllCharactersSupported;
lock (_lock)
{
- int numberOfCharctersToLoad = Math.Min(encoding.ExtraCharacters.Count, _lcd.NumberOfCustomCharactersSupported);
- if (numberOfCharctersToLoad < encoding.ExtraCharacters.Count)
+ int numberOfCharactersToLoad = Math.Min(encoding.ExtraCharacters.Count, _lcd.NumberOfCustomCharactersSupported);
+ if (numberOfCharactersToLoad < encoding.ExtraCharacters.Count)
{
- // We can't completelly load that encoding, because there are not enough custom slots.
+ // We can't completely load that encoding, because there are not enough custom slots.
allCharactersLoaded = false;
}
- for (byte i = 0; i < numberOfCharctersToLoad; i++)
+ for (byte i = 0; i < numberOfCharactersToLoad; i++)
{
byte[] pixelMap = encoding.ExtraCharacters[i];
_lcd.CreateCustomCharacter(i, pixelMap);
@@ -553,7 +527,7 @@ public void ResetEncoding()
private byte[] MapChars(string line)
{
byte[] buffer = new byte[line.Length];
- if (_characterEncoding == null)
+ if (_characterEncoding is null)
{
for (int i = 0; i < line.Length; i++)
{
@@ -575,7 +549,7 @@ public void Dispose()
{
if (_shouldDispose)
{
- _lcd.Dispose();
+ _lcd?.Dispose();
}
GC.SuppressFinalize(this);
diff --git a/src/devices/CharacterLcd/LcdInterface.Gpio.cs b/src/devices/CharacterLcd/LcdInterface.Gpio.cs
index 15c3d6f5f1..fdbfc823dc 100644
--- a/src/devices/CharacterLcd/LcdInterface.Gpio.cs
+++ b/src/devices/CharacterLcd/LcdInterface.Gpio.cs
@@ -62,10 +62,10 @@ public Gpio(int registerSelectPin, int enablePin, int[] dataPins, int backlightP
}
else if (dataPins.Length != 4)
{
- throw new ArgumentException($"The length of the array given to parameter {nameof(dataPins)} must be 4 or 8");
+ throw new ArgumentException(nameof(dataPins), "The length of the array must be 4 or 8.");
}
- _shouldDispose = controller == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || controller is null;
_controller = controller ?? new GpioController(PinNumberingScheme.Logical);
Initialize();
@@ -145,10 +145,7 @@ private void Initialize()
public override bool BacklightOn
{
- get
- {
- return _backlight != -1 && _controller.Read(_backlight) == PinValue.High;
- }
+ get => _backlight != -1 && _controller.Read(_backlight) == PinValue.High;
set
{
if (_backlight != -1)
diff --git a/src/devices/CharacterLcd/LcdInterface.I2c.cs b/src/devices/CharacterLcd/LcdInterface.I2c.cs
index 971604509c..b12318999c 100644
--- a/src/devices/CharacterLcd/LcdInterface.I2c.cs
+++ b/src/devices/CharacterLcd/LcdInterface.I2c.cs
@@ -45,25 +45,18 @@ private enum ControlByteFlags : byte
// scheme (Sitronix ST7036, Aiptek AIP31068L, probably others).
private readonly I2cDevice _device;
- public I2c(I2cDevice device)
- {
- _device = device;
-
- // While the LCD controller can be set to 4 bit mode there really isn't a way to
- // mess with that from the I2c pins as far as I know. Other drivers try to set the
- // controller up for 8 bit mode, but it appears they are doing so only because they've
- // copied existing HD44780 drivers.
- }
+ // While the LCD controller can be set to 4 bit mode there really isn't a way to
+ // mess with that from the I2c pins as far as I know. Other drivers try to set the
+ // controller up for 8 bit mode, but it appears they are doing so only because they've
+ // copied existing HD44780 drivers.
+ public I2c(I2cDevice device) => _device = device;
public override bool EightBitMode => true;
public override bool BacklightOn
{
- get
- {
- // Setting the backlight on or off is not supported with 8 bit commands, according to the docs.
- return true;
- }
+ // Setting the backlight on or off is not supported with 8 bit commands, according to the docs.
+ get => true;
set
{
// Ignore setting the backlight. Exceptions are not expected by user code here, as it is normal to
diff --git a/src/devices/CharacterLcd/LcdInterface.I2c4Bit.cs b/src/devices/CharacterLcd/LcdInterface.I2c4Bit.cs
index 0b30058db7..85eeef1c09 100644
--- a/src/devices/CharacterLcd/LcdInterface.I2c4Bit.cs
+++ b/src/devices/CharacterLcd/LcdInterface.I2c4Bit.cs
@@ -31,12 +31,12 @@ private class I2c4Bit : LcdInterface
private const byte LCD_ENTRYLEFT = 0x02;
private const byte LCD_4BITMODE = 0x00;
- private readonly I2cDevice _device;
+ private readonly I2cDevice _i2cDevice;
private bool _backlightOn;
- public I2c4Bit(I2cDevice device)
+ public I2c4Bit(I2cDevice i2cDevice)
{
- _device = device;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_backlightOn = true;
InitDisplay();
}
@@ -49,10 +49,7 @@ public I2c4Bit(I2cDevice device)
///
public override bool BacklightOn
{
- get
- {
- return _backlightOn;
- }
+ get => _backlightOn;
set
{
_backlightOn = value;
@@ -105,8 +102,8 @@ public override void SendCommand(byte command)
private void Write4Bits(byte command)
{
- _device.WriteByte((byte)(command | ENABLE | BacklightFlag));
- _device.WriteByte((byte)((command & ~ENABLE) | BacklightFlag));
+ _i2cDevice.WriteByte((byte)(command | ENABLE | BacklightFlag));
+ _i2cDevice.WriteByte((byte)((command & ~ENABLE) | BacklightFlag));
}
public override void SendCommands(ReadOnlySpan commands)
diff --git a/src/devices/CharacterLcd/LcdInterface.cs b/src/devices/CharacterLcd/LcdInterface.cs
index 593e752204..9aaebe50f8 100644
--- a/src/devices/CharacterLcd/LcdInterface.cs
+++ b/src/devices/CharacterLcd/LcdInterface.cs
@@ -113,7 +113,7 @@ public void Dispose()
///
/// Creates a GPIO based interface for the LCD.
///
- /// The pin that controls the regsiter select.
+ /// The pin that controls the register select.
/// The pin that controls the enable switch.
/// Collection of pins holding the data that will be printed on the screen.
/// The optional pin that controls the backlight of the display.
diff --git a/src/devices/CharacterLcd/LcdRgb.cs b/src/devices/CharacterLcd/LcdRgb.cs
index 674defe9c9..e9ade74b4d 100644
--- a/src/devices/CharacterLcd/LcdRgb.cs
+++ b/src/devices/CharacterLcd/LcdRgb.cs
@@ -121,10 +121,10 @@ public void SetBacklightColor(Color color)
}
///
- protected override void Dispose(bool disposing)
+ public override void Dispose()
{
_rgbDevice?.Dispose();
- base.Dispose(disposing);
+ base.Dispose();
}
}
}
diff --git a/src/devices/CharacterLcd/samples/Hd44780.ExtendedSample.cs b/src/devices/CharacterLcd/samples/Hd44780.ExtendedSample.cs
index 1eb3844d0b..69deacfa56 100644
--- a/src/devices/CharacterLcd/samples/Hd44780.ExtendedSample.cs
+++ b/src/devices/CharacterLcd/samples/Hd44780.ExtendedSample.cs
@@ -189,8 +189,7 @@ private static void PerfTests(Hd44780 lcd)
private static void SetBacklightColorTest(Hd44780 lcd)
{
- var colorLcd = lcd as LcdRgb;
- if (colorLcd == null)
+ if (lcd is not LcdRgb colorLcd)
{
Console.WriteLine("Color backlight not supported");
return;
diff --git a/src/devices/CharacterLcd/samples/LcdConsole.Samples.cs b/src/devices/CharacterLcd/samples/LcdConsole.Samples.cs
index 4668dcf3ea..94b88a1a05 100644
--- a/src/devices/CharacterLcd/samples/LcdConsole.Samples.cs
+++ b/src/devices/CharacterLcd/samples/LcdConsole.Samples.cs
@@ -82,12 +82,12 @@ public static void WriteTest(ICharacterLcd lcd)
console.ReplaceLine(1, printTime);
left--;
// Each full minute, blink the display (but continue writing the time)
- if (now.Second == 0 && alertTask == null)
+ if (now.Second == 0 && alertTask is null)
{
alertTask = console.BlinkDisplayAsync(3);
}
- if (alertTask != null && alertTask.IsCompleted)
+ if (alertTask is object && alertTask.IsCompleted)
{
// Ensure we catch any exceptions (there shouldn't be any...)
alertTask.Wait();
diff --git a/src/devices/CharacterLcd/samples/Pcf8574tSample.cs b/src/devices/CharacterLcd/samples/Pcf8574tSample.cs
index ce4dcad884..55125b6338 100644
--- a/src/devices/CharacterLcd/samples/Pcf8574tSample.cs
+++ b/src/devices/CharacterLcd/samples/Pcf8574tSample.cs
@@ -16,8 +16,8 @@ internal class Pcf8574tSample
{
private const string Twenty = "123456789\u0008123456789\u0009";
private const string Thirty = Twenty + "123456789\u000a";
- private const string Fourty = Thirty + "123456789\u000b";
- private const string Eighty = Fourty + "123456789\u000c123456789\u000d123456789\u000e123456789\u000f";
+ private const string Forty = Thirty + "123456789\u000b";
+ private const string Eighty = Forty + "123456789\u000c123456789\u000d123456789\u000e123456789\u000f";
public static void SampleEntryPoint()
{
@@ -49,11 +49,11 @@ public static void SampleEntryPoint()
// Long string
TestPrompt("Twenty", lcd, l => l.Write(Twenty));
- TestPrompt("Fourty", lcd, l => l.Write(Fourty));
+ TestPrompt("Forty", lcd, l => l.Write(Forty));
TestPrompt("Eighty", lcd, l => l.Write(Eighty));
TestPrompt("Twenty-", lcd, l => WriteFromEnd(l, Twenty));
- TestPrompt("Fourty-", lcd, l => WriteFromEnd(l, Fourty));
+ TestPrompt("Forty-", lcd, l => WriteFromEnd(l, Forty));
TestPrompt("Eighty-", lcd, l => WriteFromEnd(l, Eighty));
TestPrompt("Wrap", lcd, l => l.Write(new string('*', 80) + ">>>>>"));
diff --git a/src/devices/CharacterLcd/samples/Program.cs b/src/devices/CharacterLcd/samples/Program.cs
index c902070e98..364188093d 100644
--- a/src/devices/CharacterLcd/samples/Program.cs
+++ b/src/devices/CharacterLcd/samples/Program.cs
@@ -24,8 +24,8 @@ void UsingGpioPins()
void UsingMcp()
{
- using I2cDevice i2CDevice = I2cDevice.Create(new I2cConnectionSettings(1, 0x21));
- using Mcp23008 driver = new Mcp23008(i2CDevice);
+ using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(1, 0x21));
+ using Mcp23008 driver = new (i2cDevice);
int[] dataPins = { 3, 4, 5, 6 };
int registerSelectPin = 1;
int enablePin = 2;
@@ -40,8 +40,8 @@ void UsingMcp()
void UsingHd44780OverI2C()
{
- using I2cDevice i2CDevice = I2cDevice.Create(new I2cConnectionSettings(1, 0x27));
- using LcdInterface lcdInterface = LcdInterface.CreateI2c(i2CDevice, false);
+ using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(1, 0x27));
+ using LcdInterface lcdInterface = LcdInterface.CreateI2c(i2cDevice, false);
using Hd44780 hd44780 = new Lcd2004(lcdInterface);
hd44780.UnderlineCursorVisible = false;
hd44780.BacklightOn = true;
diff --git a/src/devices/Charlieplex/CharlieplexSegment.cs b/src/devices/Charlieplex/CharlieplexSegment.cs
index ec66839a62..6dba8a766c 100644
--- a/src/devices/Charlieplex/CharlieplexSegment.cs
+++ b/src/devices/Charlieplex/CharlieplexSegment.cs
@@ -15,7 +15,7 @@ public class CharlieplexSegment : IDisposable
private readonly int[] _pins;
private readonly CharlieplexSegmentNode[] _nodes;
private readonly int _nodeCount;
- private GpioController _controller;
+ private GpioController _gpioController;
private CharlieplexSegmentNode _lastNode;
///
@@ -29,13 +29,13 @@ public CharlieplexSegment(int[] pins, int nodeCount = 0, GpioController? gpioCo
{
if (pins.Length < 2)
{
- throw new ArgumentException($"{nameof(CharlieplexSegment)}: 2 or more pins must be provided.");
+ throw new ArgumentException(nameof(CharlieplexSegment), "2 or more pins must be provided.");
}
int charlieCount = (int)Math.Pow(pins.Length, 2) - pins.Length;
if (nodeCount > charlieCount)
{
- throw new ArgumentException($"{nameof(CharlieplexSegment)}: maximum count is {charlieCount} based on {pins.Length} pins. {nodeCount} was specified as the count.");
+ throw new ArgumentException(nameof(CharlieplexSegment), $"Maximum count is {charlieCount} based on {pins.Length} pins. {nodeCount} was specified as the count.");
}
if (nodeCount == 0)
@@ -43,20 +43,18 @@ public CharlieplexSegment(int[] pins, int nodeCount = 0, GpioController? gpioCo
nodeCount = charlieCount;
}
- if (gpioController is null)
- {
- gpioController = new GpioController();
- }
+ _shouldDispose = shouldDispose || gpioController is null;
+ _gpioController = gpioController ?? new ();
// first two pins will be needed as Output.
- gpioController.OpenPin(pins[0], PinMode.Output);
- gpioController.OpenPin(pins[1], PinMode.Output);
+ _gpioController.OpenPin(pins[0], PinMode.Output);
+ _gpioController.OpenPin(pins[1], PinMode.Output);
// remaining pins should be input type
// prevents participating in the circuit until needed
for (int i = 2; i < pins.Length; i++)
{
- gpioController.OpenPin(pins[i], PinMode.Input);
+ _gpioController.OpenPin(pins[i], PinMode.Input);
}
_lastNode = new CharlieplexSegmentNode()
@@ -64,8 +62,6 @@ public CharlieplexSegment(int[] pins, int nodeCount = 0, GpioController? gpioCo
Anode = pins[1],
Cathode = pins[0]
};
- _controller = gpioController;
- _shouldDispose = shouldDispose;
_pins = pins;
_nodeCount = nodeCount;
_nodes = GetNodes(pins, nodeCount);
@@ -120,29 +116,29 @@ Cases to consider
// skip updating pinmode when possible
if (_lastNode.Anode != node.Anode && _lastNode.Anode != node.Cathode)
{
- _controller.SetPinMode(_lastNode.Anode, PinMode.Input);
+ _gpioController.SetPinMode(_lastNode.Anode, PinMode.Input);
}
if (_lastNode.Cathode != node.Anode && _lastNode.Cathode != node.Cathode)
{
- _controller.SetPinMode(_lastNode.Cathode, PinMode.Input);
+ _gpioController.SetPinMode(_lastNode.Cathode, PinMode.Input);
}
if (node.Cathode != _lastNode.Anode && node.Cathode != _lastNode.Cathode)
{
- _controller.SetPinMode(node.Cathode, PinMode.Output);
+ _gpioController.SetPinMode(node.Cathode, PinMode.Output);
}
if (node.Anode != _lastNode.Anode && node.Anode != _lastNode.Cathode)
{
- _controller.SetPinMode(node.Anode, PinMode.Output);
+ _gpioController.SetPinMode(node.Anode, PinMode.Output);
}
- _controller.Write(node.Anode, node.Value);
+ _gpioController.Write(node.Anode, node.Value);
// It is necessary to sleep for the LED to be seen with full brightness
// It may be possible to sleep less than 1ms -- this API has ms granularity
Thread.Sleep(1);
- _controller.Write(node.Anode, 0);
+ _gpioController.Write(node.Anode, 0);
_lastNode.Anode = node.Anode;
_lastNode.Cathode = node.Cathode;
}
@@ -210,8 +206,8 @@ public void Dispose()
// this condition only applies to GPIO devices
if (_shouldDispose)
{
- _controller?.Dispose();
- _controller = null!;
+ _gpioController?.Dispose();
+ _gpioController = null!;
}
}
}
diff --git a/src/devices/Charlieplex/samples/Program.cs b/src/devices/Charlieplex/samples/Program.cs
index 43ce8b25ba..88d79c670f 100644
--- a/src/devices/Charlieplex/samples/Program.cs
+++ b/src/devices/Charlieplex/samples/Program.cs
@@ -6,14 +6,14 @@
var pins = new int[] { 6, 13, 19 };
var charlieSegmentLength = 6;
// calling this method helps with determing the correct pin circuit to use
-var nodes = CharlieplexSegment.GetNodes(pins, charlieSegmentLength);
+CharlieplexSegmentNode[] nodes = CharlieplexSegment.GetNodes(pins, charlieSegmentLength);
for (int i = 0; i < charlieSegmentLength; i++)
{
- var node = nodes[i];
+ CharlieplexSegmentNode node = nodes[i];
Console.WriteLine($"Node {i} -- Anode: {node.Anode}; Cathode: {node.Cathode}");
}
-using var charlie = new CharlieplexSegment(pins, charlieSegmentLength);
+using CharlieplexSegment charlie = new (pins, charlieSegmentLength);
var twoSeconds = TimeSpan.FromSeconds(2);
Console.WriteLine("Light all LEDs");
diff --git a/src/devices/Charlieplex/tests/CharlieplexLayout.cs b/src/devices/Charlieplex/tests/CharlieplexLayout.cs
index 8c95287045..8c86ff1244 100644
--- a/src/devices/Charlieplex/tests/CharlieplexLayout.cs
+++ b/src/devices/Charlieplex/tests/CharlieplexLayout.cs
@@ -1,6 +1,6 @@
using System;
-using Xunit;
using Iot.Device.Multiplexing;
+using Xunit;
namespace Charlietests
{
@@ -11,7 +11,7 @@ public void TwoPinLayout()
{
var pins = new int[] { 1, 2 };
- var nodes = CharlieplexSegment.GetNodes(pins);
+ CharlieplexSegmentNode[] nodes = CharlieplexSegment.GetNodes(pins);
Assert.True(nodes.Length == 2);
Assert.True(nodes[0].Anode == 1 && nodes[0].Cathode == 2);
Assert.True(nodes[1].Anode == 2 && nodes[1].Cathode == 1);
@@ -22,7 +22,7 @@ public void ThreePinLayout()
{
var pins = new int[] { 1, 2, 3 };
- var nodes = CharlieplexSegment.GetNodes(pins);
+ CharlieplexSegmentNode[] nodes = CharlieplexSegment.GetNodes(pins);
Assert.True(nodes.Length == 6);
Assert.True(nodes[0].Anode == 1 && nodes[0].Cathode == 2);
Assert.True(nodes[1].Anode == 2 && nodes[1].Cathode == 1);
@@ -36,7 +36,7 @@ public void ThreePinLayout()
public void FourPinLayout()
{
var pins = new int[] { 1, 2, 3, 4 };
- var nodes = CharlieplexSegment.GetNodes(pins);
+ CharlieplexSegmentNode[] nodes = CharlieplexSegment.GetNodes(pins);
Assert.True(true);
Assert.True(nodes.Length == 12);
Assert.True(nodes[0].Anode == 1 && nodes[0].Cathode == 2);
@@ -57,7 +57,7 @@ public void FourPinLayout()
public void FivePinLayout()
{
var pins = new int[] { 1, 2, 3, 4, 5 };
- var nodes = CharlieplexSegment.GetNodes(pins);
+ CharlieplexSegmentNode[] nodes = CharlieplexSegment.GetNodes(pins);
Assert.True(true);
Assert.True(nodes.Length == 20);
Assert.True(nodes[0].Anode == 1 && nodes[0].Cathode == 2);
diff --git a/src/devices/Common/Iot/Device/Common/NumberHelper.cs b/src/devices/Common/Iot/Device/Common/NumberHelper.cs
index 67647fc3b3..f478932875 100644
--- a/src/devices/Common/Iot/Device/Common/NumberHelper.cs
+++ b/src/devices/Common/Iot/Device/Common/NumberHelper.cs
@@ -15,10 +15,7 @@ internal static class NumberHelper
///
/// BCD Code
/// decimal
- public static int Bcd2Dec(byte bcd)
- {
- return ((bcd >> 4) * 10) + (bcd % 16);
- }
+ public static int Bcd2Dec(byte bcd) => ((bcd >> 4) * 10) + (bcd % 16);
///
/// BCD To decimal
@@ -46,7 +43,7 @@ public static byte Dec2Bcd(int dec)
{
if ((dec > 99) || (dec < 0))
{
- throw new ArgumentException($"{nameof(dec)}, encoding value can't be more than 99");
+ throw new ArgumentException(nameof(dec), "Value must be between 0-99.");
}
return (byte)(((dec / 10) << 4) + (dec % 10));
diff --git a/src/devices/Common/Iot/Device/Common/WeatherHelper.cs b/src/devices/Common/Iot/Device/Common/WeatherHelper.cs
index b072a93521..8541b36a05 100644
--- a/src/devices/Common/Iot/Device/Common/WeatherHelper.cs
+++ b/src/devices/Common/Iot/Device/Common/WeatherHelper.cs
@@ -104,10 +104,8 @@ public static Pressure CalculateSaturatedVaporPressureOverIce(Temperature airTem
/// The dry air temperature
/// The relative humidity (RH)
/// The actual vapor pressure
- public static Pressure CalculateActualVaporPressure(Temperature airTemperature, Ratio relativeHumidity)
- {
- return Pressure.FromHectopascals((relativeHumidity.DecimalFractions * CalculateSaturatedVaporPressureOverWater(airTemperature).Hectopascals));
- }
+ public static Pressure CalculateActualVaporPressure(Temperature airTemperature, Ratio relativeHumidity) =>
+ Pressure.FromHectopascals((relativeHumidity.DecimalFractions * CalculateSaturatedVaporPressureOverWater(airTemperature).Hectopascals));
///
/// Calculates the dew point.
@@ -192,10 +190,8 @@ public static Length CalculateAltitude(Pressure pressure, Pressure seaLevelPress
/// The pressure at the point for which altitude is being calculated
/// The dry air temperature at the point for which altitude is being calculated
/// The altitude
- public static Length CalculateAltitude(Pressure pressure, Temperature airTemperature)
- {
- return CalculateAltitude(pressure, MeanSeaLevel, airTemperature);
- }
+ public static Length CalculateAltitude(Pressure pressure, Temperature airTemperature) =>
+ CalculateAltitude(pressure, MeanSeaLevel, airTemperature);
///
/// Calculates the altitude in meters from the given pressure and sea-level pressure. Assumes temperature of 15C.
@@ -203,20 +199,16 @@ public static Length CalculateAltitude(Pressure pressure, Temperature airTempera
/// The pressure at the point for which altitude is being calculated
/// The sea-level pressure
/// The altitude
- public static Length CalculateAltitude(Pressure pressure, Pressure seaLevelPressure)
- {
- return CalculateAltitude(pressure, seaLevelPressure, Temperature.FromDegreesCelsius(15));
- }
+ public static Length CalculateAltitude(Pressure pressure, Pressure seaLevelPressure) =>
+ CalculateAltitude(pressure, seaLevelPressure, Temperature.FromDegreesCelsius(15));
///
/// Calculates the altitude in meters from the given pressure. Assumes mean sea-level pressure and temperature of 15C.
///
/// The pressure at the point for which altitude is being calculated
/// The altitude
- public static Length CalculateAltitude(Pressure pressure)
- {
- return CalculateAltitude(pressure, MeanSeaLevel, Temperature.FromDegreesCelsius(15));
- }
+ public static Length CalculateAltitude(Pressure pressure) =>
+ CalculateAltitude(pressure, MeanSeaLevel, Temperature.FromDegreesCelsius(15));
///
/// Calculates the approximate sea-level pressure from given absolute pressure, altitude and air temperature.
@@ -226,10 +218,8 @@ public static Length CalculateAltitude(Pressure pressure)
/// The air temperature
/// The estimated absolute sea-level pressure
/// solved for sea level pressure
- public static Pressure CalculateSeaLevelPressure(Pressure pressure, Length altitude, Temperature airTemperature)
- {
- return Pressure.FromPascals(Math.Pow((((0.0065 * altitude.Meters) / airTemperature.Kelvins) + 1), 5.255) * pressure.Pascals);
- }
+ public static Pressure CalculateSeaLevelPressure(Pressure pressure, Length altitude, Temperature airTemperature) =>
+ Pressure.FromPascals(Math.Pow((((0.0065 * altitude.Meters) / airTemperature.Kelvins) + 1), 5.255) * pressure.Pascals);
///
/// Calculates the approximate absolute pressure from given sea-level pressure, altitude and air temperature.
@@ -238,10 +228,8 @@ public static Pressure CalculateSeaLevelPressure(Pressure pressure, Length altit
/// The altitude in meters at the point for which pressure is being calculated
/// The air temperature at the point for which pressure is being calculated
/// The estimated absolute pressure at the given altitude
- public static Pressure CalculatePressure(Pressure seaLevelPressure, Length altitude, Temperature airTemperature)
- {
- return Pressure.FromPascals(seaLevelPressure.Pascals / Math.Pow((((0.0065 * altitude.Meters) / airTemperature.Kelvins) + 1), 5.255));
- }
+ public static Pressure CalculatePressure(Pressure seaLevelPressure, Length altitude, Temperature airTemperature) =>
+ Pressure.FromPascals(seaLevelPressure.Pascals / Math.Pow((((0.0065 * altitude.Meters) / airTemperature.Kelvins) + 1), 5.255));
///
/// Calculates the temperature gradient for the given pressure difference
@@ -251,10 +239,8 @@ public static Pressure CalculatePressure(Pressure seaLevelPressure, Length altit
/// The altitude in meters at the point for which temperature is being calculated
/// The standard temperature at the given altitude, when the given pressure difference is known
/// solved for temperature
- public static Temperature CalculateTemperature(Pressure pressure, Pressure seaLevelPressure, Length altitude)
- {
- return Temperature.FromKelvins((0.0065 * altitude.Meters) / (Math.Pow(seaLevelPressure.Pascals / pressure.Pascals, 1 / 5.255) - 1));
- }
+ public static Temperature CalculateTemperature(Pressure pressure, Pressure seaLevelPressure, Length altitude) =>
+ Temperature.FromKelvins((0.0065 * altitude.Meters) / (Math.Pow(seaLevelPressure.Pascals / pressure.Pascals, 1 / 5.255) - 1));
///
/// Calculates the barometric pressure from a raw reading, using the reduction formula from the german met service.
diff --git a/src/devices/Common/Iot/Device/Graphics/BdfFont.cs b/src/devices/Common/Iot/Device/Graphics/BdfFont.cs
index 7176085398..705670e81b 100644
--- a/src/devices/Common/Iot/Device/Graphics/BdfFont.cs
+++ b/src/devices/Common/Iot/Device/Graphics/BdfFont.cs
@@ -69,12 +69,6 @@ public class BdfFont
private static readonly string s_endChar = "ENDCHAR";
private static readonly string s_bitmap = "BITMAP";
-/*
- private BdfFont()
- {
- }
-*/
-
///
/// Loads BdfFont from a specified path
///
@@ -203,7 +197,6 @@ public bool GetCharData(int charOrdinal, ref Span data, bool useDefaultChar
private void ReadGlyphsData(StreamReader sr)
{
- GlyphMapper = new Dictionary();
if (BytesPerGlyph <= 2)
{
GlyphUshortData = new ushort[CharsCount * Height];
@@ -213,6 +206,7 @@ private void ReadGlyphsData(StreamReader sr)
throw new NotSupportedException("Fonts with width more than 16 pixels is not supported.");
}
+ GlyphMapper = new Dictionary();
int index = 0;
for (int i = 0; i < CharsCount; i++)
{
diff --git a/src/devices/Common/tests/WeatherTests.cs b/src/devices/Common/tests/WeatherTests.cs
index 2bb90ac582..d36e28b7ce 100644
--- a/src/devices/Common/tests/WeatherTests.cs
+++ b/src/devices/Common/tests/WeatherTests.cs
@@ -20,7 +20,7 @@ public class WeatherTests
[InlineData(28, 29.5, 12)]
public void HeatIndexIsCalculatedCorrectly(double expected, double celsius, double relativeHumidity)
{
- var heatIndex = WeatherHelper.CalculateHeatIndex(Temperature.FromDegreesCelsius(celsius), Ratio.FromPercent(relativeHumidity));
+ Temperature heatIndex = WeatherHelper.CalculateHeatIndex(Temperature.FromDegreesCelsius(celsius), Ratio.FromPercent(relativeHumidity));
Assert.Equal(expected, Math.Round(heatIndex.DegreesCelsius));
}
@@ -33,7 +33,7 @@ public void HeatIndexIsCalculatedCorrectly(double expected, double celsius, doub
[InlineData(611.213, 0)]
public void SaturatedVaporPressureOverWater(double expected, double celsius)
{
- var saturatedVaporPressure = WeatherHelper.CalculateSaturatedVaporPressureOverWater(Temperature.FromDegreesCelsius(celsius));
+ Pressure saturatedVaporPressure = WeatherHelper.CalculateSaturatedVaporPressureOverWater(Temperature.FromDegreesCelsius(celsius));
Assert.Equal(expected, saturatedVaporPressure.Pascals, 1);
}
@@ -45,7 +45,7 @@ public void SaturatedVaporPressureOverWater(double expected, double celsius)
[InlineData(22.273, -35)]
public void SaturatedVaporPressureOverIce(double expected, double celsius)
{
- var saturatedVaporPressure = WeatherHelper.CalculateSaturatedVaporPressureOverIce(Temperature.FromDegreesCelsius(celsius));
+ Pressure saturatedVaporPressure = WeatherHelper.CalculateSaturatedVaporPressureOverIce(Temperature.FromDegreesCelsius(celsius));
Assert.Equal(expected, saturatedVaporPressure.Pascals, 1);
}
@@ -55,7 +55,7 @@ public void SaturatedVaporPressureOverIce(double expected, double celsius)
[InlineData(1904, 22, 72)]
public void ActualVaporPressureIsCalculatedCorrectly(double expected, double celsius, double relativeHumidity)
{
- var actualVaporPressure = WeatherHelper.CalculateActualVaporPressure(Temperature.FromDegreesCelsius(celsius), Ratio.FromPercent(relativeHumidity));
+ Pressure actualVaporPressure = WeatherHelper.CalculateActualVaporPressure(Temperature.FromDegreesCelsius(celsius), Ratio.FromPercent(relativeHumidity));
Assert.Equal(expected, Math.Round(actualVaporPressure.Pascals, 0));
}
@@ -66,7 +66,7 @@ public void ActualVaporPressureIsCalculatedCorrectly(double expected, double cel
[InlineData(27.68, 60, 29)]
public void DewPointIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity)
{
- var dewPoint = WeatherHelper.CalculateDewPoint(Temperature.FromDegreesFahrenheit(fahrenheit), Ratio.FromPercent(relativeHumidity));
+ Temperature dewPoint = WeatherHelper.CalculateDewPoint(Temperature.FromDegreesFahrenheit(fahrenheit), Ratio.FromPercent(relativeHumidity));
Assert.Equal(expected, Math.Round(dewPoint.DegreesFahrenheit, 2));
}
@@ -76,7 +76,7 @@ public void DewPointIsCalculatedCorrectly(double expected, double fahrenheit, do
[InlineData(5, 40, 75)]
public void AbsoluteHumidityIsCalculatedCorrectly(double expected, double fahrenheit, double relativeHumidity)
{
- var absoluteHumidity = WeatherHelper.CalculateAbsoluteHumidity(Temperature.FromDegreesFahrenheit(fahrenheit), Ratio.FromPercent(relativeHumidity));
+ Density absoluteHumidity = WeatherHelper.CalculateAbsoluteHumidity(Temperature.FromDegreesFahrenheit(fahrenheit), Ratio.FromPercent(relativeHumidity));
Assert.Equal(expected, absoluteHumidity.GramsPerCubicMeter, 0);
}
@@ -86,7 +86,7 @@ public void AbsoluteHumidityIsCalculatedCorrectly(double expected, double fahren
[InlineData(547.1, 950)]
public void AltitudeIsCalculatedCorrectlyAtMslpAndDefaultTemp(double expected, double hpa)
{
- var altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa));
+ Length altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa));
Assert.Equal(expected, Math.Round(altitude.Meters, 2));
}
@@ -96,7 +96,7 @@ public void AltitudeIsCalculatedCorrectlyAtMslpAndDefaultTemp(double expected, d
[InlineData(547.1, 950, 1013.25)]
public void AltitudeIsCalculatedCorrectlyAtDefaultTemp(double expected, double hpa, double seaLevelHpa)
{
- var altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa), Pressure.FromHectopascals(seaLevelHpa));
+ Length altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa), Pressure.FromHectopascals(seaLevelHpa));
Assert.Equal(expected, Math.Round(altitude.Meters, 2));
}
@@ -106,7 +106,7 @@ public void AltitudeIsCalculatedCorrectlyAtDefaultTemp(double expected, double h
[InlineData(547.1, 950, 1013.25, 15)]
public void AltitudeIsCalculatedCorrectly(double expected, double hpa, double seaLevelHpa, double celsius)
{
- var altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa), Pressure.FromHectopascals(seaLevelHpa), Temperature.FromDegreesCelsius(celsius));
+ Length altitude = WeatherHelper.CalculateAltitude(Pressure.FromHectopascals(hpa), Pressure.FromHectopascals(seaLevelHpa), Temperature.FromDegreesCelsius(celsius));
Assert.Equal(expected, Math.Round(altitude.Meters, 2));
}
@@ -116,7 +116,7 @@ public void AltitudeIsCalculatedCorrectly(double expected, double hpa, double se
[InlineData(1013.23, 950, 546.89, 15)]
public void SeaLevelPressureIsCalculatedCorrectly(double expected, double pressure, double altitude, double celsius)
{
- var seaLevelPressure = WeatherHelper.CalculateSeaLevelPressure(Pressure.FromHectopascals(pressure), Length.FromMeters(altitude), Temperature.FromDegreesCelsius(celsius));
+ Pressure seaLevelPressure = WeatherHelper.CalculateSeaLevelPressure(Pressure.FromHectopascals(pressure), Length.FromMeters(altitude), Temperature.FromDegreesCelsius(celsius));
Assert.Equal(expected, Math.Round(seaLevelPressure.Hectopascals, 2));
}
@@ -126,7 +126,7 @@ public void SeaLevelPressureIsCalculatedCorrectly(double expected, double pressu
[InlineData(950.02, 1013.25, 546.89, 15)]
public void PressureIsCalculatedCorrectly(double expected, double seaLevelPressure, double altitude, double celsius)
{
- var pressure = WeatherHelper.CalculatePressure(Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude), Temperature.FromDegreesCelsius(celsius));
+ Pressure pressure = WeatherHelper.CalculatePressure(Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude), Temperature.FromDegreesCelsius(celsius));
Assert.Equal(expected, Math.Round(pressure.Hectopascals, 2));
}
@@ -136,7 +136,7 @@ public void PressureIsCalculatedCorrectly(double expected, double seaLevelPressu
[InlineData(15, 950, 1013.25, 546.89)]
public void TemperatureIsCalculatedCorrectly(double expected, double pressure, double seaLevelPressure, double altitude)
{
- var temperature = WeatherHelper.CalculateTemperature(Pressure.FromHectopascals(pressure), Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude));
+ Temperature temperature = WeatherHelper.CalculateTemperature(Pressure.FromHectopascals(pressure), Pressure.FromHectopascals(seaLevelPressure), Length.FromMeters(altitude));
Assert.Equal(expected, Math.Round(temperature.DegreesCelsius, 0));
}
@@ -154,7 +154,7 @@ public void TemperatureIsCalculatedCorrectly(double expected, double pressure, d
public void CalculateBarometricPressure(double measuredValue, double temperature, double altitude,
double expected)
{
- var result = WeatherHelper.CalculateBarometricPressure(Pressure.FromHectopascals(measuredValue),
+ Pressure result = WeatherHelper.CalculateBarometricPressure(Pressure.FromHectopascals(measuredValue),
Temperature.FromDegreesCelsius(temperature), Length.FromMeters(altitude));
Assert.Equal(expected, result.Hectopascals, 2);
}
@@ -168,7 +168,7 @@ public void CalculateBarometricPressure(double measuredValue, double temperature
public void CalculateBarometricPressureWithHumidity(double measuredValue, double temperature, double altitude, double relativeHumidity,
double expected)
{
- var result = WeatherHelper.CalculateBarometricPressure(Pressure.FromHectopascals(measuredValue),
+ Pressure result = WeatherHelper.CalculateBarometricPressure(Pressure.FromHectopascals(measuredValue),
Temperature.FromDegreesCelsius(temperature), Length.FromMeters(altitude), Ratio.FromPercent(relativeHumidity));
Assert.Equal(expected, result.Hectopascals, 2);
}
@@ -179,7 +179,7 @@ public void CalculateBarometricPressureWithHumidity(double measuredValue, double
[InlineData(27.8, 38.1, 20.0, 59.317)] // in data from BMP280 (in case), thermometer 1 meter away shows 20.0°, 57%
public void GetRelativeHumidityFromActualAirTemperature(double inTemp, double inHumidity, double outTemp, double outHumidityExpected)
{
- var result = WeatherHelper.GetRelativeHumidityFromActualAirTemperature(
+ Ratio result = WeatherHelper.GetRelativeHumidityFromActualAirTemperature(
Temperature.FromDegreesCelsius(inTemp),
Ratio.FromPercent(inHumidity), Temperature.FromDegreesCelsius(outTemp));
diff --git a/src/devices/DCMotor/DCMotor.cs b/src/devices/DCMotor/DCMotor.cs
index 775c48a90f..a9bd6789b3 100644
--- a/src/devices/DCMotor/DCMotor.cs
+++ b/src/devices/DCMotor/DCMotor.cs
@@ -23,7 +23,7 @@ public abstract class DCMotor : IDisposable
/// True to dispose the Gpio Controller
protected DCMotor(GpioController? controller, bool shouldDispose)
{
- _shouldDispose = shouldDispose;
+ _shouldDispose = shouldDispose || controller is null;
Controller = controller ?? new GpioController();
}
@@ -36,34 +36,17 @@ protected DCMotor(GpioController? controller, bool shouldDispose)
///
/// related with operations on pins
///
- protected GpioController Controller
- {
- get;
- set;
- }
-
- ///
- /// Disposes the class
- ///
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
+ protected GpioController Controller { get; set; }
///
/// Releases the resources used by the instance.
///
- /// true to release both managed and unmanaged resources; false to release only unmanaged resources.
- protected virtual void Dispose(bool disposing)
+ public virtual void Dispose()
{
- if (disposing)
+ if (_shouldDispose)
{
- if (_shouldDispose)
- {
- Controller?.Dispose();
- Controller = null!;
- }
+ Controller?.Dispose();
+ Controller = null!;
}
}
@@ -134,7 +117,7 @@ public static DCMotor Create(int speedControlPin, GpioController? controller = n
///
public static DCMotor Create(PwmChannel speedControlChannel, int directionPin, GpioController? controller = null, bool shouldDispose = true, bool singleBiDirectionPin = false)
{
- if (speedControlChannel == null)
+ if (speedControlChannel is null)
{
throw new ArgumentNullException(nameof(speedControlChannel));
}
@@ -222,7 +205,7 @@ public static DCMotor Create(int speedControlPin, int directionPin, GpioControll
///
public static DCMotor Create(PwmChannel speedControlChannel, int directionPin, int otherDirectionPin, GpioController? controller = null, bool shouldDispose = true)
{
- if (speedControlChannel == null)
+ if (speedControlChannel is null)
{
throw new ArgumentNullException(nameof(speedControlChannel));
}
diff --git a/src/devices/DCMotor/DCMotor2PinNoEnable.cs b/src/devices/DCMotor/DCMotor2PinNoEnable.cs
index 475c068b6c..54dd307fa8 100644
--- a/src/devices/DCMotor/DCMotor2PinNoEnable.cs
+++ b/src/devices/DCMotor/DCMotor2PinNoEnable.cs
@@ -19,7 +19,7 @@ public DCMotor2PinNoEnable(
int pin1,
GpioController? controller,
bool shouldDispose)
- : base(controller ?? ((pin1 == -1) ? null : new GpioController()), controller == null ? true : shouldDispose)
+ : base(controller ?? ((pin1 == -1) ? null : new GpioController()), controller is null ? true : shouldDispose)
{
_pwm = pwmChannel;
@@ -43,10 +43,7 @@ public DCMotor2PinNoEnable(
///
public override double Speed
{
- get
- {
- return _speed;
- }
+ get => _speed;
set
{
double val = Math.Clamp(value, _pin1 != -1 ? -1.0 : 0.0, 1.0);
@@ -79,15 +76,11 @@ public override double Speed
}
}
- protected override void Dispose(bool disposing)
+ public override void Dispose()
{
- if (disposing)
- {
- _pwm?.Dispose();
- _pwm = null!;
- }
-
- base.Dispose(disposing);
+ _pwm?.Dispose();
+ _pwm = null!;
+ base.Dispose();
}
}
}
diff --git a/src/devices/DCMotor/DCMotor2PinWithBiDirectionalPin.cs b/src/devices/DCMotor/DCMotor2PinWithBiDirectionalPin.cs
index 94c4f33e3f..b4b1d712e6 100644
--- a/src/devices/DCMotor/DCMotor2PinWithBiDirectionalPin.cs
+++ b/src/devices/DCMotor/DCMotor2PinWithBiDirectionalPin.cs
@@ -22,7 +22,7 @@ public DCMotor2PinWithBiDirectionalPin(
int dirpin,
GpioController? controller,
bool shouldDispose)
- : base(controller ?? ((dirpin == -1) ? null : new GpioController()), controller == null || shouldDispose)
+ : base(controller ?? ((dirpin == -1) ? null : new GpioController()), controller is null || shouldDispose)
{
_pwm = pwmChannel;
_dirPin = dirpin;
@@ -82,15 +82,11 @@ public override double Speed
}
}
- protected override void Dispose(bool disposing)
+ public override void Dispose()
{
- if (disposing)
- {
- _pwm?.Dispose();
- _pwm = null!;
- }
-
- base.Dispose(disposing);
+ _pwm?.Dispose();
+ _pwm = null!;
+ base.Dispose();
}
}
}
diff --git a/src/devices/DCMotor/DCMotor3Pin.cs b/src/devices/DCMotor/DCMotor3Pin.cs
index 27b2e97531..5db186604e 100644
--- a/src/devices/DCMotor/DCMotor3Pin.cs
+++ b/src/devices/DCMotor/DCMotor3Pin.cs
@@ -21,9 +21,9 @@ public DCMotor3Pin(
int pin1,
GpioController? controller,
bool shouldDispose)
- : base(controller ?? new GpioController(), controller == null ? true : shouldDispose)
+ : base(controller ?? new GpioController(), controller is null ? true : shouldDispose)
{
- if (pwmChannel == null)
+ if (pwmChannel is null)
{
throw new ArgumentNullException(nameof(pwmChannel));
}
@@ -86,16 +86,12 @@ public override double Speed
}
}
- protected override void Dispose(bool disposing)
+ public override void Dispose()
{
- if (disposing)
- {
- _speed = 0.0;
- _pwm?.Dispose();
- _pwm = null!;
- }
-
- base.Dispose(disposing);
+ _speed = 0.0;
+ _pwm?.Dispose();
+ _pwm = null!;
+ base.Dispose();
}
}
}
diff --git a/src/devices/Dhtxx/Devices/Dht11.cs b/src/devices/Dhtxx/Devices/Dht11.cs
index 66e4eb2fa1..346b570817 100644
--- a/src/devices/Dhtxx/Devices/Dht11.cs
+++ b/src/devices/Dhtxx/Devices/Dht11.cs
@@ -23,10 +23,7 @@ public Dht11(int pin, PinNumberingScheme pinNumberingScheme = PinNumberingScheme
{
}
- internal override Ratio GetHumidity(byte[] readBuff)
- {
- return Ratio.FromPercent(readBuff[0] + readBuff[1] * 0.1);
- }
+ internal override Ratio GetHumidity(byte[] readBuff) => Ratio.FromPercent(readBuff[0] + readBuff[1] * 0.1);
internal override Temperature GetTemperature(byte[] readBuff)
{
diff --git a/src/devices/Dhtxx/Devices/Dht12.cs b/src/devices/Dhtxx/Devices/Dht12.cs
index f045032bee..c51cf2c073 100644
--- a/src/devices/Dhtxx/Devices/Dht12.cs
+++ b/src/devices/Dhtxx/Devices/Dht12.cs
@@ -38,10 +38,7 @@ public Dht12(I2cDevice i2cDevice)
{
}
- internal override Ratio GetHumidity(byte[] readBuff)
- {
- return Ratio.FromPercent(readBuff[0] + readBuff[1] * 0.1);
- }
+ internal override Ratio GetHumidity(byte[] readBuff) => Ratio.FromPercent(readBuff[0] + readBuff[1] * 0.1);
internal override Temperature GetTemperature(byte[] readBuff)
{
diff --git a/src/devices/Dhtxx/Devices/Dht21.cs b/src/devices/Dhtxx/Devices/Dht21.cs
index ae78fa14d6..bfaaacc80f 100644
--- a/src/devices/Dhtxx/Devices/Dht21.cs
+++ b/src/devices/Dhtxx/Devices/Dht21.cs
@@ -23,10 +23,7 @@ public Dht21(int pin, PinNumberingScheme pinNumberingScheme = PinNumberingScheme
{
}
- internal override Ratio GetHumidity(byte[] readBuff)
- {
- return Ratio.FromPercent((readBuff[0] << 8 | readBuff[1]) * 0.1);
- }
+ internal override Ratio GetHumidity(byte[] readBuff) => Ratio.FromPercent((readBuff[0] << 8 | readBuff[1]) * 0.1);
internal override Temperature GetTemperature(byte[] readBuff)
{
diff --git a/src/devices/Dhtxx/Devices/Dht22.cs b/src/devices/Dhtxx/Devices/Dht22.cs
index ceb3d5fca4..0d15ba6fba 100644
--- a/src/devices/Dhtxx/Devices/Dht22.cs
+++ b/src/devices/Dhtxx/Devices/Dht22.cs
@@ -23,10 +23,7 @@ public Dht22(int pin, PinNumberingScheme pinNumberingScheme = PinNumberingScheme
{
}
- internal override Ratio GetHumidity(byte[] readBuff)
- {
- return Ratio.FromPercent((readBuff[0] << 8 | readBuff[1]) * 0.1);
- }
+ internal override Ratio GetHumidity(byte[] readBuff) => Ratio.FromPercent((readBuff[0] << 8 | readBuff[1]) * 0.1);
internal override Temperature GetTemperature(byte[] readBuff)
{
diff --git a/src/devices/Dhtxx/DhtBase.cs b/src/devices/Dhtxx/DhtBase.cs
index bad7ad0739..7d7357bb0b 100644
--- a/src/devices/Dhtxx/DhtBase.cs
+++ b/src/devices/Dhtxx/DhtBase.cs
@@ -93,7 +93,7 @@ public virtual Ratio Humidity
public DhtBase(int pin, PinNumberingScheme pinNumberingScheme = PinNumberingScheme.Logical, GpioController? gpioController = null, bool shouldDispose = true)
{
_protocol = CommunicationProtocol.OneWire;
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
_controller = gpioController ?? new GpioController(pinNumberingScheme);
_pin = pin;
@@ -291,15 +291,9 @@ public void Dispose()
_controller?.Dispose();
_controller = null;
}
- else
+ else if (_controller?.IsPinOpen(_pin) ?? false)
{
- if (_controller != null)
- {
- if (_controller.IsPinOpen(_pin))
- {
- _controller.ClosePin(_pin);
- }
- }
+ _controller.ClosePin(_pin);
}
_i2cDevice?.Dispose();
diff --git a/src/devices/Dhtxx/samples/Program.cs b/src/devices/Dhtxx/samples/Program.cs
index bfdca57441..42434196c7 100644
--- a/src/devices/Dhtxx/samples/Program.cs
+++ b/src/devices/Dhtxx/samples/Program.cs
@@ -23,7 +23,7 @@
I2cConnectionSettings settings = new (1, Dht10.DefaultI2cAddress);
I2cDevice device = I2cDevice.Create(settings);
- using Dht10 dht = new Dht10(device);
+ using Dht10 dht = new (device);
Dht(dht);
return;
}
@@ -47,7 +47,7 @@
{
case '2':
Console.WriteLine($"Reading temperature and humidity on DHT11, pin {pin}");
- using (var dht11 = new Dht11(pin))
+ using (Dht11 dht11 = new (pin))
{
Dht(dht11);
}
@@ -55,7 +55,7 @@
break;
case '3':
Console.WriteLine($"Reading temperature and humidity on DHT12, pin {pin}");
- using (var dht12 = new Dht12(pin))
+ using (Dht12 dht12 = new (pin))
{
Dht(dht12);
}
@@ -63,7 +63,7 @@
break;
case '4':
Console.WriteLine($"Reading temperature and humidity on DHT21, pin {pin}");
- using (var dht21 = new Dht21(pin))
+ using (Dht21 dht21 = new (pin))
{
Dht(dht21);
}
@@ -71,7 +71,7 @@
break;
case '5':
Console.WriteLine($"Reading temperature and humidity on DHT22, pin {pin}");
- using (var dht22 = new Dht22(pin))
+ using (Dht22 dht22 = new (pin))
{
Dht(dht22);
}
diff --git a/src/devices/Display/samples/Program.cs b/src/devices/Display/samples/Program.cs
index 39da559470..27875cb6ed 100644
--- a/src/devices/Display/samples/Program.cs
+++ b/src/devices/Display/samples/Program.cs
@@ -9,7 +9,7 @@
const string SupportedCharacters = "0123456789aAbBcCdDeEfFgGhHiIjJlLnNoOpPrRsStuUyYzZ-=_|°[] ";
// Initialize display (busId = 1 for Raspberry Pi 2 & 3)
-using var display = new Large4Digit7SegmentDisplay(I2cDevice.Create(new I2cConnectionSettings(busId: 1, Ht16k33.DefaultI2cAddress)))
+using Large4Digit7SegmentDisplay display = new (I2cDevice.Create(new I2cConnectionSettings(busId: 1, Ht16k33.DefaultI2cAddress)))
{
// Set max brightness
Brightness = Ht16k33.MaxBrightness
diff --git a/src/devices/ExplorerHat/ExplorerHat.cs b/src/devices/ExplorerHat/ExplorerHat.cs
index 9634b7c2cb..dad6c2a77b 100644
--- a/src/devices/ExplorerHat/ExplorerHat.cs
+++ b/src/devices/ExplorerHat/ExplorerHat.cs
@@ -29,7 +29,7 @@ public class ExplorerHat : IDisposable
///
public ExplorerHat(GpioController? controller = null, bool shouldDispose = true)
{
- _shouldDispose = controller == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || controller is null;
_controller = controller ?? new GpioController();
Motors = new Motors(_controller);
diff --git a/src/devices/ExplorerHat/Led.cs b/src/devices/ExplorerHat/Led.cs
index 04302656cb..27859760f6 100644
--- a/src/devices/ExplorerHat/Led.cs
+++ b/src/devices/ExplorerHat/Led.cs
@@ -30,10 +30,10 @@ public class Led : IDisposable
/// Underlying rpi GPIO pin number
/// used by to manage GPIO resources
/// True to dispose the Gpio Controller
- internal Led(int pin, GpioController controller, bool shouldDispose = true)
+ internal Led(int pin, GpioController? controller = null, bool shouldDispose = true)
{
- _controller = controller;
- _shouldDispose = shouldDispose;
+ _controller = controller ?? new ();
+ _shouldDispose = shouldDispose || controller is null;
Pin = pin;
IsOn = false;
diff --git a/src/devices/ExplorerHat/Lights.cs b/src/devices/ExplorerHat/Lights.cs
index 84134ff358..935ee96cd2 100644
--- a/src/devices/ExplorerHat/Lights.cs
+++ b/src/devices/ExplorerHat/Lights.cs
@@ -25,59 +25,59 @@ public class Lights : IDisposable, IEnumerable
///
/// Blue led (#1)
///
- public Led One { get => LedArray[0]; }
+ public Led One => LedArray[0];
///
/// Yellow led (#2)
///
- public Led Two { get => LedArray[1]; }
+ public Led Two => LedArray[1];
///
/// Red led (#3)
///
- public Led Three { get => LedArray[2]; }
+ public Led Three => LedArray[2];
///
/// Green led (#4)
///
- public Led Four { get => LedArray[3]; }
+ public Led Four => LedArray[3];
///
/// Blue led (#1)
///
- public Led Blue { get => LedArray[0]; }
+ public Led Blue => LedArray[0];
///
/// Yellow led (#2)
///
- public Led Yellow { get => LedArray[1]; }
+ public Led Yellow => LedArray[1];
///
/// Red led (#3)
///
- public Led Red { get => LedArray[2]; }
+ public Led Red => LedArray[2];
///
/// Green led (#4)
///
- public Led Green { get => LedArray[3]; }
+ public Led Green => LedArray[3];
///
/// Initializes a instance
///
/// used by to manage GPIO resources
/// True to dispose the Gpio Controller
- internal Lights(GpioController controller, bool shouldDispose = true)
+ internal Lights(GpioController? controller = null, bool shouldDispose = true)
{
- _controller = controller;
- _shouldDispose = shouldDispose;
+ _controller = controller ?? new ();
+ _shouldDispose = shouldDispose || controller is null;
LedArray = new List()
{
- new Led(LED1_PIN, _controller),
- new Led(LED2_PIN, _controller),
- new Led(LED3_PIN, _controller),
- new Led(LED4_PIN, _controller)
+ new (LED1_PIN, _controller),
+ new (LED2_PIN, _controller),
+ new (LED3_PIN, _controller),
+ new (LED4_PIN, _controller)
};
}
@@ -122,18 +122,12 @@ public void Dispose()
/// Returns an enumerator that iterates through the collection of leds
///
/// An enumerator that can be used to iterate through the collection of leds
- public IEnumerator GetEnumerator()
- {
- return ((IEnumerable)LedArray).GetEnumerator();
- }
+ public IEnumerator GetEnumerator() => LedArray.GetEnumerator();
///
/// Returns an enumerator that iterates through the collection of leds
///
/// An enumerator that can be used to iterate through the collection of leds
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ((IEnumerable)LedArray).GetEnumerator();
- }
+ IEnumerator IEnumerable.GetEnumerator() => LedArray.GetEnumerator();
}
}
diff --git a/src/devices/ExplorerHat/Motors.cs b/src/devices/ExplorerHat/Motors.cs
index 0ddc632ded..256ced6cf9 100644
--- a/src/devices/ExplorerHat/Motors.cs
+++ b/src/devices/ExplorerHat/Motors.cs
@@ -67,10 +67,10 @@ public void Stop()
///
/// used by to manage GPIO resources
/// True to dispose the Gpio Controller
- internal Motors(GpioController controller, bool shouldDispose = true)
+ internal Motors(GpioController? controller = null, bool shouldDispose = true)
{
- _controller = controller;
- _shouldDispose = shouldDispose;
+ _controller = controller ?? new ();
+ _shouldDispose = shouldDispose || controller is null;
_motorArray = new List()
{
@@ -86,8 +86,8 @@ internal Motors(GpioController controller, bool shouldDispose = true)
///
public void Dispose()
{
- _motorArray[0].Dispose();
- _motorArray[1].Dispose();
+ _motorArray[0]?.Dispose();
+ _motorArray[1]?.Dispose();
if (_shouldDispose)
{
_controller?.Dispose();
diff --git a/src/devices/ExplorerHat/samples/Program.cs b/src/devices/ExplorerHat/samples/Program.cs
index 45fea97cd0..7fc4284e8a 100644
--- a/src/devices/ExplorerHat/samples/Program.cs
+++ b/src/devices/ExplorerHat/samples/Program.cs
@@ -5,7 +5,7 @@
using System.Threading;
using Iot.Device.ExplorerHat;
-using var hat = new ExplorerHat();
+using ExplorerHat hat = new ();
// All lights on
hat.Lights.On();
Thread.Sleep(1000);
diff --git a/src/devices/Ft4222/Ft4222Gpio.cs b/src/devices/Ft4222/Ft4222Gpio.cs
index 281d5e4835..f9836a5a4b 100644
--- a/src/devices/Ft4222/Ft4222Gpio.cs
+++ b/src/devices/Ft4222/Ft4222Gpio.cs
@@ -125,7 +125,7 @@ protected override void AddCallbackForPinValueChangedEvent(int pinNumber, PinEve
{
if (eventTypes == PinEventTypes.None)
{
- throw new ArgumentException($"{PinEventTypes.None} is an invalid value.", nameof(eventTypes));
+ throw new ArgumentException(nameof(eventTypes), $"{nameof(PinEventTypes.None)} is an invalid value.");
}
if (eventTypes.HasFlag(PinEventTypes.Falling))
@@ -148,12 +148,12 @@ protected override void RemoveCallbackForPinValueChangedEvent(int pinNumber, Pin
{
_pinFallingHandlers[pinNumber] -= callback;
_pinRisingHandlers[pinNumber] -= callback;
- if (_pinFallingHandlers == null)
+ if (_pinFallingHandlers is null)
{
_gpioTriggers[pinNumber] &= ~GpioTrigger.Falling;
}
- if (_pinRisingHandlers == null)
+ if (_pinRisingHandlers is null)
{
_gpioTriggers[pinNumber] &= ~GpioTrigger.Rising;
}
diff --git a/src/devices/Ft4222/Ft4222Spi.cs b/src/devices/Ft4222/Ft4222Spi.cs
index 63d1d904bc..6e7e19200e 100644
--- a/src/devices/Ft4222/Ft4222Spi.cs
+++ b/src/devices/Ft4222/Ft4222Spi.cs
@@ -86,149 +86,41 @@ public Ft4222Spi(SpiConnectionSettings settings)
}
}
- private (FtClockRate clk, SpiClock spiClk) CalculateBestClockRate()
+ // Maximum is the System Clock / 1 = 80 MHz
+ // Minimum is the System Clock / 512 = 24 / 256 = 93.75 KHz
+ // Always take the below frequency to avoid over clocking
+ private (FtClockRate clk, SpiClock spiClk) CalculateBestClockRate() => _settings.ClockFrequency switch
{
- // Maximum is the System Clock / 1 = 80 MHz
- // Minimum is the System Clock / 512 = 24 / 256 = 93.75 KHz
- // Always take the below frequency to avoid over clocking
- if (_settings.ClockFrequency < 187500)
- {
- return (FtClockRate.Clock24MHz, SpiClock.DivideBy256);
- }
-
- if (_settings.ClockFrequency < 234375)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy256);
- }
-
- if (_settings.ClockFrequency < 312500)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy256);
- }
-
- if (_settings.ClockFrequency < 375000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy256);
- }
-
- if (_settings.ClockFrequency < 468750)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy128);
- }
-
- if (_settings.ClockFrequency < 625000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy128);
- }
-
- if (_settings.ClockFrequency < 750000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy128);
- }
-
- if (_settings.ClockFrequency < 937500)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy64);
- }
-
- if (_settings.ClockFrequency < 1250000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy64);
- }
-
- if (_settings.ClockFrequency < 1500000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy64);
- }
-
- if (_settings.ClockFrequency < 1875000)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy32);
- }
-
- if (_settings.ClockFrequency < 2500000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy32);
- }
-
- if (_settings.ClockFrequency < 3000000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy32);
- }
-
- if (_settings.ClockFrequency < 3750000)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy16);
- }
-
- if (_settings.ClockFrequency < 5000000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy16);
- }
-
- if (_settings.ClockFrequency < 6000000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy16);
- }
-
- if (_settings.ClockFrequency < 7500000)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy8);
- }
-
- if (_settings.ClockFrequency < 10000000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy8);
- }
-
- if (_settings.ClockFrequency < 12000000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy8);
- }
-
- if (_settings.ClockFrequency < 15000000)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy4);
- }
-
- if (_settings.ClockFrequency < 20000000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy4);
- }
-
- if (_settings.ClockFrequency < 24000000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy4);
- }
-
- if (_settings.ClockFrequency < 30000000)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy2);
- }
-
- if (_settings.ClockFrequency < 40000000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy2);
- }
-
- if (_settings.ClockFrequency < 48000000)
- {
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy2);
- }
-
- if (_settings.ClockFrequency < 60000000)
- {
- return (FtClockRate.Clock48MHz, SpiClock.DivideBy1);
- }
-
- if (_settings.ClockFrequency < 80000000)
- {
- return (FtClockRate.Clock60MHz, SpiClock.DivideBy1);
- }
-
+ < 187500 => (FtClockRate.Clock24MHz, SpiClock.DivideBy256),
+ < 234375 => (FtClockRate.Clock48MHz, SpiClock.DivideBy256),
+ < 312500 => (FtClockRate.Clock60MHz, SpiClock.DivideBy256),
+ < 375000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy256),
+ < 468750 => (FtClockRate.Clock48MHz, SpiClock.DivideBy128),
+ < 625000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy128),
+ < 750000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy128),
+ < 937500 => (FtClockRate.Clock48MHz, SpiClock.DivideBy64),
+ < 1250000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy64),
+ < 1500000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy64),
+ < 1875000 => (FtClockRate.Clock48MHz, SpiClock.DivideBy32),
+ < 2500000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy32),
+ < 3000000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy32),
+ < 3750000 => (FtClockRate.Clock48MHz, SpiClock.DivideBy16),
+ < 5000000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy16),
+ < 6000000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy16),
+ < 7500000 => (FtClockRate.Clock48MHz, SpiClock.DivideBy8),
+ < 10000000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy8),
+ < 12000000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy8),
+ < 15000000 => (FtClockRate.Clock48MHz, SpiClock.DivideBy4),
+ < 20000000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy4),
+ < 24000000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy4),
+ < 30000000 => (FtClockRate.Clock48MHz, SpiClock.DivideBy2),
+ < 40000000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy2),
+ < 48000000 => (FtClockRate.Clock80MHz, SpiClock.DivideBy2),
+ < 60000000 => (FtClockRate.Clock48MHz, SpiClock.DivideBy1),
+ < 80000000 => (FtClockRate.Clock60MHz, SpiClock.DivideBy1),
// Anything else will be 80 MHz
- return (FtClockRate.Clock80MHz, SpiClock.DivideBy1);
- }
+ _ => (FtClockRate.Clock80MHz, SpiClock.DivideBy1),
+ };
///
public override void Read(Span buffer)
diff --git a/src/devices/Ft4222/FtFunction.cs b/src/devices/Ft4222/FtFunction.cs
index 79ebe4898f..ce42e4eb08 100644
--- a/src/devices/Ft4222/FtFunction.cs
+++ b/src/devices/Ft4222/FtFunction.cs
@@ -431,7 +431,7 @@ public static FtStatus FT_Close(SafeFtHandle ftHandle)
///
/// The handle of the open device
/// The intensity of the clock pin
- /// The intensity of the MOSI and MISO pins
+ /// The intensity of the SDO and SDI pins
/// The intensity of the chip select pin
/// The status
[DllImport("libft4222", CallingConvention = CallingConvention.Cdecl)]
diff --git a/src/devices/Ft4222/samples/Program.cs b/src/devices/Ft4222/samples/Program.cs
index 91b9f4ca2c..55d5075d92 100644
--- a/src/devices/Ft4222/samples/Program.cs
+++ b/src/devices/Ft4222/samples/Program.cs
@@ -6,6 +6,7 @@
using System.Device.I2c;
using System.Device.Spi;
using System.Threading;
+using System.Collections.Generic;
using Iot.Device.Bno055;
using Iot.Device.Ft4222;
@@ -18,9 +19,9 @@
var key = Console.ReadKey();
Console.WriteLine();
-var devices = FtCommon.GetDevices();
+List devices = FtCommon.GetDevices();
Console.WriteLine($"{devices.Count} FT4222 elements found");
-foreach (var device in devices)
+foreach (DeviceInformation device in devices)
{
Console.WriteLine($"Description: {device.Description}");
Console.WriteLine($"Flags: {device.Flags}");
@@ -56,9 +57,9 @@
void TestI2c()
{
- using var ftI2c = new Ft4222I2c(new I2cConnectionSettings(0, Bno055Sensor.DefaultI2cAddress));
+ using Ft4222I2c ftI2c = new (new I2cConnectionSettings(0, Bno055Sensor.DefaultI2cAddress));
- var bno055Sensor = new Bno055Sensor(ftI2c);
+ Bno055Sensor bno055Sensor = new (ftI2c);
Console.WriteLine($"Id: {bno055Sensor.Info.ChipId}, AccId: {bno055Sensor.Info.AcceleratorId}, GyroId: {bno055Sensor.Info.GyroscopeId}, MagId: {bno055Sensor.Info.MagnetometerId}");
Console.WriteLine($"Firmware version: {bno055Sensor.Info.FirmwareVersion}, Bootloader: {bno055Sensor.Info.BootloaderVersion}");
@@ -68,7 +69,7 @@ void TestI2c()
void TestSpi()
{
- using var ftSpi = new Ft4222Spi(new SpiConnectionSettings(0, 1) { ClockFrequency = 1_000_000, Mode = SpiMode.Mode0 });
+ using Ft4222Spi ftSpi = new (new SpiConnectionSettings(0, 1) { ClockFrequency = 1_000_000, Mode = SpiMode.Mode0 });
while (!Console.KeyAvailable)
{
@@ -82,7 +83,7 @@ void TestSpi()
void TestGpio()
{
const int Gpio2 = 2;
- using var gpioController = new GpioController(PinNumberingScheme.Board, new Ft4222Gpio());
+ using GpioController gpioController = new (PinNumberingScheme.Board, new Ft4222Gpio());
// Opening GPIO2
gpioController.OpenPin(Gpio2);
@@ -111,7 +112,7 @@ void TestGpio()
void TestEvents()
{
const int Gpio2 = 2;
- using var gpioController = new GpioController(PinNumberingScheme.Board, new Ft4222Gpio());
+ using GpioController gpioController = new (PinNumberingScheme.Board, new Ft4222Gpio());
// Opening GPIO2
gpioController.OpenPin(Gpio2);
@@ -124,7 +125,7 @@ void TestEvents()
Console.WriteLine("Event setup, press a key to remove the failing event");
while (!Console.KeyAvailable)
{
- var res = gpioController.WaitForEvent(Gpio2, PinEventTypes.Falling, new TimeSpan(0, 0, 0, 0, 50));
+ WaitForEventResult res = gpioController.WaitForEvent(Gpio2, PinEventTypes.Falling, new TimeSpan(0, 0, 0, 0, 50));
if ((!res.TimedOut) && (res.EventTypes != PinEventTypes.None))
{
MyCallbackFailing(gpioController, new PinValueChangedEventArgs(res.EventTypes, Gpio2));
@@ -144,7 +145,7 @@ void TestEvents()
Console.WriteLine("Event removed, press a key to remove all events and quit");
while (!Console.KeyAvailable)
{
- var res = gpioController.WaitForEvent(Gpio2, PinEventTypes.Rising, new TimeSpan(0, 0, 0, 0, 50));
+ WaitForEventResult res = gpioController.WaitForEvent(Gpio2, PinEventTypes.Rising, new TimeSpan(0, 0, 0, 0, 50));
if ((!res.TimedOut) && (res.EventTypes != PinEventTypes.None))
{
MyCallback(gpioController, new PinValueChangedEventArgs(res.EventTypes, Gpio2));
@@ -154,12 +155,8 @@ void TestEvents()
gpioController.UnregisterCallbackForPinValueChangedEvent(Gpio2, MyCallback);
}
-void MyCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
-{
+void MyCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs) =>
Console.WriteLine($"Event on GPIO {pinValueChangedEventArgs.PinNumber}, event type: {pinValueChangedEventArgs.ChangeType}");
-}
-void MyCallbackFailing(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
-{
- Console.WriteLine($"Event on GPIO {pinValueChangedEventArgs.PinNumber}, event type: {pinValueChangedEventArgs.ChangeType}");
-}
+void MyCallbackFailing(object sender, PinValueChangedEventArgs pinValueChangedEventArgs) =>
+ Console.WriteLine($"Event on GPIO {pinValueChangedEventArgs.PinNumber}, event type: {pinValueChangedEventArgs.ChangeType}");
\ No newline at end of file
diff --git a/src/devices/GoPiGo3/GoPiGo3.cs b/src/devices/GoPiGo3/GoPiGo3.cs
index 5d9346a9fe..72bbface0f 100644
--- a/src/devices/GoPiGo3/GoPiGo3.cs
+++ b/src/devices/GoPiGo3/GoPiGo3.cs
@@ -29,7 +29,7 @@ public class GoPiGo : IDisposable
// This is used by GoPiGo3 when returning I2C data returned are correct
private const byte I2cCorrectData = 0;
- private bool _autoDispose;
+ private bool _shouldDispose;
private SpiDevice _spiDevice;
#region Properties
@@ -59,8 +59,8 @@ public class GoPiGo : IDisposable
///
public GroveSensor[] GroveSensor = new GroveSensor[2]
{
- new GroveSensor(GrovePort.Grove1),
- new GroveSensor(GrovePort.Grove2)
+ new (GrovePort.Grove1),
+ new (GrovePort.Grove2)
};
///
@@ -83,12 +83,12 @@ public class GoPiGo : IDisposable
/// The SpiDevice
/// The SPI address, by default 8
/// Try to autodetect the board
- /// True to dispose the SpiDevice when disposing the class
- public GoPiGo(SpiDevice spiDevice, byte spiAddress = 8, bool autoDetect = true, bool autoDispose = true)
+ /// True to dispose the SpiDevice when disposing the class
+ public GoPiGo(SpiDevice spiDevice, byte spiAddress = 8, bool autoDetect = true, bool shouldDispose = true)
{
- _spiDevice = spiDevice ?? throw new ArgumentException("SpiDevice can't be null");
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
SpiAddress = spiAddress;
- _autoDispose = autoDispose;
+ _shouldDispose = shouldDispose;
InitializeGoPiGo(autoDetect);
}
@@ -136,7 +136,7 @@ public void Dispose()
SetServo(ServoPort.Both, 0);
// Turn off the LEDs
SetLed((byte)GoPiGo3Led.LedEyeLeft + (byte)GoPiGo3Led.LedEyeRight + (byte)GoPiGo3Led.LedBlinkerLeft + (byte)GoPiGo3Led.LedBlinkerRight, Color.Black);
- if (_autoDispose)
+ if (_shouldDispose)
{
_spiDevice.Dispose();
}
@@ -260,7 +260,6 @@ public void SpiWrite32(SpiMessageType MessageType, int Value)
/// Returns the GoPiGo3 manufacturer name string
public string GetManufacturer()
{
- string retVal = string.Empty;
byte[] outArray =
{
SpiAddress, (byte)SpiMessageType.GetManufacturer, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
@@ -280,7 +279,6 @@ public string GetManufacturer()
/// Returns the GoPiGo3 board name string
public string GetBoard()
{
- string retVal = string.Empty;
byte[] outArray =
{
SpiAddress, (byte)SpiMessageType.GetName, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
@@ -301,7 +299,6 @@ public string GetBoard()
/// Returns the hardware version as a string
public Version GetHardwareVersion()
{
- string retVal = string.Empty;
int version = SpiRead32(SpiMessageType.GetHardwareVersion);
return new Version(version / 1000000, (version / 1000) % 1000, version % 1000);
}
@@ -310,10 +307,7 @@ public Version GetHardwareVersion()
/// Read the 128 bit GoPiGo3 hardware serial number
///
/// Returns the serial number as 32 char HEX formatted string
- public string GetIdHex()
- {
- return string.Join(string.Empty, GetId().Select((b) => b.ToString("X2")));
- }
+ public string GetIdHex() => string.Join(string.Empty, GetId().Select((b) => b.ToString("X2")));
///
/// Read the 128 bit GoPiGo3 hardware serial number
@@ -321,7 +315,6 @@ public string GetIdHex()
/// Returns the serial number as a byte array
public byte[] GetId()
{
- string retVal = string.Empty;
byte[] outArray =
{
SpiAddress, (byte)SpiMessageType.GetId, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
@@ -342,7 +335,6 @@ public byte[] GetId()
/// Returns the firmware version
public Version GetFirmwareVersion()
{
- string retVal = string.Empty;
int version = SpiRead32(SpiMessageType.GetFirmwareVersion);
return new Version(version / 1000000, (version / 1000) % 1000, version % 1000);
}
@@ -478,7 +470,7 @@ public void SetMotorLimits(MotorPort port, byte powerPercent = 0, int dps = 0)
public MotorStatus GetMotorStatus(MotorPort port)
{
MotorStatus motorStatus = new MotorStatus();
- SpiMessageType message_type = (port == MotorPort.MotorRight) ? SpiMessageType.GetMotorStatusRight : SpiMessageType.GetMotorStatusLeft;
+ SpiMessageType message_type = port == MotorPort.MotorRight ? SpiMessageType.GetMotorStatusRight : SpiMessageType.GetMotorStatusLeft;
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
if (reply[3] == SpiCorrectDataReturned)
@@ -632,7 +624,7 @@ public void GetGrovePwmFrequency(GrovePort port, uint freq = 24000)
public byte[] GroveI2cTransfer(GrovePort port, byte addr, byte[] arrayToSend, byte inBytes = 0)
{
Stopwatch stopwatch = Stopwatch.StartNew();
- var timeout = stopwatch.ElapsedMilliseconds + 5;
+ long timeout = stopwatch.ElapsedMilliseconds + 5;
while (true)
{
try
@@ -652,7 +644,7 @@ public byte[] GroveI2cTransfer(GrovePort port, byte addr, byte[] arrayToSend, by
// Wait for the sensors to be read
// In theory 115µs per byte sent
int towait = 0;
- if (arrayToSend != null)
+ if (arrayToSend is object)
{
if (arrayToSend.Length != 0)
{
@@ -710,24 +702,24 @@ public void GroveI2cStart(GrovePort port, byte addr, byte[] arrayToSend, byte in
}
else
{
- throw new ArgumentException($"{nameof(GroveI2cStart)} error: Port unsupported. Must be either Grove 1 or Grove 2.");
+ throw new ArgumentException(nameof(port), $"Port unsupported. Must be either {nameof(GrovePort.Grove1)} or {nameof(GrovePort.Grove2)}.");
}
var address = ((addr & 0x7F) << 1);
if (inBytes > GroveI2cLengthLimit)
{
- throw new ArgumentException($"{nameof(GroveI2cStart)} error: Read length error. Up to {GroveI2cLengthLimit} bytes can be read in a single transaction.");
+ throw new ArgumentException(nameof(addr), $"Read length error. Up to {GroveI2cLengthLimit} bytes can be read in a single transaction.");
}
if (arrayToSend.Length > GroveI2cLengthLimit)
{
- throw new ArgumentException($"{nameof(GroveI2cStart)} error:Write length error. Up to {GroveI2cLengthLimit} bytes can be written in a single transaction.");
+ throw new ArgumentException(nameof(arrayToSend), $"Write length error. Up to {GroveI2cLengthLimit} bytes can be written in a single transaction.");
}
byte[] outArray = { SpiAddress, (byte)message_type, (byte)address, inBytes, (byte)arrayToSend.Length };
Array.Resize(ref outArray, outArray.Length + arrayToSend.Length);
Array.Copy(arrayToSend, 0, outArray, outArray.Length - arrayToSend.Length, arrayToSend.Length);
- var reply = SpiTransferArray(outArray);
+ byte[] reply = SpiTransferArray(outArray);
GroveSensor[port_index].I2cDataLength = inBytes;
if (reply[3] != SpiCorrectDataReturned)
@@ -764,7 +756,7 @@ public byte[] GetGroveValue(GrovePort port)
}
else
{
- throw new ArgumentException($"{nameof(GroveI2cStart)} error: Port unsupported. Must be either Grove 1 or Grove 2.");
+ throw new ArgumentException(nameof(port), $"Port unsupported. Must be either {nameof(GrovePort.Grove1)} or {nameof(GrovePort.Grove2)}.");
}
#pragma warning disable SA1011
@@ -881,27 +873,14 @@ public byte[] GetGroveValue(GrovePort port)
/// Returns the pin state
public byte GetGroveState(GrovePort port)
{
- SpiMessageType message_type;
- if (port == GrovePort.Grove1Pin1)
- {
- message_type = SpiMessageType.GetGrove1Pin1State;
- }
- else if (port == GrovePort.Grove1Pin2)
- {
- message_type = SpiMessageType.GetGrove1Pin2State;
- }
- else if (port == GrovePort.Grove2Pin1)
- {
- message_type = SpiMessageType.GetGrove2Pin1State;
- }
- else if (port == GrovePort.Grove2Pin2)
+ SpiMessageType message_type = port switch
{
- message_type = SpiMessageType.GetGrove2Pin2State;
- }
- else
- {
- throw new ArgumentException($"{nameof(GetGroveState)} error: Pin(s) unsupported. Must get one at a time.");
- }
+ GrovePort.Grove1Pin1 => SpiMessageType.GetGrove1Pin1State,
+ GrovePort.Grove1Pin2 => SpiMessageType.GetGrove1Pin2State,
+ GrovePort.Grove2Pin1 => SpiMessageType.GetGrove2Pin1State,
+ GrovePort.Grove2Pin2 => SpiMessageType.GetGrove2Pin2State,
+ _ => throw new ArgumentException(nameof(port), "Pin(s) unsupported. Must get one at a time."),
+ };
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
@@ -929,27 +908,14 @@ public byte GetGroveState(GrovePort port)
/// Returns the voltage in V
public double GetGroveVoltage(GrovePort port)
{
- SpiMessageType message_type;
- if (port == GrovePort.Grove1Pin1)
- {
- message_type = SpiMessageType.GetGrove1Pin1Voltage;
- }
- else if (port == GrovePort.Grove1Pin2)
- {
- message_type = SpiMessageType.GetGrove1Pin2Voltage;
- }
- else if (port == GrovePort.Grove2Pin1)
- {
- message_type = SpiMessageType.GetGrove2Pin1Voltage;
- }
- else if (port == GrovePort.Grove2Pin2)
- {
- message_type = SpiMessageType.GetGrove2Pin2Voltage;
- }
- else
+ SpiMessageType message_type = port switch
{
- throw new ArgumentException($"{nameof(GetGroveVoltage)} error: Pin(s) unsupported. Must get one at a time.");
- }
+ GrovePort.Grove1Pin1 => SpiMessageType.GetGrove1Pin1Voltage,
+ GrovePort.Grove1Pin2 => SpiMessageType.GetGrove1Pin2Voltage,
+ GrovePort.Grove2Pin1 => SpiMessageType.GetGrove2Pin1Voltage,
+ GrovePort.Grove2Pin2 => SpiMessageType.GetGrove2Pin2Voltage,
+ _ => throw new ArgumentException(nameof(port), "Pin(s) unsupported. Must get one at a time."),
+ };
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
@@ -977,27 +943,14 @@ public double GetGroveVoltage(GrovePort port)
/// Returns the analogic read
public int GetGroveAnalog(GrovePort port)
{
- SpiMessageType message_type;
- if (port == GrovePort.Grove1Pin1)
- {
- message_type = SpiMessageType.GetGrove1Pin1Analog;
- }
- else if (port == GrovePort.Grove1Pin2)
- {
- message_type = SpiMessageType.GetGrove1Pin2Analog;
- }
- else if (port == GrovePort.Grove2Pin1)
- {
- message_type = SpiMessageType.GetGrove2Pin1Analog;
- }
- else if (port == GrovePort.Grove2Pin2)
+ SpiMessageType message_type = port switch
{
- message_type = SpiMessageType.GetGrove2Pin2Analog;
- }
- else
- {
- throw new ArgumentException($"{nameof(GetGroveAnalog)} error: Pin(s) unsupported. Must get one at a time.");
- }
+ GrovePort.Grove1Pin1 => SpiMessageType.GetGrove1Pin1Analog,
+ GrovePort.Grove1Pin2 => SpiMessageType.GetGrove1Pin2Analog,
+ GrovePort.Grove2Pin1 => SpiMessageType.GetGrove2Pin1Analog,
+ GrovePort.Grove2Pin2 => SpiMessageType.GetGrove2Pin2Analog,
+ _ => throw new ArgumentException(nameof(port), "Pin(s) unsupported. Must get one at a time."),
+ };
byte[] outArray = { SpiAddress, (byte)message_type, 0, 0, 0, 0, 0 };
var reply = SpiTransferArray(outArray);
diff --git a/src/devices/GoPiGo3/Movements/Motor.cs b/src/devices/GoPiGo3/Movements/Motor.cs
index 241d27c86d..ccf1892dce 100644
--- a/src/devices/GoPiGo3/Movements/Motor.cs
+++ b/src/devices/GoPiGo3/Movements/Motor.cs
@@ -54,7 +54,7 @@ public Motor(GoPiGo brick, MotorPort port, int timeout)
{
if (port == MotorPort.Both)
{
- throw new ArgumentException($"Motor class can only have 1 motor");
+ throw new ArgumentException(nameof(port), "Motor class can only have 1 motor");
}
_goPiGo = brick;
diff --git a/src/devices/GoPiGo3/Movements/Vehicle.cs b/src/devices/GoPiGo3/Movements/Vehicle.cs
index dc7107214c..2442598fdc 100644
--- a/src/devices/GoPiGo3/Movements/Vehicle.cs
+++ b/src/devices/GoPiGo3/Movements/Vehicle.cs
@@ -147,7 +147,7 @@ public bool DirectionOpposite
private void RunMotorSyncTime(MotorPort[] ports, int[] speeds, int timeout)
{
- if ((ports == null) || (speeds == null))
+ if ((ports is null) || (speeds is null))
{
return;
}
@@ -158,7 +158,7 @@ private void RunMotorSyncTime(MotorPort[] ports, int[] speeds, int timeout)
}
// create a timer for the needed time to run
- if (_timer == null)
+ if (_timer is null)
{
_timer = new Timer(RunUntil, null, TimeSpan.FromMilliseconds(timeout), Timeout.InfiniteTimeSpan);
}
@@ -207,7 +207,7 @@ private void StartMotor(MotorPort port, int speed)
private void RunMotorSyncDegrees(MotorPort[] ports, int[] speeds, int[] degrees)
{
- if ((ports == null) || (speeds == null) || degrees == null)
+ if ((ports is null) || (speeds is null) || degrees is null)
{
return;
}
diff --git a/src/devices/GoPiGo3/Sensors/AnalogSensor.cs b/src/devices/GoPiGo3/Sensors/AnalogSensor.cs
index 48d5e4a772..854b92cb3b 100644
--- a/src/devices/GoPiGo3/Sensors/AnalogSensor.cs
+++ b/src/devices/GoPiGo3/Sensors/AnalogSensor.cs
@@ -24,7 +24,7 @@ public AnalogSensor(GoPiGo goPiGo, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Error: Grove Port not supported");
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_goPiGo = goPiGo;
diff --git a/src/devices/GoPiGo3/Sensors/Buzzer.cs b/src/devices/GoPiGo3/Sensors/Buzzer.cs
index 892092a3dd..8919134992 100644
--- a/src/devices/GoPiGo3/Sensors/Buzzer.cs
+++ b/src/devices/GoPiGo3/Sensors/Buzzer.cs
@@ -37,7 +37,7 @@ public Buzzer(GoPiGo goPiGo, GrovePort port, byte duty)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Error: Grove Port not supported");
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_goPiGo = goPiGo;
diff --git a/src/devices/GoPiGo3/Sensors/DigitalInput.cs b/src/devices/GoPiGo3/Sensors/DigitalInput.cs
index bb0b15d9e3..dab6aa4a2f 100644
--- a/src/devices/GoPiGo3/Sensors/DigitalInput.cs
+++ b/src/devices/GoPiGo3/Sensors/DigitalInput.cs
@@ -24,7 +24,7 @@ public DigitalInput(GoPiGo goPiGo, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Error: Grove Port not supported");
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_goPiGo = goPiGo;
diff --git a/src/devices/GoPiGo3/Sensors/DigitalOutput.cs b/src/devices/GoPiGo3/Sensors/DigitalOutput.cs
index 3102ac3876..38cc0a4f9c 100644
--- a/src/devices/GoPiGo3/Sensors/DigitalOutput.cs
+++ b/src/devices/GoPiGo3/Sensors/DigitalOutput.cs
@@ -25,7 +25,7 @@ public DigitalOutput(GoPiGo goPiGo, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Error: Grove Port not supported");
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_goPiGo = goPiGo;
diff --git a/src/devices/GoPiGo3/Sensors/UltraSonicSensor.cs b/src/devices/GoPiGo3/Sensors/UltraSonicSensor.cs
index b1060fc107..1ba0e83f6d 100644
--- a/src/devices/GoPiGo3/Sensors/UltraSonicSensor.cs
+++ b/src/devices/GoPiGo3/Sensors/UltraSonicSensor.cs
@@ -29,7 +29,7 @@ public UltraSonicSensor(GoPiGo goPiGo, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Error: Grove Port not supported");
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_goPiGo = goPiGo;
diff --git a/src/devices/GrovePi/GrovePi.cs b/src/devices/GrovePi/GrovePi.cs
index 95628ffe24..96a50b5fb6 100644
--- a/src/devices/GrovePi/GrovePi.cs
+++ b/src/devices/GrovePi/GrovePi.cs
@@ -101,8 +101,7 @@ public void WriteCommand(GrovePiCommand command, GrovePort pin, byte param1, byt
return;
}
catch (IOException ex)
- {
- // Give it another try
+ {
innerEx = ex;
tries++;
Thread.Sleep(10);
@@ -120,26 +119,18 @@ public void WriteCommand(GrovePiCommand command, GrovePort pin, byte param1, byt
///
public byte[]? ReadCommand(GrovePiCommand command, GrovePort pin)
{
- int numberBytesToRead = 0;
- switch (command)
+ int numberBytesToRead = command switch
+ {
+ GrovePiCommand.DigitalRead => 1,
+ GrovePiCommand.AnalogRead | GrovePiCommand.UltrasonicRead | GrovePiCommand.LetBarGet => 3,
+ GrovePiCommand.Version => 4,
+ GrovePiCommand.DhtTemp => 9,
+ _ => 0,
+ };
+
+ if (numberBytesToRead == 0)
{
- case GrovePiCommand.DigitalRead:
- numberBytesToRead = 1;
- break;
- case GrovePiCommand.AnalogRead:
- case GrovePiCommand.UltrasonicRead:
- case GrovePiCommand.LetBarGet:
- numberBytesToRead = 3;
- break;
- case GrovePiCommand.Version:
- numberBytesToRead = 4;
- break;
- case GrovePiCommand.DhtTemp:
- numberBytesToRead = 9;
- break;
- // No other commands are for read
- default:
- return null;
+ return null;
}
byte[] outArray = new byte[numberBytesToRead];
@@ -203,20 +194,14 @@ public PinValue DigitalRead(GrovePort pin)
///
/// The GroovePi pin to read
/// High to put the pin high, Low to put the pin low
- public void DigitalWrite(GrovePort pin, PinValue pinLevel)
- {
- WriteCommand(GrovePiCommand.DigitalWrite, pin, (byte)pinLevel, 0);
- }
+ public void DigitalWrite(GrovePort pin, PinValue pinLevel) => WriteCommand(GrovePiCommand.DigitalWrite, pin, (byte)pinLevel, 0);
///
/// Setup the pin mode, equivalent of pinMod on Arduino
///
/// The GroovePi pin to setup
/// THe mode to setup Intput or Output
- public void PinMode(GrovePort pin, PinMode mode)
- {
- WriteCommand(GrovePiCommand.PinMode, pin, (byte)mode, 0);
- }
+ public void PinMode(GrovePort pin, PinMode mode) => WriteCommand(GrovePiCommand.PinMode, pin, (byte)mode, 0);
///
/// Read an analog value on a pin, equivalent of analogRead on Arduino
@@ -242,9 +227,6 @@ public int AnalogRead(GrovePort pin)
///
/// The GroovePi pin to write
/// The value to write between 0 and 255
- public void AnalogWrite(GrovePort pin, byte value)
- {
- WriteCommand(GrovePiCommand.AnalogWrite, pin, value, 0);
- }
+ public void AnalogWrite(GrovePort pin, byte value) => WriteCommand(GrovePiCommand.AnalogWrite, pin, value, 0);
}
}
diff --git a/src/devices/GrovePi/Sensors/AnalogSensor.cs b/src/devices/GrovePi/Sensors/AnalogSensor.cs
index ce9ce53e55..ff44a54261 100644
--- a/src/devices/GrovePi/Sensors/AnalogSensor.cs
+++ b/src/devices/GrovePi/Sensors/AnalogSensor.cs
@@ -34,7 +34,7 @@ public AnalogSensor(GrovePi grovePi, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_grovePi = grovePi;
diff --git a/src/devices/GrovePi/Sensors/DhtSensor.cs b/src/devices/GrovePi/Sensors/DhtSensor.cs
index 66d5711f95..013b5a3465 100644
--- a/src/devices/GrovePi/Sensors/DhtSensor.cs
+++ b/src/devices/GrovePi/Sensors/DhtSensor.cs
@@ -31,7 +31,7 @@ public DhtSensor(GrovePi grovePi, GrovePort port, DhtType dhtType)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_grovePi = grovePi;
diff --git a/src/devices/GrovePi/Sensors/DigitalInput.cs b/src/devices/GrovePi/Sensors/DigitalInput.cs
index 7a1c6cebc2..cd2ec512f0 100644
--- a/src/devices/GrovePi/Sensors/DigitalInput.cs
+++ b/src/devices/GrovePi/Sensors/DigitalInput.cs
@@ -24,7 +24,7 @@ public DigitalInput(GrovePi grovePi, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported");
}
_grovePi = grovePi;
diff --git a/src/devices/GrovePi/Sensors/DigitalOutput.cs b/src/devices/GrovePi/Sensors/DigitalOutput.cs
index ff9883a93d..4fa2272069 100644
--- a/src/devices/GrovePi/Sensors/DigitalOutput.cs
+++ b/src/devices/GrovePi/Sensors/DigitalOutput.cs
@@ -30,7 +30,7 @@ public DigitalOutput(GrovePi grovePi, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported.");
}
_grovePi = grovePi;
diff --git a/src/devices/GrovePi/Sensors/LedBar.cs b/src/devices/GrovePi/Sensors/LedBar.cs
index 45e39b0080..0a2ffb7463 100644
--- a/src/devices/GrovePi/Sensors/LedBar.cs
+++ b/src/devices/GrovePi/Sensors/LedBar.cs
@@ -53,7 +53,7 @@ public LedBar(GrovePi grovePi, GrovePort port, LedBarOrientation orientation)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported.");
}
_grovePi = grovePi;
@@ -97,7 +97,7 @@ public byte Value
{
if (value > 10)
{
- throw new ArgumentException($"Only 10 leds can be controlled");
+ throw new ArgumentException(nameof(Value), "Only 10 leds can be controlled, 1-10.");
}
_grovePi.WriteCommand(GrovePiCommand.LedBarLevel, _port, _level, 0);
@@ -113,7 +113,7 @@ public void SetOneLed(byte led, bool status)
{
if (led > 10)
{
- throw new ArgumentException($"{nameof(led)} can only be from 0 to 10");
+ throw new ArgumentException(nameof(led), "Only 10 leds can be controlled, 1-10.");
}
_grovePi.WriteCommand(GrovePiCommand.LedBarSetOneLed, _port, led, status ? (byte)1 : (byte)0);
diff --git a/src/devices/GrovePi/Sensors/PwmOutput.cs b/src/devices/GrovePi/Sensors/PwmOutput.cs
index 362cb89809..7d08483cec 100644
--- a/src/devices/GrovePi/Sensors/PwmOutput.cs
+++ b/src/devices/GrovePi/Sensors/PwmOutput.cs
@@ -30,7 +30,7 @@ public PwmOutput(GrovePi grovePi, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported.");
}
_grovePi = grovePi;
diff --git a/src/devices/GrovePi/Sensors/UltrasonicSensor.cs b/src/devices/GrovePi/Sensors/UltrasonicSensor.cs
index b7d9f7254c..e5b217a75b 100644
--- a/src/devices/GrovePi/Sensors/UltrasonicSensor.cs
+++ b/src/devices/GrovePi/Sensors/UltrasonicSensor.cs
@@ -30,7 +30,7 @@ public UltrasonicSensor(GrovePi grovePi, GrovePort port)
{
if (!SupportedPorts.Contains(port))
{
- throw new ArgumentException($"Grove port {port} not supported.", nameof(port));
+ throw new ArgumentException(nameof(port), "Grove port not supported.");
}
_grovePi = grovePi;
diff --git a/src/devices/GrovePi/samples/Program.cs b/src/devices/GrovePi/samples/Program.cs
index 5c06d0082f..f17a09f3fe 100644
--- a/src/devices/GrovePi/samples/Program.cs
+++ b/src/devices/GrovePi/samples/Program.cs
@@ -22,8 +22,8 @@
grovePi.PinMode(GrovePort.DigitalPin3, PinMode.Output);
grovePi.PinMode(GrovePort.DigitalPin4, PinMode.Input);
// 2 high level classes
-UltrasonicSensor ultrasonic = new UltrasonicSensor(grovePi, GrovePort.DigitalPin6);
-DhtSensor dhtSensor = new DhtSensor(grovePi, GrovePort.DigitalPin7, DhtType.Dht11);
+UltrasonicSensor ultrasonic = new (grovePi, GrovePort.DigitalPin6);
+DhtSensor dhtSensor = new (grovePi, GrovePort.DigitalPin7, DhtType.Dht11);
int poten = 0;
while (!Console.KeyAvailable)
{
diff --git a/src/devices/Hcsr04/Hcsr04.cs b/src/devices/Hcsr04/Hcsr04.cs
index 24e4085677..7ab45fcbbe 100644
--- a/src/devices/Hcsr04/Hcsr04.cs
+++ b/src/devices/Hcsr04/Hcsr04.cs
@@ -35,12 +35,12 @@ public class Hcsr04 : IDisposable
/// Trigger pulse input.
/// Trigger pulse output.
/// True to dispose the Gpio Controller
- public Hcsr04(GpioController gpioController, int triggerPin, int echoPin, bool shouldDispose = true)
+ public Hcsr04(GpioController? gpioController, int triggerPin, int echoPin, bool shouldDispose = true)
{
+ _shouldDispose = shouldDispose || gpioController is null;
+ _controller = gpioController ?? new ();
_echo = echoPin;
_trigger = triggerPin;
- _controller = gpioController;
- _shouldDispose = shouldDispose;
_controller.OpenPin(_echo, PinMode.Input);
_controller.OpenPin(_trigger, PinMode.Output);
diff --git a/src/devices/Hcsr04/samples/Program.cs b/src/devices/Hcsr04/samples/Program.cs
index 739733896b..3e181e4e19 100644
--- a/src/devices/Hcsr04/samples/Program.cs
+++ b/src/devices/Hcsr04/samples/Program.cs
@@ -8,7 +8,7 @@
Console.WriteLine("Hello Hcsr04 Sample!");
-using var sonar = new Hcsr04(4, 17);
+using Hcsr04 sonar = new (4, 17);
while (true)
{
if (sonar.TryGetDistance(out Length distance))
diff --git a/src/devices/Hcsr501/Hcsr501.cs b/src/devices/Hcsr501/Hcsr501.cs
index 5445e581ca..1afbcf2a4f 100644
--- a/src/devices/Hcsr501/Hcsr501.cs
+++ b/src/devices/Hcsr501/Hcsr501.cs
@@ -26,7 +26,7 @@ public Hcsr501(int outPin, PinNumberingScheme pinNumberingScheme = PinNumberingS
{
_outPin = outPin;
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
_controller = gpioController ?? new GpioController(pinNumberingScheme);
_controller.OpenPin(outPin, PinMode.Input);
_controller.RegisterCallbackForPinValueChangedEvent(outPin, PinEventTypes.Falling, Sensor_ValueChanged);
@@ -64,7 +64,7 @@ public void Dispose()
private void Sensor_ValueChanged(object sender, PinValueChangedEventArgs e)
{
- if (Hcsr501ValueChanged != null)
+ if (Hcsr501ValueChanged is object)
{
Hcsr501ValueChanged(sender, new Hcsr501ValueChangedEventArgs(_controller.Read(_outPin)));
}
diff --git a/src/devices/Hcsr501/Hcsr501ValueChangedEventArgs.cs b/src/devices/Hcsr501/Hcsr501ValueChangedEventArgs.cs
index 2e95bc4fd8..bc53219cd9 100644
--- a/src/devices/Hcsr501/Hcsr501ValueChangedEventArgs.cs
+++ b/src/devices/Hcsr501/Hcsr501ValueChangedEventArgs.cs
@@ -20,9 +20,6 @@ public class Hcsr501ValueChangedEventArgs : EventArgs
/// Constructs Hcsr501ValueChangedEventArgs instance
///
/// New value of pin
- public Hcsr501ValueChangedEventArgs(PinValue value)
- {
- PinValue = value;
- }
+ public Hcsr501ValueChangedEventArgs(PinValue value) => PinValue = value;
}
}
diff --git a/src/devices/Hcsr501/samples/Program.cs b/src/devices/Hcsr501/samples/Program.cs
index 7673bb2a10..c4d91813c4 100644
--- a/src/devices/Hcsr501/samples/Program.cs
+++ b/src/devices/Hcsr501/samples/Program.cs
@@ -9,11 +9,10 @@
const int Hcsr501Pin = 17;
const int LedPin = 27;
-using GpioController ledController = new GpioController();
+using GpioController ledController = new ();
ledController.OpenPin(LedPin, PinMode.Output);
-using Iot.Device.Hcsr501.Hcsr501 sensor =
- new Iot.Device.Hcsr501.Hcsr501(Hcsr501Pin);
+using Hcsr501 sensor = new (Hcsr501Pin);
while (true)
{
// adjusting the detection distance and time by rotating the potentiometer on the sensor
diff --git a/src/devices/Hmc5883l/Hmc5883l.cs b/src/devices/Hmc5883l/Hmc5883l.cs
index 1d01d314e7..2fb8518af9 100644
--- a/src/devices/Hmc5883l/Hmc5883l.cs
+++ b/src/devices/Hmc5883l/Hmc5883l.cs
@@ -58,7 +58,7 @@ public Hmc5883l(
SamplesAmount samplesAmount = SamplesAmount.One,
MeasurementConfiguration measurementConfig = MeasurementConfiguration.Normal)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_gain = (byte)gain;
_measuringMode = (byte)measuringMode;
_outputRate = (byte)outputRate;
diff --git a/src/devices/Hmc5883l/samples/Program.cs b/src/devices/Hmc5883l/samples/Program.cs
index b88d3f5473..1269f907ad 100644
--- a/src/devices/Hmc5883l/samples/Program.cs
+++ b/src/devices/Hmc5883l/samples/Program.cs
@@ -8,7 +8,7 @@
I2cConnectionSettings settings = new (1, Hmc5883l.DefaultI2cAddress);
using I2cDevice device = I2cDevice.Create(settings);
-using Hmc5883l sensor = new Hmc5883l(device);
+using Hmc5883l sensor = new (device);
while (true)
{
// read heading
diff --git a/src/devices/Hts221/Hts221.cs b/src/devices/Hts221/Hts221.cs
index a01aff49c7..6dd89c8a19 100644
--- a/src/devices/Hts221/Hts221.cs
+++ b/src/devices/Hts221/Hts221.cs
@@ -21,12 +21,7 @@ public class Hts221 : IDisposable
///
public Hts221(I2cDevice i2cDevice)
{
- if (i2cDevice == null)
- {
- throw new ArgumentNullException(nameof(i2cDevice));
- }
-
- _i2c = i2cDevice;
+ _i2c = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
// Highest resolution for both temperature and humidity sensor:
// 0.007 DegreesCelsius and 0.03 percentage of relative humidity respectively
diff --git a/src/devices/Hts221/samples/Program.cs b/src/devices/Hts221/samples/Program.cs
index 4aae9a2b0d..563bccd555 100644
--- a/src/devices/Hts221/samples/Program.cs
+++ b/src/devices/Hts221/samples/Program.cs
@@ -11,7 +11,7 @@
// I2C address on SenseHat board
const int I2cAddress = 0x5F;
-using var th = new Hts221(CreateI2cDevice());
+using Hts221 th = new (CreateI2cDevice());
while (true)
{
var tempValue = th.Temperature;
diff --git a/src/devices/Ina219/Ina219.cs b/src/devices/Ina219/Ina219.cs
index 2d1f4d6a98..2ec0631dad 100644
--- a/src/devices/Ina219/Ina219.cs
+++ b/src/devices/Ina219/Ina219.cs
@@ -31,7 +31,7 @@ public class Ina219 : IDisposable
// These values are the datasheet defined delays in micro seconds between requesting a Current or Power value from the INA219 and the ADC sampling having completed
// along with any conversions.
- private static readonly Dictionary s_readDelays = new Dictionary()
+ private static readonly Dictionary s_readDelays = new ()
{
{ Ina219AdcResolutionOrSamples.Adc9Bit, 84 },
{ Ina219AdcResolutionOrSamples.Adc10Bit, 148 },
@@ -46,19 +46,6 @@ public class Ina219 : IDisposable
{ Ina219AdcResolutionOrSamples.Adc128Sample, 68100 }
};
- ///
- /// Method to initialize values during device construction
- ///
- /// Interface to I2C device access
-#if !NETCOREAPP2_1 && !NETCOREAPP3_1
- [MemberNotNull(nameof(_i2cDevice))]
-#endif
- private void Initialize(I2cDevice i2cDevice)
- {
- _currentLsb = 1F;
- _i2cDevice = i2cDevice;
- }
-
///
/// Construct an Ina219 device using an I2cDevice
///
@@ -68,12 +55,8 @@ private void Initialize(I2cDevice i2cDevice)
/// The I2cDevice initialized to communicate with the INA219.
public Ina219(I2cDevice i2cDevice)
{
- if (_i2cDevice is null)
- {
- throw new ArgumentException($"{nameof(i2cDevice)} is not configured");
- }
-
- Initialize(i2cDevice);
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
+ _currentLsb = 1F;
}
///
@@ -82,18 +65,9 @@ public Ina219(I2cDevice i2cDevice)
///
/// This binding creates an I2cDevice ufor communication with the INA219. The I2cDevice is disposed when then INA219 is disposed.
///
- /// The I2cConnectionSettings object initialized with the appropiate settings to communicate with the INA219.
+ /// The I2cConnectionSettings object initialized with the appropriate settings to communicate with the INA219.
public Ina219(I2cConnectionSettings settings)
- {
- Initialize(I2cDevice.Create(settings));
- _disposeI2cDevice = true;
-#if NETCOREAPP2_1 || NETCOREAPP3_1
- if (_i2cDevice is null)
- {
- throw new ArgumentException($"{nameof(_i2cDevice)} is not configured");
- }
-#endif
- }
+ : this(I2cDevice.Create(settings)) => _disposeI2cDevice = true;
///
/// Reset the INA219 to default values;
@@ -120,7 +94,6 @@ public void Reset()
public Ina219OperatingMode OperatingMode
{
get => (Ina219OperatingMode)(ReadRegister(Ina219Register.Configuration) & (ushort)Ina219ConfigurationFlags.ModeMask);
-
set
{
ushort regValue = ReadRegister(Ina219Register.Configuration);
@@ -142,7 +115,6 @@ public Ina219OperatingMode OperatingMode
public Ina219BusVoltageRange BusVoltageRange
{
get => (Ina219BusVoltageRange)(ReadRegister(Ina219Register.Configuration) & (ushort)Ina219ConfigurationFlags.BrngMask);
-
set
{
ushort regValue = ReadRegister(Ina219Register.Configuration);
@@ -164,7 +136,6 @@ public Ina219BusVoltageRange BusVoltageRange
public Ina219PgaSensitivity PgaSensitivity
{
get => (Ina219PgaSensitivity)(ReadRegister(Ina219Register.Configuration) & (ushort)Ina219ConfigurationFlags.PgaMask);
-
set
{
ushort regValue = ReadRegister(Ina219Register.Configuration);
@@ -185,7 +156,6 @@ public Ina219PgaSensitivity PgaSensitivity
public Ina219AdcResolutionOrSamples BusAdcResolutionOrSamples
{
get => (Ina219AdcResolutionOrSamples)((ReadRegister(Ina219Register.Configuration) & (ushort)Ina219ConfigurationFlags.BadcMask) >> 4);
-
set
{
ushort regValue = ReadRegister(Ina219Register.Configuration);
@@ -208,7 +178,6 @@ public Ina219AdcResolutionOrSamples BusAdcResolutionOrSamples
public Ina219AdcResolutionOrSamples ShuntAdcResolutionOrSamples
{
get => (Ina219AdcResolutionOrSamples)(ReadRegister(Ina219Register.Configuration) & (ushort)Ina219ConfigurationFlags.SadcMask);
-
set
{
ushort regValue = ReadRegister(Ina219Register.Configuration);
@@ -261,21 +230,15 @@ public void Dispose()
/// Read the measured shunt voltage.
///
/// The shunt potential difference
- public ElectricPotential ReadShuntVoltage()
- {
- // read the shunt voltage. LSB = 10uV then convert to Volts
- return ElectricPotential.FromVolts(ReadRegister(Ina219Register.ShuntVoltage, s_readDelays[(Ina219AdcResolutionOrSamples)_shuntAdcResSamp]) * 10.0 / 1000000.0);
- }
+ // read the shunt voltage. LSB = 10uV then convert to Volts
+ public ElectricPotential ReadShuntVoltage() => ElectricPotential.FromVolts(ReadRegister(Ina219Register.ShuntVoltage, s_readDelays[(Ina219AdcResolutionOrSamples)_shuntAdcResSamp]) * 10.0 / 1000000.0);
///
/// Read the measured Bus voltage.
///
/// The Bus potential (voltage)
- public ElectricPotential ReadBusVoltage()
- {
- // read the bus voltage. LSB = 4mV then convert to Volts
- return ElectricPotential.FromVolts(((short)ReadRegister(Ina219Register.BusVoltage, s_readDelays[_busAdcResSamp]) >> 3) * 4 / 1000.0);
- }
+ // read the bus voltage. LSB = 4mV then convert to Volts
+ public ElectricPotential ReadBusVoltage() => ElectricPotential.FromVolts(((short)ReadRegister(Ina219Register.BusVoltage, s_readDelays[_busAdcResSamp]) >> 3) * 4 / 1000.0);
///
/// Read the calculated current through the INA219.
diff --git a/src/devices/Ina219/samples/Program.cs b/src/devices/Ina219/samples/Program.cs
index e0d5f38cd2..b5b8beaecc 100644
--- a/src/devices/Ina219/samples/Program.cs
+++ b/src/devices/Ina219/samples/Program.cs
@@ -11,7 +11,7 @@
const byte Adafruit_Ina219_I2cBus = 0x1;
// create an INA219 device on I2C bus 1 addressing channel 64
-using Ina219 device = new Ina219(new I2cConnectionSettings(Adafruit_Ina219_I2cBus, Adafruit_Ina219_I2cAddress));
+using Ina219 device = new (new I2cConnectionSettings(Adafruit_Ina219_I2cBus, Adafruit_Ina219_I2cAddress));
// reset the device
device.Reset();
diff --git a/src/devices/LiquidLevel/LiquidLevelSwitch.cs b/src/devices/LiquidLevel/LiquidLevelSwitch.cs
index 0e362ba529..af82786c13 100644
--- a/src/devices/LiquidLevel/LiquidLevelSwitch.cs
+++ b/src/devices/LiquidLevel/LiquidLevelSwitch.cs
@@ -26,22 +26,19 @@ public class LiquidLevelSwitch : IDisposable
public LiquidLevelSwitch(int dataPin, PinValue liquidPresentPinState, GpioController? gpioController = null, PinNumberingScheme pinNumberingScheme = PinNumberingScheme.Logical, bool shouldDispose = true)
{
_controller = gpioController ?? new GpioController(pinNumberingScheme);
+ _shouldDispose = shouldDispose || gpioController is null;
_dataPin = dataPin;
_liquidPresentPinState = liquidPresentPinState;
_controller.OpenPin(_dataPin, PinMode.Input);
- _shouldDispose = shouldDispose || gpioController == null;
}
///
/// Determines whether liquid is present.
///
/// true
if liquid is present, otherwise false
.
- public bool IsLiquidPresent()
- {
- return _controller.Read(_dataPin) == _liquidPresentPinState;
- }
+ public bool IsLiquidPresent() => _controller.Read(_dataPin) == _liquidPresentPinState;
///
/// Dispose Buzzer.
diff --git a/src/devices/LiquidLevel/samples/LiquidLevelSwitch.sample.cs b/src/devices/LiquidLevel/samples/LiquidLevelSwitch.sample.cs
index 9779e8115a..045e0a9f4c 100644
--- a/src/devices/LiquidLevel/samples/LiquidLevelSwitch.sample.cs
+++ b/src/devices/LiquidLevel/samples/LiquidLevelSwitch.sample.cs
@@ -6,7 +6,7 @@
using System.Threading;
using Iot.Device.LiquidLevel;
-using LiquidLevelSwitch sensor = new LiquidLevelSwitch(23, PinValue.Low);
+using LiquidLevelSwitch sensor = new (23, PinValue.Low);
while (true)
{
// read liquid level switch
diff --git a/src/devices/LiquidLevel/samples/Llc200d3sh.sample.cs b/src/devices/LiquidLevel/samples/Llc200d3sh.sample.cs
index e3112fb57a..534ea8740b 100644
--- a/src/devices/LiquidLevel/samples/Llc200d3sh.sample.cs
+++ b/src/devices/LiquidLevel/samples/Llc200d3sh.sample.cs
@@ -5,7 +5,7 @@
using System.Threading;
using Iot.Device.LiquidLevel;
-using Llc200d3sh sensor = new Llc200d3sh(23);
+using Llc200d3sh sensor = new (23);
while (true)
{
// read liquid level switch
diff --git a/src/devices/Lm75/Lm75.cs b/src/devices/Lm75/Lm75.cs
index 085d1ed194..9cfd940b49 100644
--- a/src/devices/Lm75/Lm75.cs
+++ b/src/devices/Lm75/Lm75.cs
@@ -33,10 +33,7 @@ public class Lm75 : IDisposable
///
public bool Disabled
{
- get
- {
- return _disable;
- }
+ get => _disable;
set
{
SetShutdown(value);
@@ -52,8 +49,7 @@ public bool Disabled
/// The I2C device used for communication.
public Lm75(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
-
+ _i2cDevice = i2cDevice ?? throw new ArgumentException(nameof(i2cDevice));
Disabled = false;
}
diff --git a/src/devices/Lm75/samples/Program.cs b/src/devices/Lm75/samples/Program.cs
index 89884e63aa..f744c24cf8 100644
--- a/src/devices/Lm75/samples/Program.cs
+++ b/src/devices/Lm75/samples/Program.cs
@@ -9,7 +9,7 @@
I2cConnectionSettings settings = new (1, Lm75.DefaultI2cAddress);
using I2cDevice device = I2cDevice.Create(settings);
-using Lm75 sensor = new Lm75(device);
+using Lm75 sensor = new (device);
while (true)
{
// read temperature
diff --git a/src/devices/Lps25h/Lps25h.cs b/src/devices/Lps25h/Lps25h.cs
index 78ae405dd1..2bb5982b1c 100644
--- a/src/devices/Lps25h/Lps25h.cs
+++ b/src/devices/Lps25h/Lps25h.cs
@@ -22,12 +22,7 @@ public class Lps25h : IDisposable
///
public Lps25h(I2cDevice i2cDevice)
{
- if (i2cDevice == null)
- {
- throw new ArgumentNullException(nameof(i2cDevice));
- }
-
- _i2c = i2cDevice;
+ _i2c = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
// Highest resolution for both pressure and temperature sensor
byte resolution = Read(Register.ResolutionMode);
diff --git a/src/devices/Lps25h/samples/Program.cs b/src/devices/Lps25h/samples/Program.cs
index 882d24ea76..0dfce4987f 100644
--- a/src/devices/Lps25h/samples/Program.cs
+++ b/src/devices/Lps25h/samples/Program.cs
@@ -14,12 +14,12 @@
// set this to the current sea level pressure in the area for correct altitude readings
var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
-using var th = new Lps25h(CreateI2cDevice());
+using Lps25h th = new (CreateI2cDevice());
while (true)
{
- var tempValue = th.Temperature;
- var preValue = th.Pressure;
- var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);
+ Temperature tempValue = th.Temperature;
+ Pressure preValue = th.Pressure;
+ Length altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);
Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
diff --git a/src/devices/Lsm9Ds1/Lsm9Ds1.AccelerometerAndGyroscope.cs b/src/devices/Lsm9Ds1/Lsm9Ds1.AccelerometerAndGyroscope.cs
index d2d919baec..b330ed087b 100644
--- a/src/devices/Lsm9Ds1/Lsm9Ds1.AccelerometerAndGyroscope.cs
+++ b/src/devices/Lsm9Ds1/Lsm9Ds1.AccelerometerAndGyroscope.cs
@@ -14,6 +14,7 @@ namespace Iot.Device.Lsm9Ds1
public class Lsm9Ds1AccelerometerAndGyroscope : IDisposable
{
private const byte ReadMask = 0x80;
+ private const int Max = (1 << 15);
private I2cDevice _i2c;
private AccelerationScale _accelerometerScale;
private AngularRateScale _angularRateScale;
@@ -26,12 +27,7 @@ public Lsm9Ds1AccelerometerAndGyroscope(
AccelerationScale accelerationScale = AccelerationScale.Scale02G,
AngularRateScale angularRateScale = AngularRateScale.Scale0245Dps)
{
- if (i2cDevice == null)
- {
- throw new ArgumentNullException(nameof(i2cDevice));
- }
-
- _i2c = i2cDevice;
+ _i2c = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_accelerometerScale = accelerationScale;
_angularRateScale = angularRateScale;
@@ -90,44 +86,26 @@ private void Read(RegisterAG register, Span buffer)
_i2c.Read(buffer);
}
- private float GetAccelerationDivisor()
+ // intentionally return float
+ // we have 16-bit signed number
+ // we can use int since our divisors are powers of 2
+ private float GetAccelerationDivisor() => _accelerometerScale switch
{
- // intentionally return float
-
- // we have 16-bit signed number
- // we can use int since our divisors are powers of 2
- const int max = (1 << 15);
- switch (_accelerometerScale)
- {
- case AccelerationScale.Scale02G:
- return max / 2;
- case AccelerationScale.Scale04G:
- return max / 4;
- case AccelerationScale.Scale08G:
- return max / 8;
- case AccelerationScale.Scale16G:
- return max / 16;
- default:
- throw new ArgumentException(nameof(_accelerometerScale));
- }
- }
-
- private float GetAngularRateDivisor()
+ AccelerationScale.Scale02G => Max / 2,
+ AccelerationScale.Scale04G => Max / 4,
+ AccelerationScale.Scale08G => Max / 8,
+ AccelerationScale.Scale16G => Max / 16,
+ _ => throw new ArgumentException(nameof(_accelerometerScale), "Value is unknown."),
+ };
+
+ // we have 16-bit signed number
+ private float GetAngularRateDivisor() => _angularRateScale switch
{
- // we have 16-bit signed number
- const float max = (float)(1 << 15);
- switch (_angularRateScale)
- {
- case AngularRateScale.Scale0245Dps:
- return max / 245;
- case AngularRateScale.Scale0500Dps:
- return max / 500;
- case AngularRateScale.Scale2000Dps:
- return max / 2000;
- default:
- throw new ArgumentException(nameof(_angularRateScale));
- }
- }
+ AngularRateScale.Scale0245Dps => Max / 245,
+ AngularRateScale.Scale0500Dps => Max / 500,
+ AngularRateScale.Scale2000Dps => Max / 2000,
+ _ => throw new ArgumentException(nameof(_angularRateScale), "Value is unknown."),
+ };
///
public void Dispose()
diff --git a/src/devices/Lsm9Ds1/Lsm9Ds1.Magnetometer.cs b/src/devices/Lsm9Ds1/Lsm9Ds1.Magnetometer.cs
index 1ed8dbaea4..51e488bbf8 100644
--- a/src/devices/Lsm9Ds1/Lsm9Ds1.Magnetometer.cs
+++ b/src/devices/Lsm9Ds1/Lsm9Ds1.Magnetometer.cs
@@ -14,6 +14,7 @@ namespace Iot.Device.Lsm9Ds1
public class Lsm9Ds1Magnetometer : IDisposable
{
private const byte ReadMask = 0x80;
+ private const float Max = (1 << 15);
private I2cDevice _i2c;
private MagneticInductionScale _magneticInductionScale;
@@ -24,12 +25,7 @@ public Lsm9Ds1Magnetometer(
I2cDevice i2cDevice,
MagneticInductionScale magneticInductionScale = MagneticInductionScale.Scale04G)
{
- if (i2cDevice == null)
- {
- throw new ArgumentNullException(nameof(i2cDevice));
- }
-
- _i2c = i2cDevice;
+ _i2c = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_magneticInductionScale = magneticInductionScale;
byte temperatureCompensation = 1; // enable temperature compensation
@@ -97,23 +93,14 @@ private void Read(RegisterM register, Span buffer)
_i2c.Read(buffer);
}
- private float GetMagneticInductionDivisor()
+ private float GetMagneticInductionDivisor() => _magneticInductionScale switch
{
- const float max = (1 << 15);
- switch (_magneticInductionScale)
- {
- case MagneticInductionScale.Scale04G:
- return max / 4;
- case MagneticInductionScale.Scale08G:
- return max / 8;
- case MagneticInductionScale.Scale12G:
- return max / 12;
- case MagneticInductionScale.Scale16G:
- return max / 16;
- default:
- throw new ArgumentException(nameof(_magneticInductionScale));
- }
- }
+ MagneticInductionScale.Scale04G => Max / 4,
+ MagneticInductionScale.Scale08G => Max / 8,
+ MagneticInductionScale.Scale12G => Max / 12,
+ MagneticInductionScale.Scale16G => Max / 16,
+ _ => throw new ArgumentException(nameof(_magneticInductionScale)),
+ };
///
public void Dispose()
diff --git a/src/devices/Lsm9Ds1/samples/Lsm9Ds1.AccelerometerAndGyroscope.Sample.cs b/src/devices/Lsm9Ds1/samples/Lsm9Ds1.AccelerometerAndGyroscope.Sample.cs
index 1b81913cc8..bdbea59ce2 100644
--- a/src/devices/Lsm9Ds1/samples/Lsm9Ds1.AccelerometerAndGyroscope.Sample.cs
+++ b/src/devices/Lsm9Ds1/samples/Lsm9Ds1.AccelerometerAndGyroscope.Sample.cs
@@ -13,7 +13,7 @@ internal class AccelerometerAndGyroscope
public static void Run()
{
- using var ag = new Lsm9Ds1AccelerometerAndGyroscope(CreateI2cDevice());
+ using Lsm9Ds1AccelerometerAndGyroscope ag = new (CreateI2cDevice());
while (true)
{
Console.WriteLine($"Acceleration={ag.Acceleration}");
@@ -24,7 +24,7 @@ public static void Run()
private static I2cDevice CreateI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
}
diff --git a/src/devices/Lsm9Ds1/samples/Lsm9Ds1.Magnetometer.Sample.cs b/src/devices/Lsm9Ds1/samples/Lsm9Ds1.Magnetometer.Sample.cs
index e9af545664..a7f26694bb 100644
--- a/src/devices/Lsm9Ds1/samples/Lsm9Ds1.Magnetometer.Sample.cs
+++ b/src/devices/Lsm9Ds1/samples/Lsm9Ds1.Magnetometer.Sample.cs
@@ -16,15 +16,16 @@ internal class Magnetometer
public static void Run()
{
- using (var m = new Lsm9Ds1Magnetometer(CreateI2cDevice()))
+ using (Lsm9Ds1Magnetometer m = new (CreateI2cDevice()))
{
Console.WriteLine("Calibrating...");
Console.WriteLine("Move the sensor around Z for the next 20 seconds, try covering every angle");
+ TimeSpan timeout = TimeSpan.FromMilliseconds(20000);
Stopwatch sw = Stopwatch.StartNew();
Vector3 min = m.MagneticInduction;
Vector3 max = m.MagneticInduction;
- while (sw.ElapsedMilliseconds < 20 * 1000)
+ while (sw.Elapsed < timeout)
{
Vector3 sample = m.MagneticInduction;
min = Vector3.Min(min, sample);
@@ -82,7 +83,7 @@ public static void Run()
private static I2cDevice CreateI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
}
diff --git a/src/devices/Max44009/Max44009.cs b/src/devices/Max44009/Max44009.cs
index 9355ee1c23..0a4a8c9e5f 100644
--- a/src/devices/Max44009/Max44009.cs
+++ b/src/devices/Max44009/Max44009.cs
@@ -21,7 +21,7 @@ public class Max44009 : IDisposable
///
/// MAX44009 Illuminance (Lux)
///
- public double Illuminance { get => GetIlluminance(); }
+ public double Illuminance => GetIlluminance();
///
/// Creates a new instance of the MAX44009, MAX44009 working mode is default. (Consume lowest power)
@@ -29,7 +29,7 @@ public class Max44009 : IDisposable
/// The I2C device used for communication.
public Max44009(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
// Details in the Datasheet P8
Span writeBuff = stackalloc byte[2]
@@ -47,7 +47,7 @@ public Max44009(I2cDevice i2cDevice)
/// Measurement Cycle
public Max44009(I2cDevice i2cDevice, IntegrationTime integrationTime)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
// Details in the Datasheet P8
Span writeBuff = stackalloc byte[2]
diff --git a/src/devices/Max44009/samples/Program.cs b/src/devices/Max44009/samples/Program.cs
index 8b069190d0..da430e0bab 100644
--- a/src/devices/Max44009/samples/Program.cs
+++ b/src/devices/Max44009/samples/Program.cs
@@ -10,7 +10,7 @@
using I2cDevice device = I2cDevice.Create(settings);
// integration time is 100ms
-using Max44009 sensor = new Max44009(device, IntegrationTime.Time100);
+using Max44009 sensor = new (device, IntegrationTime.Time100);
while (true)
{
// read illuminance
diff --git a/src/devices/Max7219/MatrixGraphics.cs b/src/devices/Max7219/MatrixGraphics.cs
index 3ae84a0f16..ffdc79c526 100644
--- a/src/devices/Max7219/MatrixGraphics.cs
+++ b/src/devices/Max7219/MatrixGraphics.cs
@@ -22,18 +22,8 @@ public class MatrixGraphics
/// Font to use for drawing text
public MatrixGraphics(Max7219 device, IFont font)
{
- if (device == null)
- {
- throw new ArgumentNullException(nameof(device));
- }
-
- if (font == null)
- {
- throw new ArgumentNullException(nameof(font));
- }
-
- _device = device;
- Font = font;
+ _device = device ?? throw new ArgumentNullException(nameof(device));
+ Font = font ?? throw new ArgumentNullException(nameof(font));
}
///
@@ -47,7 +37,7 @@ public MatrixGraphics(Max7219 device, IFont font)
public void WriteLetter(int deviceId, char chr, bool flush = true)
{
var charBytes = Font[chr];
- var end = Math.Min(charBytes.Count, Max7219.NumDigits);
+ int end = Math.Min(charBytes.Count, Max7219.NumDigits);
for (int col = 0; col < end; col++)
{
_device[deviceId, col] = charBytes[col];
diff --git a/src/devices/Max7219/Max7219.cs b/src/devices/Max7219/Max7219.cs
index b8140c471f..ab2c61d6a8 100644
--- a/src/devices/Max7219/Max7219.cs
+++ b/src/devices/Max7219/Max7219.cs
@@ -55,12 +55,7 @@ public partial class Max7219 : IDisposable
///
public Max7219(SpiDevice spiDevice, int cascadedDevices = 1, RotationType rotation = RotationType.None)
{
- if (spiDevice == null)
- {
- throw new ArgumentNullException(nameof(spiDevice));
- }
-
- _spiDevice = spiDevice;
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
CascadedDevices = cascadedDevices;
Rotation = rotation;
_buffer = new byte[CascadedDevices, NumDigits];
@@ -101,10 +96,7 @@ internal void SetRegister(Register register, byte data)
///
/// The size of the data should be 2 * cascaded devices.
///
- private void Write(Span data)
- {
- _spiDevice.Write(data);
- }
+ private void Write(Span data) => _spiDevice.Write(data);
///
/// Sets the brightness of all cascaded devices to the same intensity level.
@@ -187,10 +179,7 @@ private void ValidateIndex(int index, out int deviceId, out int digit)
///
/// Writes all the Values to the devices.
///
- public void Flush()
- {
- WriteBuffer(_buffer);
- }
+ public void Flush() => WriteBuffer(_buffer);
///
/// Writes a two dimensional buffer containing all the values to the devices.
@@ -375,19 +364,13 @@ public void Clear(int start, int end, bool flush = true)
///
/// Clears the buffer from the given start to end and flushes
///
- public void ClearAll(bool flush = true)
- {
- Clear(0, CascadedDevices, flush);
- }
+ public void ClearAll(bool flush = true) => Clear(0, CascadedDevices, flush);
///
public void Dispose()
{
- if (_spiDevice != null)
- {
- _spiDevice.Dispose();
- _spiDevice = null!;
- }
+ _spiDevice?.Dispose();
+ _spiDevice = null!;
}
}
}
diff --git a/src/devices/Max7219/samples/Program.cs b/src/devices/Max7219/samples/Program.cs
index 372341129e..41e0348d05 100644
--- a/src/devices/Max7219/samples/Program.cs
+++ b/src/devices/Max7219/samples/Program.cs
@@ -6,9 +6,9 @@
using System.Threading;
using Iot.Device.Max7219;
-var message = "Hello World from MAX7219!";
+string message = "Hello World from MAX7219!";
-if (args.Length > 0)
+if (args is { Length: > 0 })
{
message = string.Join(" ", args);
}
@@ -21,7 +21,7 @@
Mode = Iot.Device.Max7219.Max7219.SpiMode
};
using SpiDevice spi = SpiDevice.Create(connectionSettings);
-using Max7219 devices = new Max7219(spi, cascadedDevices: 4);
+using Max7219 devices = new (spi, cascadedDevices: 4);
// initialize the devices
devices.Init();
@@ -62,7 +62,7 @@
// reinitialize device and show message using the matrix graphics
devices.Init();
devices.Rotation = RotationType.Right;
-var graphics = new MatrixGraphics(devices, Fonts.Default);
+MatrixGraphics graphics = new (devices, Fonts.Default);
foreach (var font in new[]
{
Fonts.CP437, Fonts.LCD, Fonts.Sinclair, Fonts.Tiny, Fonts.CyrillicUkrainian
@@ -72,14 +72,11 @@
graphics.ShowMessage(message, alwaysScroll: true);
}
-RotationType? ReadRotation(char c)
+RotationType? ReadRotation(char c) => c switch
{
- switch (c)
- {
- case 'l': return RotationType.Left;
- case 'r': return RotationType.Right;
- case 'n': return RotationType.None;
- case 'h': return RotationType.Half;
- default: return null;
- }
-}
+ 'l' => RotationType.Left,
+ 'r' => RotationType.Right,
+ 'n' => RotationType.None,
+ 'h' => RotationType.Half,
+ _ => null,
+};
diff --git a/src/devices/Mbi5027/Mbi5027.cs b/src/devices/Mbi5027/Mbi5027.cs
index c3189d8949..fe2854643c 100644
--- a/src/devices/Mbi5027/Mbi5027.cs
+++ b/src/devices/Mbi5027/Mbi5027.cs
@@ -50,7 +50,7 @@ public void EnableDetectionMode()
{
if (GpioController is null || _pinMapping.Clk < 0 || _pinMapping.OE < 0 || _pinMapping.LE < 0 || _pinMapping.Sdo < 0)
{
- throw new ArgumentNullException($"{nameof(EnableDetectionMode)}: GpioController was not provided or {nameof(_pinMapping.Clk)}, {nameof(_pinMapping.LE)}, {nameof(_pinMapping.OE)}, or {nameof(_pinMapping.Sdo)} not mapped to pin");
+ throw new Exception($"{nameof(EnableDetectionMode)}: GpioController was not provided or {nameof(_pinMapping.Clk)}, {nameof(_pinMapping.LE)}, {nameof(_pinMapping.OE)}, or {nameof(_pinMapping.Sdo)} not mapped to pin");
}
/* Required timing waveform
@@ -78,7 +78,7 @@ public IEnumerable ReadOutputErrorStatus()
{
if (GpioController is null)
{
- throw new Exception($"{nameof(GpioController)} is not cofigured.");
+ throw new Exception($"{nameof(GpioController)} is not configured.");
}
/* Required timing waveform
@@ -151,7 +151,7 @@ public void EnableNormalMode()
{
if (GpioController is null || _pinMapping.Clk < 0 || _pinMapping.OE < 0 || _pinMapping.LE < 0)
{
- throw new ArgumentNullException($"{nameof(EnableDetectionMode)}: GpioController was not provided or {nameof(_pinMapping.Clk)}, {nameof(_pinMapping.LE)}, or {nameof(_pinMapping.OE)} not mapped to pin");
+ throw new Exception($"{nameof(EnableDetectionMode)}: GpioController was not provided or {nameof(_pinMapping.Clk)}, {nameof(_pinMapping.LE)}, or {nameof(_pinMapping.OE)} not mapped to pin");
}
/* Required timing waveform
@@ -176,7 +176,7 @@ private void ChangeModeSignal(PinValue oe, PinValue le)
{
if (GpioController is null || _pinMapping.Clk < 0 || _pinMapping.OE < 0 || _pinMapping.LE < 0 || _pinMapping.Sdo < 0)
{
- throw new ArgumentNullException($"{nameof(EnableDetectionMode)}: GpioController was not provided or {nameof(_pinMapping.Clk)}, {nameof(_pinMapping.LE)}, {nameof(_pinMapping.OE)}, or {nameof(_pinMapping.Sdo)} not mapped to pin");
+ throw new Exception($"{nameof(EnableDetectionMode)}: GpioController was not provided or {nameof(_pinMapping.Clk)}, {nameof(_pinMapping.LE)}, {nameof(_pinMapping.OE)}, or {nameof(_pinMapping.Sdo)} not mapped to pin");
}
GpioController.Write(_pinMapping.OE, oe);
diff --git a/src/devices/Mbi5027/samples/Program.cs b/src/devices/Mbi5027/samples/Program.cs
index bdfcd18754..e495703af2 100644
--- a/src/devices/Mbi5027/samples/Program.cs
+++ b/src/devices/Mbi5027/samples/Program.cs
@@ -7,8 +7,8 @@
using System.Threading;
using Iot.Device.Multiplexing;
-using var sr = new Mbi5027(Mbi5027PinMapping.Complete);
-var cancellationSource = new CancellationTokenSource();
+using Mbi5027 sr = new (Mbi5027PinMapping.Complete);
+CancellationTokenSource cancellationSource = new ();
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
@@ -27,7 +27,7 @@ void BinaryCounter(ShiftRegister sr, CancellationTokenSource cancellationSource)
{
int endValue = 1000;
Console.WriteLine($"Write 0 through {endValue}");
- var delay = 10;
+ int delay = 10;
for (int i = 0; i < endValue; i++)
{
sr.ShiftByte((byte)i);
@@ -46,7 +46,7 @@ void CheckCircuit(Mbi5027 sr)
Console.WriteLine("Checking circuit");
sr.EnableDetectionMode();
- var index = sr.BitLength - 1;
+ int index = sr.BitLength - 1;
foreach (var value in sr.ReadOutputErrorStatus())
{
diff --git a/src/devices/Mcp23xxx/Mcp23x0x.cs b/src/devices/Mcp23xxx/Mcp23x0x.cs
index 7f07476b7f..69128e19a3 100644
--- a/src/devices/Mcp23xxx/Mcp23x0x.cs
+++ b/src/devices/Mcp23xxx/Mcp23x0x.cs
@@ -22,7 +22,7 @@ public abstract class Mcp23x0x : Mcp23xxx
///
/// True to dispose the Gpio Controller
protected Mcp23x0x(BusAdapter device, int reset, int interrupt, GpioController? controller = null, bool shouldDispose = true)
- : base(device, reset, interrupt, controller: controller, shouldDispose: shouldDispose)
+ : base(device, reset, interrupt, gpioController: controller, shouldDispose: shouldDispose)
{
}
diff --git a/src/devices/Mcp23xxx/Mcp23xxx.cs b/src/devices/Mcp23xxx/Mcp23xxx.cs
index ae645c8fd6..316ab24f87 100644
--- a/src/devices/Mcp23xxx/Mcp23xxx.cs
+++ b/src/devices/Mcp23xxx/Mcp23xxx.cs
@@ -38,7 +38,7 @@ public abstract partial class Mcp23xxx : GpioDriver
/// The output pin number that is connected to the hardware reset.
/// The input pin number that is connected to the interrupt for Port A (INTA).
/// The input pin number that is connected to the interrupt for Port B (INTB).
- ///
+ ///
/// The controller for the reset and interrupt pins. If not specified, the default controller will be used.
///
///
@@ -49,11 +49,10 @@ public abstract partial class Mcp23xxx : GpioDriver
///
/// True to dispose the Gpio Controller
protected Mcp23xxx(BusAdapter bus, int reset = -1, int interruptA = -1, int interruptB = -1,
- GpioController? controller = null, BankStyle bankStyle = BankStyle.Sequential, bool shouldDispose = true)
+ GpioController? gpioController = null, BankStyle bankStyle = BankStyle.Sequential, bool shouldDispose = true)
{
_bus = bus;
_bankStyle = bankStyle;
- _shouldDispose = controller == null ? true : shouldDispose;
_reset = reset;
_interruptA = interruptA;
@@ -62,7 +61,8 @@ protected Mcp23xxx(BusAdapter bus, int reset = -1, int interruptA = -1, int inte
// Only need master controller if there are external pins provided.
if (_reset != -1 || _interruptA != -1 || _interruptB != -1)
{
- _controller = controller ?? new GpioController();
+ _shouldDispose = shouldDispose || gpioController is null;
+ _controller = gpioController ?? new GpioController();
if (_interruptA != -1)
{
diff --git a/src/devices/Mcp23xxx/samples/Program.cs b/src/devices/Mcp23xxx/samples/Program.cs
index d9e8158d22..69ca12a6b7 100644
--- a/src/devices/Mcp23xxx/samples/Program.cs
+++ b/src/devices/Mcp23xxx/samples/Program.cs
@@ -13,7 +13,7 @@
Console.WriteLine("Hello Mcp23xxx!");
using Mcp23xxx mcp23xxx = GetMcp23xxxDevice(Mcp23xxxDevice.Mcp23017);
-using GpioController controllerUsingMcp = new GpioController(PinNumberingScheme.Logical, mcp23xxx);
+using GpioController controllerUsingMcp = new (PinNumberingScheme.Logical, mcp23xxx);
// Samples are currently written specifically for the 16 bit variant
if (mcp23xxx is Mcp23x1x mcp23x1x)
{
diff --git a/src/devices/Mcp23xxx/tests/Mcp23xxxTest.cs b/src/devices/Mcp23xxx/tests/Mcp23xxxTest.cs
index 4e0210e86b..4c63e15114 100644
--- a/src/devices/Mcp23xxx/tests/Mcp23xxxTest.cs
+++ b/src/devices/Mcp23xxx/tests/Mcp23xxxTest.cs
@@ -129,8 +129,8 @@ public Mcp23xxxChipMock(int ports, bool isSpi)
public Span Registers => _registers;
// Can't coalesce here https://github.com/dotnet/roslyn/issues/29927
- public ReadOnlySpan LastReadBuffer => _lastReadBuffer == null ? ReadOnlySpan.Empty : _lastReadBuffer;
- public ReadOnlySpan LastWriteBuffer => _lastWriteBuffer == null ? ReadOnlySpan.Empty : _lastWriteBuffer;
+ public ReadOnlySpan LastReadBuffer => _lastReadBuffer is null ? ReadOnlySpan.Empty : _lastReadBuffer;
+ public ReadOnlySpan LastWriteBuffer => _lastWriteBuffer is null ? ReadOnlySpan.Empty : _lastWriteBuffer;
public void Read(Span buffer)
{
diff --git a/src/devices/Mcp25xxx/Mcp25xxx.cs b/src/devices/Mcp25xxx/Mcp25xxx.cs
index 3db3935a8a..cf5e3dee28 100644
--- a/src/devices/Mcp25xxx/Mcp25xxx.cs
+++ b/src/devices/Mcp25xxx/Mcp25xxx.cs
@@ -55,7 +55,7 @@ public Mcp25xxx(
bool shouldDispose = true)
{
_spiDevice = spiDevice;
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
_reset = reset;
_tx0rts = tx0rts;
@@ -271,7 +271,7 @@ public byte[] ReadRxBuffer(RxBufferAddressPointer addressPointer, int byteCount
{
if (byteCount < 1)
{
- throw new ArgumentException($"Invalid number of bytes {byteCount}.", nameof(byteCount));
+ throw new ArgumentException(nameof(byteCount), "Invalid number of bytes.");
}
const int StackThreshold = 31; // Usually won't read more than this at a time.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid0.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid0.cs
index 5232d4f825..5289fb4216 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid0.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid0.cs
@@ -23,7 +23,7 @@ public RxFxEid0(byte rxFilterNumber, byte extendedIdentifier)
{
if (rxFilterNumber > 5)
{
- throw new ArgumentException($"Invalid RX Filter Number value {rxFilterNumber}.", nameof(rxFilterNumber));
+ throw new ArgumentException(nameof(rxFilterNumber), $"Invalid RX Filter Number value {rxFilterNumber}.");
}
RxFilterNumber = rxFilterNumber;
@@ -42,52 +42,32 @@ public RxFxEid0(byte rxFilterNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxFilterNumber switch
{
- switch (RxFilterNumber)
- {
- case 0:
- return Address.RxF0Eid0;
- case 1:
- return Address.RxF1Eid0;
- case 2:
- return Address.RxF2Eid0;
- case 3:
- return Address.RxF3Eid0;
- case 4:
- return Address.RxF4Eid0;
- case 5:
- return Address.RxF5Eid0;
- default:
- throw new ArgumentException($"Invalid Rx Filter Number value {RxFilterNumber}.", nameof(RxFilterNumber));
- }
- }
+ 0 => Address.RxF0Eid0,
+ 1 => Address.RxF1Eid0,
+ 2 => Address.RxF2Eid0,
+ 3 => Address.RxF3Eid0,
+ 4 => Address.RxF4Eid0,
+ 5 => Address.RxF5Eid0,
+ _ => throw new Exception($"Invalid value for {nameof(RxFilterNumber)}: {RxFilterNumber}."),
+ };
///
/// Gets the Rx Filter Number based on the register address.
///
/// The address to look up Rx Filter Number.
/// The Rx Filter Number based on the register address.
- public static byte GetRxFilterNumber(Address address)
+ public static byte GetRxFilterNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxF0Eid0:
- return 0;
- case Address.RxF1Eid0:
- return 1;
- case Address.RxF2Eid0:
- return 2;
- case Address.RxF3Eid0:
- return 3;
- case Address.RxF4Eid0:
- return 4;
- case Address.RxF5Eid0:
- return 5;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxF0Eid0 => 0,
+ Address.RxF1Eid0 => 1,
+ Address.RxF2Eid0 => 2,
+ Address.RxF3Eid0 => 3,
+ Address.RxF4Eid0 => 4,
+ Address.RxF5Eid0 => 5,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid8.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid8.cs
index 5bbe0b1fc0..5bfb4ecec2 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid8.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxEid8.cs
@@ -23,7 +23,7 @@ public RxFxEid8(byte rxFilterNumber, byte extendedIdentifier)
{
if (rxFilterNumber > 5)
{
- throw new ArgumentException($"Invalid RX Filter Number value {rxFilterNumber}.", nameof(rxFilterNumber));
+ throw new ArgumentException(nameof(rxFilterNumber), $"Invalid RX Filter Number value {rxFilterNumber}.");
}
RxFilterNumber = rxFilterNumber;
@@ -42,52 +42,32 @@ public RxFxEid8(byte rxFilterNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxFilterNumber switch
{
- switch (RxFilterNumber)
- {
- case 0:
- return Address.RxF0Eid8;
- case 1:
- return Address.RxF1Eid8;
- case 2:
- return Address.RxF2Eid8;
- case 3:
- return Address.RxF3Eid8;
- case 4:
- return Address.RxF4Eid8;
- case 5:
- return Address.RxF5Eid8;
- default:
- throw new ArgumentException($"Invalid Rx Filter Number value {RxFilterNumber}.", nameof(RxFilterNumber));
- }
- }
+ 0 => Address.RxF0Eid8,
+ 1 => Address.RxF1Eid8,
+ 2 => Address.RxF2Eid8,
+ 3 => Address.RxF3Eid8,
+ 4 => Address.RxF4Eid8,
+ 5 => Address.RxF5Eid8,
+ _ => throw new Exception($"Invalid value for {nameof(RxFilterNumber)}: {RxFilterNumber}."),
+ };
///
/// Gets the Rx Filter Number based on the register address.
///
/// The address to look up Rx Filter Number.
/// The Rx Filter Number based on the register address.
- public static byte GetRxFilterNumber(Address address)
+ public static byte GetRxFilterNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxF0Eid8:
- return 0;
- case Address.RxF1Eid8:
- return 1;
- case Address.RxF2Eid8:
- return 2;
- case Address.RxF3Eid8:
- return 3;
- case Address.RxF4Eid8:
- return 4;
- case Address.RxF5Eid8:
- return 5;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxF0Eid8 => 0,
+ Address.RxF1Eid8 => 1,
+ Address.RxF2Eid8 => 2,
+ Address.RxF3Eid8 => 3,
+ Address.RxF4Eid8 => 4,
+ Address.RxF5Eid8 => 5,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidh.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidh.cs
index e143efdc37..20b4347fe8 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidh.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidh.cs
@@ -23,7 +23,7 @@ public RxFxSidh(byte rxFilterNumber, byte standardIdentifierFilter)
{
if (rxFilterNumber > 5)
{
- throw new ArgumentException($"Invalid RX Filter Number value {rxFilterNumber}.", nameof(rxFilterNumber));
+ throw new ArgumentException(nameof(rxFilterNumber), $"Invalid RX Filter Number value {rxFilterNumber}.");
}
RxFilterNumber = rxFilterNumber;
@@ -41,52 +41,32 @@ public RxFxSidh(byte rxFilterNumber, byte standardIdentifierFilter)
///
public byte StandardIdentifierFilter { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxFilterNumber switch
{
- switch (RxFilterNumber)
- {
- case 0:
- return Address.RxF0Sidh;
- case 1:
- return Address.RxF1Sidh;
- case 2:
- return Address.RxF2Sidh;
- case 3:
- return Address.RxF3Sidh;
- case 4:
- return Address.RxF4Sidh;
- case 5:
- return Address.RxF5Sidh;
- default:
- throw new ArgumentException($"Invalid Rx Filter Number value {RxFilterNumber}.", nameof(RxFilterNumber));
- }
- }
+ 0 => Address.RxF0Sidh,
+ 1 => Address.RxF1Sidh,
+ 2 => Address.RxF2Sidh,
+ 3 => Address.RxF3Sidh,
+ 4 => Address.RxF4Sidh,
+ 5 => Address.RxF5Sidh,
+ _ => throw new Exception($"Invalid value for {nameof(RxFilterNumber)}: {RxFilterNumber}."),
+ };
///
/// Gets the Rx Filter Number based on the register address.
///
/// The address to up look Rx Filter Number.
/// The Rx Filter Number based on the register address.
- public static byte GetRxFilterNumber(Address address)
+ public static byte GetRxFilterNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxF0Sidh:
- return 0;
- case Address.RxF1Sidh:
- return 1;
- case Address.RxF2Sidh:
- return 2;
- case Address.RxF3Sidh:
- return 3;
- case Address.RxF4Sidh:
- return 4;
- case Address.RxF5Sidh:
- return 5;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxF0Sidh => 0,
+ Address.RxF1Sidh => 1,
+ Address.RxF2Sidh => 2,
+ Address.RxF3Sidh => 3,
+ Address.RxF4Sidh => 4,
+ Address.RxF5Sidh => 5,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidl.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidl.cs
index 70a03520cd..68ce60c525 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidl.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxFxSidl.cs
@@ -31,17 +31,17 @@ public RxFxSidl(byte rxFilterNumber, byte extendedIdentifierFilter, bool extende
{
if (rxFilterNumber > 5)
{
- throw new ArgumentException($"Invalid RX Filter Number value {rxFilterNumber}.", nameof(rxFilterNumber));
+ throw new ArgumentException(nameof(rxFilterNumber), $"Invalid RX Filter Number value {rxFilterNumber}.");
}
if (extendedIdentifierFilter > 3)
{
- throw new ArgumentException($"Invalid EID value {extendedIdentifierFilter}.", nameof(extendedIdentifierFilter));
+ throw new ArgumentException(nameof(extendedIdentifierFilter), $"Invalid EID value {extendedIdentifierFilter}.");
}
if (standardIdentifierFilter > 7)
{
- throw new ArgumentException($"Invalid SID value {standardIdentifierFilter}.", nameof(standardIdentifierFilter));
+ throw new ArgumentException(nameof(standardIdentifierFilter), $"Invalid SID value {standardIdentifierFilter}.");
}
RxFilterNumber = rxFilterNumber;
@@ -59,7 +59,7 @@ public RxFxSidl(byte rxFilterNumber, byte value)
{
if (rxFilterNumber > 5)
{
- throw new ArgumentException($"Invalid RX Filter Number value {rxFilterNumber}.", nameof(rxFilterNumber));
+ throw new ArgumentException(nameof(rxFilterNumber), $"Invalid RX Filter Number value {rxFilterNumber}.");
}
RxFilterNumber = rxFilterNumber;
@@ -92,52 +92,32 @@ public RxFxSidl(byte rxFilterNumber, byte value)
///
public byte StandardIdentifierFilter { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxFilterNumber switch
{
- switch (RxFilterNumber)
- {
- case 0:
- return Address.RxF0Sidl;
- case 1:
- return Address.RxF1Sidl;
- case 2:
- return Address.RxF2Sidl;
- case 3:
- return Address.RxF3Sidl;
- case 4:
- return Address.RxF4Sidl;
- case 5:
- return Address.RxF5Sidl;
- default:
- throw new ArgumentException($"Invalid Rx Filter Number value {RxFilterNumber}.", nameof(RxFilterNumber));
- }
- }
+ 0 => Address.RxF0Sidl,
+ 1 => Address.RxF1Sidl,
+ 2 => Address.RxF2Sidl,
+ 3 => Address.RxF3Sidl,
+ 4 => Address.RxF4Sidl,
+ 5 => Address.RxF5Sidl,
+ _ => throw new Exception($"Invalid value for {nameof(RxFilterNumber)}: {RxFilterNumber}."),
+ };
///
/// Gets the Rx Filter Number based on the register address.
///
/// The address to look up Rx Filter Number.
/// The Rx Filter Number based on the register address.
- public static byte GetRxFilterNumber(Address address)
+ public static byte GetRxFilterNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxF0Sidl:
- return 0;
- case Address.RxF1Sidl:
- return 1;
- case Address.RxF2Sidl:
- return 2;
- case Address.RxF3Sidl:
- return 3;
- case Address.RxF4Sidl:
- return 4;
- case Address.RxF5Sidl:
- return 5;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxF0Sidl => 0,
+ Address.RxF1Sidl => 1,
+ Address.RxF2Sidl => 2,
+ Address.RxF3Sidl => 3,
+ Address.RxF4Sidl => 4,
+ Address.RxF5Sidl => 5,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid0.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid0.cs
index 90d7f6a4c7..390c6d9caf 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid0.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid0.cs
@@ -23,7 +23,7 @@ public RxMxEid0(byte rxMaskNumber, byte extendedIdentifierMask)
{
if (rxMaskNumber > 1)
{
- throw new ArgumentException($"Invalid RX Mask Number value {rxMaskNumber}.", nameof(rxMaskNumber));
+ throw new ArgumentException(nameof(rxMaskNumber), $"Invalid RX Mask Number value {rxMaskNumber}.");
}
RxMaskNumber = rxMaskNumber;
@@ -42,36 +42,24 @@ public RxMxEid0(byte rxMaskNumber, byte extendedIdentifierMask)
///
public byte ExtendedIdentifierMask { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxMaskNumber switch
{
- switch (RxMaskNumber)
- {
- case 0:
- return Address.RxM0Eid0;
- case 1:
- return Address.RxM1Eid0;
- default:
- throw new ArgumentException($"Invalid Rx Mask Number value {RxMaskNumber}.", nameof(RxMaskNumber));
- }
- }
+ 0 => Address.RxM0Eid0,
+ 1 => Address.RxM1Eid0,
+ _ => throw new Exception($"Invalid value for {nameof(RxMaskNumber)}: {RxMaskNumber}."),
+ };
///
/// Gets the Rx Mask Number based on the register address.
///
/// The address to look up Rx Mask Number.
/// The Rx Mask Number based on the register address.
- public static byte GetRxMaskNumber(Address address)
+ public static byte GetRxMaskNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxM0Eid0:
- return 0;
- case Address.RxM1Eid0:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxM0Eid0 => 0,
+ Address.RxM1Eid0 => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid8.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid8.cs
index 322b437ec3..6192bbf3c5 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid8.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxEid8.cs
@@ -23,7 +23,7 @@ public RxMxEid8(byte rxMaskNumber, byte extendedIdentifier)
{
if (rxMaskNumber > 1)
{
- throw new ArgumentException($"Invalid RX Mask Number value {rxMaskNumber}.", nameof(rxMaskNumber));
+ throw new ArgumentException(nameof(rxMaskNumber), $"Invalid RX Mask Number value {rxMaskNumber}.");
}
RxMaskNumber = rxMaskNumber;
@@ -42,36 +42,24 @@ public RxMxEid8(byte rxMaskNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxMaskNumber switch
{
- switch (RxMaskNumber)
- {
- case 0:
- return Address.RxM0Eid8;
- case 1:
- return Address.RxM1Eid8;
- default:
- throw new ArgumentException($"Invalid Rx Mask Number value {RxMaskNumber}.", nameof(RxMaskNumber));
- }
- }
+ 0 => Address.RxM0Eid8,
+ 1 => Address.RxM1Eid8,
+ _ => throw new Exception($"Invalid value for {nameof(RxMaskNumber)}: {RxMaskNumber}."),
+ };
///
/// Gets the Rx Mask Number based on the register address.
///
/// The address to look up Rx Mask Number.
/// The Rx Mask Number based on the register address.
- public static byte GetRxMaskNumber(Address address)
+ public static byte GetRxMaskNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxM0Eid8:
- return 0;
- case Address.RxM1Eid8:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxM0Eid8 => 0,
+ Address.RxM1Eid8 => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidh.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidh.cs
index 226968b400..b24a9ec865 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidh.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidh.cs
@@ -22,7 +22,7 @@ public RxMxSidh(byte rxMaskNumber, byte standardIdentifierMask)
{
if (rxMaskNumber > 1)
{
- throw new ArgumentException($"Invalid RX Mask Number value {rxMaskNumber}.", nameof(rxMaskNumber));
+ throw new ArgumentException(nameof(rxMaskNumber), $"Invalid RX Mask Number value {rxMaskNumber}.");
}
RxMaskNumber = rxMaskNumber;
@@ -40,36 +40,24 @@ public RxMxSidh(byte rxMaskNumber, byte standardIdentifierMask)
///
public byte StandardIdentifierMask { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxMaskNumber switch
{
- switch (RxMaskNumber)
- {
- case 0:
- return Address.RxM0Sidh;
- case 1:
- return Address.RxM1Sidh;
- default:
- throw new ArgumentException($"Invalid Rx Mask Number value {RxMaskNumber}.", nameof(RxMaskNumber));
- }
- }
+ 0 => Address.RxM0Sidh,
+ 1 => Address.RxM1Sidh,
+ _ => throw new Exception($"Invalid value for {nameof(RxMaskNumber)}: {RxMaskNumber}."),
+ };
///
/// Gets the Rx Mask Number based on the register address.
///
/// The address to look up Rx Mask Number.
/// The Rx Mask Number based on the register address.
- public static byte GetRxMaskNumber(Address address)
+ public static byte GetRxMaskNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxM0Sidh:
- return 0;
- case Address.RxM1Sidh:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxM0Sidh => 0,
+ Address.RxM1Sidh => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidl.cs b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidl.cs
index 7f47467d7f..9345de508e 100644
--- a/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidl.cs
+++ b/src/devices/Mcp25xxx/Register/AcceptanceFilter/RxMxSidl.cs
@@ -26,17 +26,17 @@ public RxMxSidl(byte rxMaskNumber, byte extendedIdentifierMask, byte standardIde
{
if (rxMaskNumber > 1)
{
- throw new ArgumentException($"Invalid RX Mask Number value {rxMaskNumber}.", nameof(rxMaskNumber));
+ throw new ArgumentException(nameof(rxMaskNumber), $"Invalid RX Mask Number value {rxMaskNumber}.");
}
if (extendedIdentifierMask > 3)
{
- throw new ArgumentException($"Invalid EID value {extendedIdentifierMask}.", nameof(extendedIdentifierMask));
+ throw new ArgumentException(nameof(extendedIdentifierMask), $"Invalid EID value {extendedIdentifierMask}.");
}
if (standardIdentifierMask > 7)
{
- throw new ArgumentException($"Invalid SID value {standardIdentifierMask}.", nameof(standardIdentifierMask));
+ throw new ArgumentException(nameof(standardIdentifierMask), $"Invalid SID value {standardIdentifierMask}.");
}
RxMaskNumber = rxMaskNumber;
@@ -53,7 +53,7 @@ public RxMxSidl(byte rxMaskNumber, byte value)
{
if (rxMaskNumber > 1)
{
- throw new ArgumentException($"Invalid RX Mask Number value {rxMaskNumber}.", nameof(rxMaskNumber));
+ throw new ArgumentException(nameof(rxMaskNumber), $"Invalid RX Mask Number value {rxMaskNumber}.");
}
RxMaskNumber = rxMaskNumber;
@@ -78,36 +78,24 @@ public RxMxSidl(byte rxMaskNumber, byte value)
///
public byte StandardIdentifierMask { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxMaskNumber switch
{
- switch (RxMaskNumber)
- {
- case 0:
- return Address.RxM0Sidl;
- case 1:
- return Address.RxM1Sidl;
- default:
- throw new ArgumentException($"Invalid Rx Mask Number value {RxMaskNumber}.", nameof(RxMaskNumber));
- }
- }
+ 0 => Address.RxM0Sidl,
+ 1 => Address.RxM1Sidl,
+ _ => throw new Exception($"Invalid value for {nameof(RxMaskNumber)}: {RxMaskNumber}."),
+ };
///
/// Gets the Rx Mask Number based on the register address.
///
/// The address to look up Rx Mask Number.
/// The Rx Mask Number based on the register address.
- public static byte GetRxMaskNumber(Address address)
+ public static byte GetRxMaskNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxM0Sidl:
- return 0;
- case Address.RxM1Sidl:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxM0Sidl => 0,
+ Address.RxM1Sidl => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf1.cs b/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf1.cs
index d3f727f3dd..989407a29f 100644
--- a/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf1.cs
+++ b/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf1.cs
@@ -24,7 +24,7 @@ public Cnf1(byte baudRatePrescaler, JumpWidthLength synchronizationJumpWidthLeng
{
if (baudRatePrescaler > 0b0011_1111)
{
- throw new ArgumentException($"Invalid BRP value {baudRatePrescaler}.", nameof(baudRatePrescaler));
+ throw new ArgumentException(nameof(baudRatePrescaler), $"Invalid BRP value {baudRatePrescaler}.");
}
BaudRatePrescaler = baudRatePrescaler;
diff --git a/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf2.cs b/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf2.cs
index 3706f6fa2c..0ff4347495 100644
--- a/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf2.cs
+++ b/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf2.cs
@@ -29,12 +29,12 @@ public Cnf2(byte propagationSegmentLength, byte ps1Length, bool samplePointConfi
{
if (propagationSegmentLength > 0b0000_0111)
{
- throw new ArgumentException($"Invalid PRSEG value {propagationSegmentLength}.", nameof(propagationSegmentLength));
+ throw new ArgumentException(nameof(propagationSegmentLength), $"Invalid PRSEG value {propagationSegmentLength}.");
}
if (ps1Length > 0b0000_0111)
{
- throw new ArgumentException($"Invalid PHSEG1 value {ps1Length}.", nameof(ps1Length));
+ throw new ArgumentException(nameof(ps1Length), $"Invalid PHSEG1 value {ps1Length}.");
}
PropagationSegmentLength = propagationSegmentLength;
diff --git a/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf3.cs b/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf3.cs
index 05a93ac6b9..020a719932 100644
--- a/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf3.cs
+++ b/src/devices/Mcp25xxx/Register/BitTimeConfiguration/Cnf3.cs
@@ -35,7 +35,7 @@ public Cnf3(byte ps2Length, bool wakeUpFilter, bool startOfFrameSignal)
{
if (ps2Length > 0b0000_0111)
{
- throw new ArgumentException($"Invalid PHSEG2 value {ps2Length}.", nameof(ps2Length));
+ throw new ArgumentException(nameof(ps2Length), $"Invalid PHSEG2 value {ps2Length}.");
}
Ps2Length = ps2Length;
diff --git a/src/devices/Mcp25xxx/Register/ErrorDetection/Rec.cs b/src/devices/Mcp25xxx/Register/ErrorDetection/Rec.cs
index b25a830bd3..bd08d92f0f 100644
--- a/src/devices/Mcp25xxx/Register/ErrorDetection/Rec.cs
+++ b/src/devices/Mcp25xxx/Register/ErrorDetection/Rec.cs
@@ -32,9 +32,6 @@ public Rec(byte receiveErrorCount)
/// Converts register contents to a byte.
///
/// The byte that represent the register contents.
- public byte ToByte()
- {
- return ReceiveErrorCount;
- }
+ public byte ToByte() => ReceiveErrorCount;
}
}
diff --git a/src/devices/Mcp25xxx/Register/ErrorDetection/Tec.cs b/src/devices/Mcp25xxx/Register/ErrorDetection/Tec.cs
index 6f0670f077..54030b92ff 100644
--- a/src/devices/Mcp25xxx/Register/ErrorDetection/Tec.cs
+++ b/src/devices/Mcp25xxx/Register/ErrorDetection/Tec.cs
@@ -32,9 +32,6 @@ public Tec(byte transmitErrorCount)
/// Converts register contents to a byte.
///
/// The byte that represent the register contents.
- public byte ToByte()
- {
- return TransmitErrorCount;
- }
+ public byte ToByte() => TransmitErrorCount;
}
}
diff --git a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDlc.cs b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDlc.cs
index f667111321..52bf3f5e52 100644
--- a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDlc.cs
+++ b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDlc.cs
@@ -28,7 +28,7 @@ public RxBxDlc(byte rxBufferNumber, byte dataLengthCode, bool extendedFrameRemot
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
RxBufferNumber = rxBufferNumber;
@@ -45,7 +45,7 @@ public RxBxDlc(byte rxBufferNumber, byte value)
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
RxBufferNumber = rxBufferNumber;
@@ -72,36 +72,24 @@ public RxBxDlc(byte rxBufferNumber, byte value)
///
public bool ExtendedFrameRemoteTransmissionRequest { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxBufferNumber switch
{
- switch (RxBufferNumber)
- {
- case 0:
- return Address.RxB0Dlc;
- case 1:
- return Address.RxB1Dlc;
- default:
- throw new ArgumentException($"Invalid Rx Buffer Number value {RxBufferNumber}.", nameof(RxBufferNumber));
- }
- }
+ 0 => Address.RxB0Dlc,
+ 1 => Address.RxB1Dlc,
+ _ => throw new Exception($"Invalid value for {nameof(RxBufferNumber)}: {RxBufferNumber}."),
+ };
///
/// Gets the Rx Buffer Number based on the register address.
///
/// The address to look up Rx Buffer Number.
/// The Rx Buffer Number based on the register address.
- public static byte GetRxBufferNumber(Address address)
+ public static byte GetRxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxB0Dlc:
- return 0;
- case Address.RxB1Dlc:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxB0Dlc => 0,
+ Address.RxB1Dlc => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid address value {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDn.cs b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDn.cs
index 525fd1f0b5..68c9ca6407 100644
--- a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDn.cs
+++ b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxDn.cs
@@ -20,12 +20,12 @@ public RxBxDn(byte rxBufferNumber, byte index, byte receiveBufferDataFieldBytes)
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
if (index > 7)
{
- throw new ArgumentException($"Invalid Index value {index}.", nameof(index));
+ throw new ArgumentException(nameof(index), $"Invalid Index value {index}.");
}
RxBufferNumber = rxBufferNumber;
@@ -48,37 +48,24 @@ public RxBxDn(byte rxBufferNumber, byte index, byte receiveBufferDataFieldBytes)
///
public byte ReceiveBufferDataFieldBytes { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxBufferNumber switch
{
- switch (RxBufferNumber)
- {
- case 0:
- return (Address)((byte)Address.RxB0D0 + Index);
- case 1:
- return (Address)((byte)Address.RxB1D0 + Index);
- default:
- throw new ArgumentException($"Invalid Rx Bufferer Number value {RxBufferNumber}.", nameof(RxBufferNumber));
- }
- }
+ 0 => (Address)((byte)Address.RxB0D0 + Index),
+ 1 => (Address)((byte)Address.RxB1D0 + Index),
+ _ => throw new Exception($"Invalid value for {nameof(RxBufferNumber)}: {RxBufferNumber}."),
+ };
///
/// Gets the Rx Buffer Number based on the register address.
///
/// The address to look up Rx Buffer Number.
/// The Rx Buffer Number based on the register address.
- public static byte GetRxBufferNumber(Address address)
+ public static byte GetRxBufferNumber(Address address) => address switch
{
- if (address >= Address.RxB0D0 && address <= Address.RxB0D7)
- {
- return 0;
- }
- else if (address >= Address.RxB1D0 && address <= Address.RxB1D7)
- {
- return 1;
- }
-
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
+ >= Address.RxB0D0 and <= Address.RxB0D7 => 0,
+ >= Address.RxB1D0 and <= Address.RxB1D7 => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid address value {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid0.cs b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid0.cs
index 053516d985..3f17791beb 100644
--- a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid0.cs
+++ b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid0.cs
@@ -22,7 +22,7 @@ public RxBxEid0(byte rxBufferNumber, byte extendedIdentifier)
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
RxBufferNumber = rxBufferNumber;
@@ -40,36 +40,24 @@ public RxBxEid0(byte rxBufferNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxBufferNumber switch
{
- switch (RxBufferNumber)
- {
- case 0:
- return Address.RxB0Eid0;
- case 1:
- return Address.RxB1Eid0;
- default:
- throw new ArgumentException($"Invalid Rx Buffer Number value {RxBufferNumber}.", nameof(RxBufferNumber));
- }
- }
+ 0 => Address.RxB0Eid0,
+ 1 => Address.RxB1Eid0,
+ _ => throw new Exception($"Invalid value for {nameof(RxBufferNumber)}: {RxBufferNumber}."),
+ };
///
/// Gets the Rx Buffer Number based on the register address.
///
/// The address to look up Rx Buffer Number.
/// The Rx Buffer Number based on the register address.
- public static byte GetRxBufferNumber(Address address)
+ public static byte GetRxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxB0Eid0:
- return 0;
- case Address.RxB1Eid0:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxB0Eid0 => 0,
+ Address.RxB1Eid0 => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid8.cs b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid8.cs
index 7a09ddb6fb..5d9d6de365 100644
--- a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid8.cs
+++ b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxEid8.cs
@@ -22,7 +22,7 @@ public RxBxEid8(byte rxBufferNumber, byte extendedIdentifier)
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
RxBufferNumber = rxBufferNumber;
@@ -40,36 +40,24 @@ public RxBxEid8(byte rxBufferNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxBufferNumber switch
{
- switch (RxBufferNumber)
- {
- case 0:
- return Address.RxB0Eid8;
- case 1:
- return Address.RxB1Eid8;
- default:
- throw new ArgumentException($"Invalid Rx Buffer Number value {RxBufferNumber}.", nameof(RxBufferNumber));
- }
- }
+ 0 => Address.RxB0Eid8,
+ 1 => Address.RxB1Eid8,
+ _ => throw new Exception($"Invalid value for {nameof(RxBufferNumber)}: {RxBufferNumber}."),
+ };
///
/// Gets the Rx Buffer Number based on the register address.
///
/// The address to look up Rx Buffer Number.
/// The Rx Buffer Number based on the register address.
- public static byte GetRxBufferNumber(Address address)
+ public static byte GetRxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxB0Eid8:
- return 0;
- case Address.RxB1Eid8:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxB0Eid8 => 0,
+ Address.RxB1Eid8 => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid address value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidh.cs b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidh.cs
index 519615ce44..aa0de06671 100644
--- a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidh.cs
+++ b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidh.cs
@@ -22,7 +22,7 @@ public RxBxSidh(byte rxBufferNumber, byte standardIdentifier)
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
RxBufferNumber = rxBufferNumber;
@@ -40,36 +40,24 @@ public RxBxSidh(byte rxBufferNumber, byte standardIdentifier)
///
public byte StandardIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxBufferNumber switch
{
- switch (RxBufferNumber)
- {
- case 0:
- return Address.RxB0Sidh;
- case 1:
- return Address.RxB1Sidh;
- default:
- throw new ArgumentException($"Invalid Rx Buffer Number value {RxBufferNumber}.", nameof(RxBufferNumber));
- }
- }
+ 0 => Address.RxB0Sidh,
+ 1 => Address.RxB1Sidh,
+ _ => throw new Exception($"Invalid value for {nameof(RxBufferNumber)}: {RxBufferNumber}."),
+ };
///
/// Gets the Rx Buffer Number based on the register address.
///
/// The address to up look Rx Buffer Number.
/// The Rx Buffer Number based on the register address.
- public static byte GetRxBufferNumber(Address address)
+ public static byte GetRxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxB0Sidh:
- return 0;
- case Address.RxB1Sidh:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxB0Sidh => 0,
+ Address.RxB1Sidh => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidl.cs b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidl.cs
index 7659c25873..1c1d58a327 100644
--- a/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidl.cs
+++ b/src/devices/Mcp25xxx/Register/MessageReceive/RxBxSidl.cs
@@ -42,17 +42,17 @@ public RxBxSidl(
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
if (extendedIdentifier > 3)
{
- throw new ArgumentException($"Invalid EID value {extendedIdentifier}.", nameof(extendedIdentifier));
+ throw new ArgumentException(nameof(extendedIdentifier), $"Invalid EID value {extendedIdentifier}.");
}
if (standardIdentifier > 7)
{
- throw new ArgumentException($"Invalid SID value {standardIdentifier}.", nameof(standardIdentifier));
+ throw new ArgumentException(nameof(standardIdentifier), $"Invalid SID value {standardIdentifier}.");
}
RxBufferNumber = rxBufferNumber;
@@ -71,7 +71,7 @@ public RxBxSidl(byte rxBufferNumber, byte value)
{
if (rxBufferNumber > 1)
{
- throw new ArgumentException($"Invalid RX Buffer Number value {rxBufferNumber}.", nameof(rxBufferNumber));
+ throw new ArgumentException(nameof(rxBufferNumber), $"Invalid RX Buffer Number value {rxBufferNumber}.");
}
RxBufferNumber = rxBufferNumber;
@@ -113,36 +113,24 @@ public RxBxSidl(byte rxBufferNumber, byte value)
///
public byte StandardIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => RxBufferNumber switch
{
- switch (RxBufferNumber)
- {
- case 0:
- return Address.RxB0Sidl;
- case 1:
- return Address.RxB1Sidl;
- default:
- throw new ArgumentException($"Invalid Rx Buffer Number value {RxBufferNumber}.", nameof(RxBufferNumber));
- }
- }
+ 0 => Address.RxB0Sidl,
+ 1 => Address.RxB1Sidl,
+ _ => throw new Exception($"Invalid value for {nameof(RxBufferNumber)}: {RxBufferNumber}."),
+ };
///
/// Gets the Rx Buffer Number based on the register address.
///
/// The address to look up Rx Buffer Number.
/// The Rx Buffer Number based on the register address.
- public static byte GetRxBufferNumber(Address address)
+ public static byte GetRxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.RxB0Sidl:
- return 0;
- case Address.RxB1Sidl:
- return 1;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.RxB0Sidl => 0,
+ Address.RxB1Sidl => 1,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxCtrl.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxCtrl.cs
index 7b4bbbc8d1..b3f15ff988 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxCtrl.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxCtrl.cs
@@ -45,7 +45,7 @@ public TxBxCtrl(
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -65,7 +65,7 @@ public TxBxCtrl(byte txBufferNumber, byte value)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -140,40 +140,26 @@ public enum BufferPriority
///
public bool MessageAbortedFlag { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return Address.TxB0Ctrl;
- case 1:
- return Address.TxB1Ctrl;
- case 2:
- return Address.TxB2Ctrl;
- default:
- throw new ArgumentException($"Invalid Tx Buffer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => Address.TxB0Ctrl,
+ 1 => Address.TxB1Ctrl,
+ 2 => Address.TxB2Ctrl,
+ _ => throw new ArgumentException($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
///
/// The address to look up Tx Buffer Number.
/// The Tx Buffer Number based on the register address.
- public static byte GetTxBufferNumber(Address address)
+ public static byte GetTxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.TxB0Ctrl:
- return 0;
- case Address.TxB1Ctrl:
- return 1;
- case Address.TxB2Ctrl:
- return 2;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.TxB0Ctrl => 0,
+ Address.TxB1Ctrl => 1,
+ Address.TxB2Ctrl => 2,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDlc.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDlc.cs
index e570105562..8b9f28146b 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDlc.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDlc.cs
@@ -27,7 +27,7 @@ public TxBxDlc(byte txBufferNumber, int dataLengthCode, bool remoteTransmissionR
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -44,7 +44,7 @@ public TxBxDlc(byte txBufferNumber, byte value)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -71,40 +71,26 @@ public TxBxDlc(byte txBufferNumber, byte value)
///
public bool RemoteTransmissionRequest { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return Address.TxB0Dlc;
- case 1:
- return Address.TxB1Dlc;
- case 2:
- return Address.TxB2Dlc;
- default:
- throw new ArgumentException($"Invalid Tx Buffer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => Address.TxB0Dlc,
+ 1 => Address.TxB1Dlc,
+ 2 => Address.TxB2Dlc,
+ _ => throw new Exception($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
///
/// The address to look up Tx Buffer Number.
/// The Tx Buffer Number based on the register address.
- public static byte GetTxBufferNumber(Address address)
+ public static byte GetTxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.TxB0Dlc:
- return 0;
- case Address.TxB1Dlc:
- return 1;
- case Address.TxB2Dlc:
- return 2;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.TxB0Dlc => 0,
+ Address.TxB1Dlc => 1,
+ Address.TxB2Dlc => 2,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDn.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDn.cs
index 0efc2a9594..fddd4c81b9 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDn.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxDn.cs
@@ -20,12 +20,12 @@ public TxBxDn(byte txBufferNumber, int index, byte transmitBufferDataFieldBytes)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value: {txBufferNumber}.");
}
if (index > 7)
{
- throw new ArgumentException($"Invalid Index value {index}.", nameof(index));
+ throw new ArgumentException(nameof(index), $"Invalid Index value: {index}.");
}
TxBufferNumber = txBufferNumber;
@@ -48,18 +48,12 @@ public TxBxDn(byte txBufferNumber, int index, byte transmitBufferDataFieldBytes)
///
public byte TransmitBufferDataFieldBytes { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return (Address)((byte)Address.TxB0D0 + Index);
- case 1:
- return (Address)((byte)Address.TxB1D0 + Index);
- default:
- throw new ArgumentException($"Invalid Tx Bufferer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => (Address)((byte)Address.TxB0D0 + Index),
+ 1 => (Address)((byte)Address.TxB1D0 + Index),
+ _ => throw new Exception($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid0.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid0.cs
index 5159427428..15fad90962 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid0.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid0.cs
@@ -22,7 +22,7 @@ public TxBxEid0(byte txBufferNumber, byte extendedIdentifier)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -40,40 +40,26 @@ public TxBxEid0(byte txBufferNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return Address.TxB0Eid0;
- case 1:
- return Address.TxB1Eid0;
- case 2:
- return Address.TxB2Eid0;
- default:
- throw new ArgumentException($"Invalid Tx Buffer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => Address.TxB0Eid0,
+ 1 => Address.TxB1Eid0,
+ 2 => Address.TxB2Eid0,
+ _ => throw new Exception($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
///
/// The address to look up Tx Buffer Number.
/// The Tx Buffer Number based on the register address.
- public static byte GetTxBufferNumber(Address address)
+ public static byte GetTxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.TxB0Eid0:
- return 0;
- case Address.TxB1Eid0:
- return 1;
- case Address.TxB2Eid0:
- return 2;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.TxB0Eid0 => 0,
+ Address.TxB1Eid0 => 1,
+ Address.TxB2Eid0 => 2,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid8.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid8.cs
index 066984beff..4b2c7b9474 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid8.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxEid8.cs
@@ -22,7 +22,7 @@ public TxBxEid8(byte txBufferNumber, byte extendedIdentifier)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -40,40 +40,26 @@ public TxBxEid8(byte txBufferNumber, byte extendedIdentifier)
///
public byte ExtendedIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return Address.TxB0Eid8;
- case 1:
- return Address.TxB1Eid8;
- case 2:
- return Address.TxB2Eid8;
- default:
- throw new ArgumentException($"Invalid Tx Buffer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => Address.TxB0Eid8,
+ 1 => Address.TxB1Eid8,
+ 2 => Address.TxB2Eid8,
+ _ => throw new Exception($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
///
/// The address to look up Tx Buffer Number.
/// The Tx Buffer Number based on the register address.
- public static byte GetTxBufferNumber(Address address)
+ public static byte GetTxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.TxB0Eid8:
- return 0;
- case Address.TxB1Eid8:
- return 1;
- case Address.TxB2Eid8:
- return 2;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.TxB0Eid8 => 0,
+ Address.TxB1Eid8 => 1,
+ Address.TxB2Eid8 => 2,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidh.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidh.cs
index cee7f93398..b7173d80f7 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidh.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidh.cs
@@ -22,7 +22,7 @@ public TxBxSidh(byte txBufferNumber, byte standardIdentifier)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -40,40 +40,26 @@ public TxBxSidh(byte txBufferNumber, byte standardIdentifier)
///
public byte StandardIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return Address.TxB0Sidh;
- case 1:
- return Address.TxB1Sidh;
- case 2:
- return Address.TxB2Sidh;
- default:
- throw new ArgumentException($"Invalid Tx Buffer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => Address.TxB0Sidh,
+ 1 => Address.TxB1Sidh,
+ 2 => Address.TxB2Sidh,
+ _ => throw new Exception($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
///
/// The address to look up Tx Buffer Number.
/// The Tx Buffer Number based on the register address.
- public static byte GetTxBufferNumber(Address address)
+ public static byte GetTxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.TxB0Sidh:
- return 0;
- case Address.TxB1Sidh:
- return 1;
- case Address.TxB2Sidh:
- return 2;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.TxB0Sidh => 0,
+ Address.TxB1Sidh => 1,
+ Address.TxB2Sidh => 2,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidl.cs b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidl.cs
index 0a6dcf22a0..ece89bf0e7 100644
--- a/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidl.cs
+++ b/src/devices/Mcp25xxx/Register/MessageTransmit/TxBxSidl.cs
@@ -31,17 +31,17 @@ public TxBxSidl(byte txBufferNumber, byte extendedIdentifier, bool extendedIdent
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
if (extendedIdentifier > 3)
{
- throw new ArgumentException($"Invalid EID value {extendedIdentifier}.", nameof(extendedIdentifier));
+ throw new ArgumentException(nameof(extendedIdentifier), $"Invalid EID value {extendedIdentifier}.");
}
if (standardIdentifier > 7)
{
- throw new ArgumentException($"Invalid SID value {standardIdentifier}.", nameof(standardIdentifier));
+ throw new ArgumentException(nameof(standardIdentifier), $"Invalid SID value {standardIdentifier}.");
}
TxBufferNumber = txBufferNumber;
@@ -59,7 +59,7 @@ public TxBxSidl(byte txBufferNumber, byte value)
{
if (txBufferNumber > 2)
{
- throw new ArgumentException($"Invalid TX Buffer Number value {txBufferNumber}.", nameof(txBufferNumber));
+ throw new ArgumentException(nameof(txBufferNumber), $"Invalid TX Buffer Number value {txBufferNumber}.");
}
TxBufferNumber = txBufferNumber;
@@ -92,40 +92,26 @@ public TxBxSidl(byte txBufferNumber, byte value)
///
public byte StandardIdentifier { get; }
- private Address GetAddress()
+ private Address GetAddress() => TxBufferNumber switch
{
- switch (TxBufferNumber)
- {
- case 0:
- return Address.TxB0Sidl;
- case 1:
- return Address.TxB1Sidl;
- case 2:
- return Address.TxB2Sidl;
- default:
- throw new ArgumentException($"Invalid Tx Buffer Number value {TxBufferNumber}.", nameof(TxBufferNumber));
- }
- }
+ 0 => Address.TxB0Sidl,
+ 1 => Address.TxB1Sidl,
+ 2 => Address.TxB2Sidl,
+ _ => throw new Exception($"Invalid value for {nameof(TxBufferNumber)}: {TxBufferNumber}."),
+ };
///
/// Gets the Tx Buffer Number based on the register address.
///
/// The address to look up Tx Buffer Number.
/// The Tx Buffer Number based on the register address.
- public static byte GetTxBufferNumber(Address address)
+ public static byte GetTxBufferNumber(Address address) => address switch
{
- switch (address)
- {
- case Address.TxB0Sidl:
- return 0;
- case Address.TxB1Sidl:
- return 1;
- case Address.TxB2Sidl:
- return 2;
- default:
- throw new ArgumentException($"Invalid address value {address}.", nameof(address));
- }
- }
+ Address.TxB0Sidl => 0,
+ Address.TxB1Sidl => 1,
+ Address.TxB2Sidl => 2,
+ _ => throw new ArgumentException(nameof(address), $"Invalid value: {address}."),
+ };
///
/// Gets the address of the register.
diff --git a/src/devices/Mcp25xxx/tests/Mcp25xxx.Tests.csproj b/src/devices/Mcp25xxx/tests/Mcp25xxx.Tests.csproj
index 1c3dcf75eb..4ef65a1bb7 100644
--- a/src/devices/Mcp25xxx/tests/Mcp25xxx.Tests.csproj
+++ b/src/devices/Mcp25xxx/tests/Mcp25xxx.Tests.csproj
@@ -7,13 +7,13 @@
-
all
runtime; build; native; contentfiles; analyzers; buildtransitive
+
diff --git a/src/devices/Mcp3428/Helpers.cs b/src/devices/Mcp3428/Helpers.cs
index 96de3143d3..45127bb0d6 100644
--- a/src/devices/Mcp3428/Helpers.cs
+++ b/src/devices/Mcp3428/Helpers.cs
@@ -13,23 +13,13 @@ internal static class Helpers
/// The resolution.
/// System.Double.
/// res - null
- public static double LSBValue(AdcResolution res)
+ public static double LSBValue(AdcResolution res) => res switch
{
- switch (res)
- {
- case AdcResolution.Bit12:
- return 1e-3;
-
- case AdcResolution.Bit14:
- return 250e-6;
-
- case AdcResolution.Bit16:
- return 62.5e-6;
-
- default:
- throw new ArgumentOutOfRangeException(nameof(res), res, null);
- }
- }
+ AdcResolution.Bit12 => 1e-3,
+ AdcResolution.Bit14 => 250e-6,
+ AdcResolution.Bit16 => 62.5e-6,
+ _ => throw new ArgumentOutOfRangeException(nameof(res), res, null),
+ };
///
/// Gets the divisor to scale raw data based on resolution. = 1/LSB
@@ -37,23 +27,13 @@ public static double LSBValue(AdcResolution res)
/// The resolution.
/// System.UInt16.
/// res - null
- public static ushort LsbDivisor(AdcResolution res)
+ public static ushort LsbDivisor(AdcResolution res) => res switch
{
- switch (res)
- {
- case AdcResolution.Bit12:
- return 1000;
-
- case AdcResolution.Bit14:
- return 4000;
-
- case AdcResolution.Bit16:
- return 16000;
-
- default:
- throw new ArgumentOutOfRangeException(nameof(res), res, null);
- }
- }
+ AdcResolution.Bit12 => 1000,
+ AdcResolution.Bit14 => 4000,
+ AdcResolution.Bit16 => 16000,
+ _ => throw new ArgumentOutOfRangeException(nameof(res), res, null),
+ };
///
/// Determine device I2C address based on the configuration pin states. Based on documentation TABLE 5-3-
@@ -65,47 +45,22 @@ public static byte I2CAddressFromPins(PinState adr0, PinState adr1)
{
byte addr = 0b1101000; // Base value from doc
- var idx = (byte)adr0 << 4 + (byte)adr1;
+ int idx = (byte)adr0 << 4 + (byte)adr1;
- switch (idx)
+ byte addr2 = idx switch
{
- case 0:
- case 0x22:
- break;
-
- case 0x02:
- addr += 1;
- break;
-
- case 0x01:
- addr += 2;
- break;
-
- case 0x10:
- addr += 4;
- break;
-
- case 0x12:
- addr += 5;
- break;
-
- case 0x11:
- addr += 6;
- break;
-
- case 0x20:
- addr += 3;
- break;
-
- case 0x21:
- addr += 7;
- break;
-
- default:
- throw new ArgumentException("Invalid combination");
- }
-
- return addr;
+ 0 | 0x22 => 0,
+ 0x02 => 1,
+ 0x01 => 2,
+ 0x10 => 4,
+ 0x12 => 5,
+ 0x11 => 6,
+ 0x20 => 3,
+ 0x21 => 7,
+ _ => throw new ArgumentException("Invalid combination"),
+ };
+
+ return addr += addr2;
}
public static byte SetChannelBits(byte configByte, int channel)
@@ -118,25 +73,13 @@ public static byte SetChannelBits(byte configByte, int channel)
return (byte)((configByte & ~Helpers.Masks.ChannelMask) | ((byte)channel << 5));
}
- public static byte SetGainBits(byte configByte, AdcGain gain)
- {
- return (byte)((configByte & ~Helpers.Masks.GainMask) | (byte)gain);
- }
+ public static byte SetGainBits(byte configByte, AdcGain gain) => (byte)((configByte & ~Helpers.Masks.GainMask) | (byte)gain);
- public static byte SetModeBit(byte configByte, AdcMode mode)
- {
- return (byte)((configByte & ~Helpers.Masks.ModeMask) | (byte)mode);
- }
+ public static byte SetModeBit(byte configByte, AdcMode mode) => (byte)((configByte & ~Helpers.Masks.ModeMask) | (byte)mode);
- public static byte SetReadyBit(byte configByte, bool ready)
- {
- return (byte)(ready ? configByte & ~Helpers.Masks.ReadyMask : configByte | Helpers.Masks.ReadyMask);
- }
+ public static byte SetReadyBit(byte configByte, bool ready) => (byte)(ready ? configByte & ~Helpers.Masks.ReadyMask : configByte | Helpers.Masks.ReadyMask);
- public static byte SetResolutionBits(byte configByte, AdcResolution resolution)
- {
- return (byte)((configByte & ~Helpers.Masks.ResolutionMask) | (byte)resolution);
- }
+ public static byte SetResolutionBits(byte configByte, AdcResolution resolution) => (byte)((configByte & ~Helpers.Masks.ResolutionMask) | (byte)resolution);
public static int UpdateFrequency(AdcResolution res)
{
diff --git a/src/devices/Mcp3428/Mcp3426.cs b/src/devices/Mcp3428/Mcp3426.cs
index 8e8026ac00..24d14c8912 100644
--- a/src/devices/Mcp3428/Mcp3426.cs
+++ b/src/devices/Mcp3428/Mcp3426.cs
@@ -34,9 +34,6 @@ public Mcp3426(I2cDevice i2CDevice)
/// ADC resolution
/// PGA gain
public Mcp3426(I2cDevice i2CDevice, AdcMode mode = AdcMode.Continuous, AdcResolution resolution = AdcResolution.Bit12, AdcGain pgaGain = AdcGain.X1)
- : this(i2CDevice)
- {
- SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
- }
+ : this(i2CDevice) => SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
}
}
diff --git a/src/devices/Mcp3428/Mcp3427.cs b/src/devices/Mcp3428/Mcp3427.cs
index 504d8bd748..bcd751f94b 100644
--- a/src/devices/Mcp3428/Mcp3427.cs
+++ b/src/devices/Mcp3428/Mcp3427.cs
@@ -29,10 +29,7 @@ public Mcp3427(I2cDevice i2CDevice)
/// ADC resolution
/// PGA gain
public Mcp3427(I2cDevice i2CDevice, AdcMode mode = AdcMode.Continuous, AdcResolution resolution = AdcResolution.Bit12, AdcGain pgaGain = AdcGain.X1)
- : this(i2CDevice)
- {
- SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
- }
+ : this(i2CDevice) => SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
///
/// Determine device I2C address based on the configuration pin states.
@@ -40,9 +37,6 @@ public Mcp3427(I2cDevice i2CDevice, AdcMode mode = AdcMode.Continuous, AdcResolu
/// The adr0 pin state
/// The adr1 pin state
/// System.Int32.
- public static int I2CAddressFromPins(PinState adr0, PinState adr1)
- {
- return Helpers.I2CAddressFromPins(adr0, adr1);
- }
+ public static int I2CAddressFromPins(PinState adr0, PinState adr1) => Helpers.I2CAddressFromPins(adr0, adr1);
}
}
diff --git a/src/devices/Mcp3428/Mcp3428.cs b/src/devices/Mcp3428/Mcp3428.cs
index 8b62bfa5d2..f878e739d4 100644
--- a/src/devices/Mcp3428/Mcp3428.cs
+++ b/src/devices/Mcp3428/Mcp3428.cs
@@ -30,10 +30,7 @@ public Mcp3428(I2cDevice i2CDevice)
/// PGA gain
public Mcp3428(I2cDevice i2CDevice, AdcMode mode = AdcMode.Continuous,
AdcResolution resolution = AdcResolution.Bit12, AdcGain pgaGain = AdcGain.X1)
- : this(i2CDevice)
- {
- SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
- }
+ : this(i2CDevice) => SetConfig(0, mode: mode, resolution: resolution, pgaGain: pgaGain);
///
/// Determine device I2C address based on the configuration pin states.
@@ -41,9 +38,6 @@ public Mcp3428(I2cDevice i2CDevice, AdcMode mode = AdcMode.Continuous,
/// The adr0 pin state
/// The adr1 pin state
/// System.Int32.
- public static int I2CAddressFromPins(PinState adr0, PinState adr1)
- {
- return Helpers.I2CAddressFromPins(adr0, adr1);
- }
+ public static int I2CAddressFromPins(PinState adr0, PinState adr1) => Helpers.I2CAddressFromPins(adr0, adr1);
}
}
diff --git a/src/devices/Mcp3428/Mcp342x.cs b/src/devices/Mcp3428/Mcp342x.cs
index a5de743abd..732e4e525e 100644
--- a/src/devices/Mcp3428/Mcp342x.cs
+++ b/src/devices/Mcp3428/Mcp342x.cs
@@ -19,12 +19,12 @@ public abstract class Mcp342x : IDisposable
///
/// Protected constructor to easily generate MCP3426/7 devices whose only difference is channel count and I2C address
///
- /// The i2 c device.
+ /// The i2 c device.
/// The channels.
///
- protected Mcp342x(I2cDevice i2CDevice, int channels)
+ protected Mcp342x(I2cDevice i2cDevice, int channels)
{
- _i2cDevice = i2CDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
ChannelCount = channels;
ReadValue(); // Don't like this in constructor, makes sure props are valid
}
@@ -86,23 +86,13 @@ public AdcResolution Resolution
}
}
- ///
- public void Dispose()
- {
- _i2cDevice?.Dispose();
- _i2cDevice = null!;
- }
-
///
/// Reads the channel.
///
/// The channel.
/// System.Double.
///
- public double ReadChannel(int channel)
- {
- return ReadValue(channel);
- }
+ public double ReadChannel(int channel) => ReadValue(channel);
private readonly byte[] _readBuffer = new byte[3];
private I2cDevice _i2cDevice;
@@ -309,10 +299,7 @@ protected bool SetConfig(int channel = 0, AdcMode mode = AdcMode.Continuous,
///
protected ConversionResult LastConversion
{
- get
- {
- return _lastConversion;
- }
+ get => _lastConversion;
set
{
_lastConversion = value;
@@ -329,10 +316,7 @@ protected ConversionResult LastConversion
/// Writes configuration
///
/// Configuration to write
- protected void WriteConfig(byte configByte)
- {
- _i2cDevice.WriteByte(configByte);
- }
+ protected void WriteConfig(byte configByte) => _i2cDevice.WriteByte(configByte);
private static int _asyncThreshold = 20;
@@ -346,10 +330,7 @@ protected void WriteConfig(byte configByte)
///
/// Time limit in ms. Default: 20ms
///
- public static void SetAsyncThreshold(int thresh)
- {
- _asyncThreshold = thresh;
- }
+ public static void SetAsyncThreshold(int thresh) => _asyncThreshold = thresh;
///
/// One-shot read as an asynchronous operation. Initiates read and waits for it to finish.
@@ -463,5 +444,12 @@ public async ValueTask ReadChannelAsync(int channel, CancellationToken c
await ReadValueAsync(channel, cancellationToken);
return LastConversion.Voltage;
}
+
+ ///
+ public void Dispose()
+ {
+ _i2cDevice?.Dispose();
+ _i2cDevice = null!;
+ }
}
}
diff --git a/src/devices/Mcp3428/samples/Program.cs b/src/devices/Mcp3428/samples/Program.cs
index 56f5b3ba13..d922e05264 100644
--- a/src/devices/Mcp3428/samples/Program.cs
+++ b/src/devices/Mcp3428/samples/Program.cs
@@ -4,13 +4,13 @@
using System;
using System.Device.I2c;
using System.Diagnostics;
-using System.Threading.Tasks;
+using System.Threading;
using Iot.Device.Mcp3428;
Console.WriteLine("Hello Mcp3428 Sample!");
I2cConnectionSettings options = new (1, Mcp3428.I2CAddressFromPins(PinState.Low, PinState.Low));
using I2cDevice i2cDevice = I2cDevice.Create(options);
-using Mcp3428 adc = new Mcp3428(i2cDevice, AdcMode.OneShot, resolution: AdcResolution.Bit16, pgaGain: AdcGain.X1);
+using Mcp3428 adc = new (i2cDevice, AdcMode.OneShot, resolution: AdcResolution.Bit16, pgaGain: AdcGain.X1);
var watch = new Stopwatch();
watch.Start();
while (true)
@@ -27,9 +27,9 @@
Console.WriteLine();
Console.WriteLine($"ADC Channel[{adc.LastChannel + 1}] read in {watch.ElapsedMilliseconds - last} ms, value: {value} V");
- await Task.Delay(500);
+ Thread.Sleep(500);
}
Console.WriteLine($"mode {adc.Mode}, gain {adc.InputGain}, res {adc.Resolution}");
- await Task.Delay(1000);
+ Thread.Sleep(1000);
}
diff --git a/src/devices/Mcp3xxx/Mcp3001.cs b/src/devices/Mcp3xxx/Mcp3001.cs
index 9097d340b9..8dc8d1e7ec 100644
--- a/src/devices/Mcp3xxx/Mcp3001.cs
+++ b/src/devices/Mcp3xxx/Mcp3001.cs
@@ -23,10 +23,7 @@ public Mcp3001(SpiDevice spiDevice)
/// Reads a 10-bit (0..1023) value from the device
///
/// 10-bit value corresponding to relative voltage level on specified device channel
- public int Read()
- {
- // Read the data from the device. As the 10 bits of data start at bit 3 then read 13 bits and shift right by 3.
- return ReadInternal(adcRequest: 0, adcResolutionBits: 10 + 3, delayBits: 0) >> 3;
- }
+ // Read the data from the device. As the 10 bits of data start at bit 3 then read 13 bits and shift right by 3.
+ public int Read() => ReadInternal(adcRequest: 0, adcResolutionBits: 10 + 3, delayBits: 0) >> 3;
}
}
diff --git a/src/devices/Mcp3xxx/Mcp3201.cs b/src/devices/Mcp3xxx/Mcp3201.cs
index dce2ddcb1a..69c1d6816c 100644
--- a/src/devices/Mcp3xxx/Mcp3201.cs
+++ b/src/devices/Mcp3xxx/Mcp3201.cs
@@ -23,10 +23,7 @@ public Mcp3201(SpiDevice spiDevice)
/// Reads a 12-bit (0..4096) value from the device
///
/// 12-bit value corresponding to relative voltage level on specified device channel
- public int Read()
- {
- // Read the data from the device. As the 12 bits of data start at bit 1 then read 13 bits and shift right by 1.
- return ReadInternal(adcRequest: 0, adcResolutionBits: 12 + 1, delayBits: 0) >> 1;
- }
+ // Read the data from the device. As the 12 bits of data start at bit 1 then read 13 bits and shift right by 1.
+ public int Read() => ReadInternal(adcRequest: 0, adcResolutionBits: 12 + 1, delayBits: 0) >> 1;
}
}
diff --git a/src/devices/Mcp3xxx/Mcp33xx.cs b/src/devices/Mcp3xxx/Mcp33xx.cs
index a610d5aad0..94f95b053f 100644
--- a/src/devices/Mcp3xxx/Mcp33xx.cs
+++ b/src/devices/Mcp3xxx/Mcp33xx.cs
@@ -28,10 +28,7 @@ public Mcp33xx(SpiDevice spiDevice, byte channelCount, byte adcResolutionBits)
/// Channel which represents the signal (valid values: 0 to channelcount - 1).
/// Channel which represents the signal ground (valid values: 0 to channelcount - 1).
/// A value corresponding to relative voltage level on specified device channels
- public override int ReadPseudoDifferential(int valueChannel, int referenceChannel)
- {
- throw new NotSupportedException($"Mcp33xx device does not support {nameof(ReadPseudoDifferential)}.");
- }
+ public override int ReadPseudoDifferential(int valueChannel, int referenceChannel) => throw new NotSupportedException($"Mcp33xx device does not support {nameof(ReadPseudoDifferential)}.");
///
/// Reads a 13 bit signed value from the device using differential inputs
@@ -53,7 +50,7 @@ public override int ReadDifferential(int valueChannel, int referenceChannel)
if (valueChannel == referenceChannel)
{
- throw new ArgumentException($"ADC differential channels must be different.", nameof(valueChannel) + " " + nameof(referenceChannel));
+ throw new ArgumentException(nameof(valueChannel), $"ADC differential channels must be different. {nameof(valueChannel)}: {valueChannel}; {nameof(referenceChannel)}: {referenceChannel}.");
}
// check if it is possible to use hardware differential because both input channels are in the same differential channel pairing
@@ -80,10 +77,7 @@ public override int ReadDifferential(int valueChannel, int referenceChannel)
/// Signed value with a sign bit at a particular location
/// Bit number that contains the sign bit
/// A value corresponding to the signed value sign extended into an int
- public static int SignExtend(int signedValue, int signingBit)
- {
- // if the sign bit is set then extend the signing bit to create a signed integer
- return (signedValue >> signingBit) == 0 ? signedValue : signedValue - (2 << signingBit);
- }
+ // if the sign bit is set then extend the signing bit to create a signed integer
+ public static int SignExtend(int signedValue, int signingBit) => (signedValue >> signingBit) == 0 ? signedValue : signedValue - (2 << signingBit);
}
}
diff --git a/src/devices/Mcp3xxx/Mcp3Base.cs b/src/devices/Mcp3xxx/Mcp3Base.cs
index a8e247e7f7..e84f91dd7a 100644
--- a/src/devices/Mcp3xxx/Mcp3Base.cs
+++ b/src/devices/Mcp3xxx/Mcp3Base.cs
@@ -109,24 +109,7 @@ protected enum InputType
/// Constructs Mcp3Base instance
///
/// Device used for SPI communication
- public Mcp3Base(SpiDevice spiDevice)
- {
- if (spiDevice == null)
- {
- throw new ArgumentNullException(nameof(spiDevice));
- }
-
- _spiDevice = spiDevice;
- }
-
- ///
- /// Disposes Mcp3Base instances
- ///
- public void Dispose()
- {
- _spiDevice?.Dispose();
- _spiDevice = null!;
- }
+ public Mcp3Base(SpiDevice spiDevice) => _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
///
/// Reads a value from the device
@@ -174,5 +157,14 @@ protected int ReadInternal(int adcRequest, int adcResolutionBits, int delayBits)
// return the ADC response with any possible higer bits masked out
return retval & (int)((1L << adcResolutionBits) - 1);
}
+
+ ///
+ /// Disposes Mcp3Base instances
+ ///
+ public void Dispose()
+ {
+ _spiDevice?.Dispose();
+ _spiDevice = null!;
+ }
}
}
diff --git a/src/devices/Mcp3xxx/Mcp3xxx.cs b/src/devices/Mcp3xxx/Mcp3xxx.cs
index 03bcff18bc..947de20983 100644
--- a/src/devices/Mcp3xxx/Mcp3xxx.cs
+++ b/src/devices/Mcp3xxx/Mcp3xxx.cs
@@ -63,8 +63,7 @@ protected void CheckChannelPairing(int valueChannel, int referenceChannel)
if (valueChannel / 2 != referenceChannel / 2 || valueChannel == referenceChannel)
{
throw new ArgumentException(
- $"ADC differential channels must be different and part of the same channel pairing.",
- nameof(valueChannel) + " " + nameof(referenceChannel));
+ $"ADC differential channels must be different and part of the same channel pairing. {nameof(valueChannel)} - {nameof(referenceChannel)}");
}
}
@@ -107,8 +106,7 @@ public virtual int ReadDifferential(int valueChannel, int referenceChannel)
if (valueChannel == referenceChannel)
{
- throw new ArgumentException($"ADC differential channels must be different.",
- nameof(valueChannel) + " " + nameof(referenceChannel));
+ throw new ArgumentException(nameof(valueChannel), $"ADC differential channels must be different. {nameof(valueChannel)} - {nameof(referenceChannel)}");
}
return ReadInternal(valueChannel, InputType.SingleEnded, _adcResolutionBits) -
@@ -120,10 +118,7 @@ public virtual int ReadDifferential(int valueChannel, int referenceChannel)
///
/// Channel which value should be read from (valid values: 0 to channelcount - 1)
/// A value corresponding to relative voltage level on specified device channel
- public virtual int Read(int channel)
- {
- return ReadInternal(channel, InputType.SingleEnded, _adcResolutionBits);
- }
+ public virtual int Read(int channel) => ReadInternal(channel, InputType.SingleEnded, _adcResolutionBits);
///
/// Reads a value from the device
@@ -134,47 +129,24 @@ public virtual int Read(int channel)
/// A value corresponding to relative voltage level on specified device channel
protected int ReadInternal(int channel, InputType inputType, int adcResolutionBits)
{
- int channelVal;
- int requestVal;
-
CheckChannelRange(channel, inputType == InputType.SingleEnded ? ChannelCount : ChannelCount / 2);
// create a value that represents the channel value. For differental inputs
// then incorporate the lower bit which indicates if the channel is inverted or not.
- switch (inputType)
+ int channelVal = inputType switch
{
- case InputType.Differential:
- channelVal = channel * 2;
- break;
-
- case InputType.InvertedDifferential:
- channelVal = channel * 2;
- break;
-
- default:
- channelVal = channel;
- break;
- }
+ InputType.Differential | InputType.InvertedDifferential => channel * 2,
+ _ =>channel,
+ };
// create a value to represent the request to the ADC
- switch (ChannelCount)
+ int requestVal = ChannelCount switch
{
- case 4:
- case 8:
- requestVal = (inputType == InputType.SingleEnded ? 0b1_1000 : 0b1_0000) | channelVal;
- break;
-
- case 2:
- requestVal = (inputType == InputType.SingleEnded ? 0b1101 : 0b1001) | channelVal << 1;
- break;
-
- case 1:
- requestVal = 0;
- break;
-
- default:
- throw new ArgumentOutOfRangeException("Unsupported Channel Count");
- }
+ 4 | 8 => (inputType == InputType.SingleEnded ? 0b1_1000 : 0b1_0000) | channelVal,
+ 2 => (inputType == InputType.SingleEnded ? 0b1101 : 0b1001) | channelVal << 1,
+ 1 => 0,
+ _ => throw new ArgumentOutOfRangeException("Unsupported Channel Count"),
+ };
// read the data from the device...
// the delayBits is set to account for the extra sampling delay on the 3004, 3008, 3204, 3208, 3302 and 3304
diff --git a/src/devices/Mcp3xxx/samples/Program.cs b/src/devices/Mcp3xxx/samples/Program.cs
index 4dc9a07e0b..a74d778d34 100644
--- a/src/devices/Mcp3xxx/samples/Program.cs
+++ b/src/devices/Mcp3xxx/samples/Program.cs
@@ -12,7 +12,7 @@
ClockFrequency = 1000000
};
-using SpiDevice spi = new SoftwareSpi(clk: 6, miso: 23, mosi: 5, cs: 24);
+using SpiDevice spi = new SoftwareSpi(clk: 6, sdi: 23, sdo: 5, cs: 24);
// For hardware implementation replace it with following
// using (SpiDevice spi = SpiDevice.Create(hardwareSpiSettings))
using Mcp3008 mcp = new Mcp3008(spi);
diff --git a/src/devices/Mcp9808/Mcp9808.cs b/src/devices/Mcp9808/Mcp9808.cs
index 32d76addb5..9b4197bf3a 100644
--- a/src/devices/Mcp9808/Mcp9808.cs
+++ b/src/devices/Mcp9808/Mcp9808.cs
@@ -34,10 +34,7 @@ public class Mcp9808 : IDisposable
///
public bool Disabled
{
- get
- {
- return _disable;
- }
+ get => _disable;
set
{
SetShutdown(value);
@@ -52,7 +49,7 @@ public bool Disabled
/// The I2C device used for communication.
public Mcp9808(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
Disabled = false;
@@ -85,10 +82,7 @@ private bool Init()
/// Return the internal resolution register
///
/// Resolution setting
- public byte GetResolution()
- {
- return Read8(Register8.MCP_RESOLUTION);
- }
+ public byte GetResolution() => Read8(Register8.MCP_RESOLUTION);
///
/// Wakes-up the device
@@ -104,10 +98,7 @@ public void Wake()
///
/// Shuts down the device
///
- public void Shutdown()
- {
- SetShutdown(true);
- }
+ public void Shutdown() => SetShutdown(true);
///
/// Read MCP9808 Temperature (℃)
@@ -164,10 +155,7 @@ public void Dispose()
_i2cDevice = null!;
}
- internal Register16 ReadRegister16(Register8 reg)
- {
- return (Register16)Read16(reg);
- }
+ internal Register16 ReadRegister16(Register8 reg) => (Register16)Read16(reg);
internal ushort Read16(Register8 reg)
{
@@ -191,7 +179,6 @@ internal void Write16(Register8 reg, Register16 value)
internal byte Read8(Register8 reg)
{
_i2cDevice.WriteByte((byte)reg);
-
return _i2cDevice.ReadByte();
}
diff --git a/src/devices/Media/SoundDevice/Devices/UnixSoundDevice.cs b/src/devices/Media/SoundDevice/Devices/UnixSoundDevice.cs
index a2c4b79740..1e0881846b 100644
--- a/src/devices/Media/SoundDevice/Devices/UnixSoundDevice.cs
+++ b/src/devices/Media/SoundDevice/Devices/UnixSoundDevice.cs
@@ -61,7 +61,11 @@ public override bool PlaybackMute
///
/// The recording volume of the sound device.
///
- public override long RecordingVolume { get => GetRecordingVolume(); set => SetRecordingVolume(value); }
+ public override long RecordingVolume
+ {
+ get => GetRecordingVolume();
+ set => SetRecordingVolume(value);
+ }
private bool _recordingMute;
diff --git a/src/devices/Media/SoundDevice/samples/Program.cs b/src/devices/Media/SoundDevice/samples/Program.cs
index d41de197f3..51fffb5edc 100644
--- a/src/devices/Media/SoundDevice/samples/Program.cs
+++ b/src/devices/Media/SoundDevice/samples/Program.cs
@@ -5,7 +5,7 @@
using System.IO;
using Iot.Device.Media;
-SoundConnectionSettings settings = new SoundConnectionSettings();
+SoundConnectionSettings settings = new ();
using SoundDevice device = SoundDevice.Create(settings);
string path = Directory.GetCurrentDirectory();
diff --git a/src/devices/Media/VideoDevice/samples/Program.cs b/src/devices/Media/VideoDevice/samples/Program.cs
index c1a3f6229f..04ff7cebfd 100644
--- a/src/devices/Media/VideoDevice/samples/Program.cs
+++ b/src/devices/Media/VideoDevice/samples/Program.cs
@@ -6,7 +6,7 @@
using System.IO;
using Iot.Device.Media;
-VideoConnectionSettings settings = new VideoConnectionSettings(0, (2560, 1920), PixelFormat.JPEG);
+VideoConnectionSettings settings = new (0, (2560, 1920), PixelFormat.JPEG);
using VideoDevice device = VideoDevice.Create(settings);
// Get the supported formats of the device
diff --git a/src/devices/Mhz19b/Mhz19b.cs b/src/devices/Mhz19b/Mhz19b.cs
index fca42bcfc2..438dc0146c 100644
--- a/src/devices/Mhz19b/Mhz19b.cs
+++ b/src/devices/Mhz19b/Mhz19b.cs
@@ -65,7 +65,7 @@ public Mhz19b(string uartDevice)
public VolumeConcentration GetCo2Reading()
{
// send read command request
- var request = CreateRequest(Command.ReadCo2Concentration);
+ byte[] request = CreateRequest(Command.ReadCo2Concentration);
request[(int)MessageFormat.Checksum] = Checksum(request);
_serialPortStream.Write(request, 0, request.Length);
@@ -115,7 +115,7 @@ public void PerformSpanPointCalibration(VolumeConcentration span)
throw new ArgumentException("Span value out of range (1000-5000[ppm])", nameof(span));
}
- var request = CreateRequest(Command.CalibrateSpanPoint);
+ byte[] request = CreateRequest(Command.CalibrateSpanPoint);
// set span in request, c. f. datasheet rev. 1.0, pg. 8 for details
request[(int)MessageFormat.DataHighRequest] = (byte)(span.PartsPerMillion / 256);
request[(int)MessageFormat.DataLowRequest] = (byte)(span.PartsPerMillion % 256);
@@ -130,7 +130,7 @@ public void PerformSpanPointCalibration(VolumeConcentration span)
/// Communication with sensor failed
public void SetAutomaticBaselineCorrection(AbmState state)
{
- var request = CreateRequest(Command.AutoCalibrationSwitch);
+ byte[] request = CreateRequest(Command.AutoCalibrationSwitch);
// set on/off state in request, c. f. datasheet rev. 1.0, pg. 8 for details
request[(int)MessageFormat.DataHighRequest] = (byte)state;
@@ -144,7 +144,7 @@ public void SetAutomaticBaselineCorrection(AbmState state)
/// Communication with sensor failed
public void SetSensorDetectionRange(DetectionRange detectionRange)
{
- var request = CreateRequest(Command.DetectionRangeSetting);
+ byte[] request = CreateRequest(Command.DetectionRangeSetting);
// set detection range in request, c. f. datasheet rev. 1.0, pg. 8 for details
request[(int)MessageFormat.DataHighRequest] = (byte)((int)detectionRange / 256);
request[(int)MessageFormat.DataLowRequest] = (byte)((int)detectionRange % 256);
diff --git a/src/devices/Mhz19b/samples/Program.cs b/src/devices/Mhz19b/samples/Program.cs
index 8cd0f63526..c2b74ab4bc 100644
--- a/src/devices/Mhz19b/samples/Program.cs
+++ b/src/devices/Mhz19b/samples/Program.cs
@@ -10,14 +10,14 @@
using UnitsNet;
// create serial port using the setting acc. to datasheet, pg. 7, sec. general settings
-using SerialPort serialPort = new SerialPort("/dev/serial0", 9600, Parity.None, 8, StopBits.One)
+using SerialPort serialPort = new ("/dev/serial0", 9600, Parity.None, 8, StopBits.One)
{
Encoding = Encoding.ASCII,
ReadTimeout = 1000,
WriteTimeout = 1000
};
serialPort.Open();
-using Mhz19b sensor = new Mhz19b(serialPort.BaseStream, true);
+using Mhz19b sensor = new (serialPort.BaseStream, true);
// Alternatively you can let the binding create the serial port stream:
// Mhz19b sensor = new Mhz19b("/dev/serial0");
diff --git a/src/devices/Mlx90614/Mlx90614.cs b/src/devices/Mlx90614/Mlx90614.cs
index 53e5b71ec6..b4b25d3649 100644
--- a/src/devices/Mlx90614/Mlx90614.cs
+++ b/src/devices/Mlx90614/Mlx90614.cs
@@ -26,7 +26,7 @@ public sealed class Mlx90614 : IDisposable
/// The I2C device used for communication.
public Mlx90614(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
}
///
diff --git a/src/devices/Mlx90614/samples/Program.cs b/src/devices/Mlx90614/samples/Program.cs
index 042b36b506..386fac20b7 100644
--- a/src/devices/Mlx90614/samples/Program.cs
+++ b/src/devices/Mlx90614/samples/Program.cs
@@ -9,7 +9,7 @@
I2cConnectionSettings settings = new (1, Mlx90614.DefaultI2cAddress);
using I2cDevice i2cDevice = I2cDevice.Create(settings);
-using Mlx90614 sensor = new Mlx90614(i2cDevice);
+using Mlx90614 sensor = new (i2cDevice);
while (true)
{
Console.WriteLine($"Ambient: {sensor.ReadAmbientTemperature().DegreesCelsius} ℃");
diff --git a/src/devices/MotorHat/DCMotor3Pwm.cs b/src/devices/MotorHat/DCMotor3Pwm.cs
index 27bcb0ff1a..f61f16084d 100644
--- a/src/devices/MotorHat/DCMotor3Pwm.cs
+++ b/src/devices/MotorHat/DCMotor3Pwm.cs
@@ -28,11 +28,8 @@ public DCMotor3Pwm(PwmChannel pwm, PwmChannel in1, PwmChannel in2)
public override double Speed
{
- get
- {
- // Just return the last speed received
- return _speed;
- }
+ // Just return the last speed received
+ get => _speed;
set
{
// Make sure the speed is between -1 and 1
@@ -67,7 +64,7 @@ public override double Speed
}
}
- protected override void Dispose(bool disposing)
+ public override void Dispose()
{
_pwmPin.Stop();
_in1Pin.Stop();
diff --git a/src/devices/MotorHat/MotorHat.cs b/src/devices/MotorHat/MotorHat.cs
index 3935405a13..4def7be47b 100644
--- a/src/devices/MotorHat/MotorHat.cs
+++ b/src/devices/MotorHat/MotorHat.cs
@@ -41,7 +41,7 @@ public class MotorHat : IDisposable
///
public MotorHat(I2cConnectionSettings settings, double frequency = 1600)
{
- var device = I2cDevice.Create(settings);
+ I2cDevice device = I2cDevice.Create(settings);
_pca9685 = new Pca9685(device);
_pca9685.PwmFrequency = frequency;
@@ -108,7 +108,7 @@ public DCMotor.DCMotor CreateDCMotor(int motorNumber)
in1Pin = 5;
break;
default:
- throw new ArgumentException($"MotorHat Motor must be between 1 and 4 inclusive. Received: {motorNumber}");
+ throw new ArgumentException(nameof(motorNumber), $"MotorHat Motor must be between 1 and 4 inclusive. {nameof(motorNumber)}: {motorNumber}");
}
var speedPwm = _pca9685.CreatePwmChannel(speedPin);
diff --git a/src/devices/MotorHat/samples/Program.cs b/src/devices/MotorHat/samples/Program.cs
index d5e7b62f39..0a70c0c2e7 100644
--- a/src/devices/MotorHat/samples/Program.cs
+++ b/src/devices/MotorHat/samples/Program.cs
@@ -15,7 +15,7 @@
// var selectedI2cAddress = 0b000000; // A5 A4 A3 A2 A1 A0
// var deviceAddress = MotorHat.I2cAddressBase + selectedI2cAddress;
// I2cConnectionSettings settings = new (busId, deviceAddress);
-using MotorHat motorHat = new MotorHat();
+using MotorHat motorHat = new ();
using DCMotor motor = motorHat.CreateDCMotor(1);
bool done = false;
diff --git a/src/devices/Mpr121/Mpr121.cs b/src/devices/Mpr121/Mpr121.cs
index a672b667c0..a405d5b25f 100644
--- a/src/devices/Mpr121/Mpr121.cs
+++ b/src/devices/Mpr121/Mpr121.cs
@@ -22,7 +22,7 @@ public class Mpr121 : IDisposable
private static readonly int CHANNELS_NUMBER = Enum.GetValues(typeof(Channels)).Length;
- private I2cDevice _device;
+ private I2cDevice _i2cDevice;
private Timer _timer;
private Dictionary _statuses;
@@ -43,11 +43,7 @@ public class Mpr121 : IDisposable
///
public int PeriodRefresh
{
- get
- {
- return _periodRefresh;
- }
-
+ get => _periodRefresh;
set
{
_periodRefresh = value;
@@ -67,14 +63,14 @@ public int PeriodRefresh
///
/// Initialize a MPR121 controller.
///
- /// The i2c device.
+ /// The i2c device.
/// The period in milliseconds of refresing the channel statuses.
/// The controller configuration.
- public Mpr121(I2cDevice device, int periodRefresh = -1, Mpr121Configuration? configuration = null)
+ public Mpr121(I2cDevice i2cDevice, int periodRefresh = -1, Mpr121Configuration? configuration = null)
{
configuration = configuration ?? GetDefaultConfiguration();
- _device = device;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
_timer = new Timer(RefreshChannelStatuses, this, Timeout.Infinite, Timeout.Infinite);
_statuses = new Dictionary();
@@ -91,8 +87,8 @@ public Mpr121(I2cDevice device, int periodRefresh = -1, Mpr121Configuration? con
///
public void Dispose()
{
- _device?.Dispose();
- _device = null!;
+ _i2cDevice?.Dispose();
+ _i2cDevice = null!;
_timer?.Dispose();
_timer = null!;
}
@@ -182,10 +178,7 @@ private void InitializeController(Mpr121Configuration configuration)
///
/// The callback function for timer to refresh channels statuses.
///
- private void RefreshChannelStatuses(object? state)
- {
- RefreshChannelStatuses();
- }
+ private void RefreshChannelStatuses(object? state) => RefreshChannelStatuses();
///
/// Refresh the channel statuses.
@@ -197,7 +190,7 @@ private void RefreshChannelStatuses()
PeriodRefresh = 0;
Span buffer = stackalloc byte[2];
- _device.Read(buffer);
+ _i2cDevice.Read(buffer);
short rawStatus = BinaryPrimitives.ReadInt16LittleEndian(buffer);
bool isStatusChanged = false;
@@ -226,12 +219,9 @@ private void SetRegister(Registers register, byte value)
{
(byte)register, value
};
- _device.Write(data);
+ _i2cDevice.Write(data);
}
- private void OnChannelStatusesChanged()
- {
- ChannelStatusesChanged?.Invoke(this, new ChannelStatusesChangedEventArgs(_statuses.ToImmutableDictionary()));
- }
+ private void OnChannelStatusesChanged() => ChannelStatusesChanged?.Invoke(this, new ChannelStatusesChangedEventArgs(_statuses.ToImmutableDictionary()));
}
}
diff --git a/src/devices/Mpr121/samples/Program.cs b/src/devices/Mpr121/samples/Program.cs
index 3dba1829b8..18518f1d68 100644
--- a/src/devices/Mpr121/samples/Program.cs
+++ b/src/devices/Mpr121/samples/Program.cs
@@ -8,7 +8,7 @@
using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(busId: 1, deviceAddress: Mpr121.DefaultI2cAddress));
// Initialize controller with default configuration and auto-refresh the channel statuses every 100 ms.
-using Mpr121 mpr121 = new Mpr121(device: i2cDevice, periodRefresh: 100);
+using Mpr121 mpr121 = new (i2cDevice: i2cDevice, periodRefresh: 100);
Console.Clear();
Console.CursorVisible = false;
diff --git a/src/devices/Mpu9250/Mpu6500.cs b/src/devices/Mpu9250/Mpu6500.cs
index 9a61048ad3..5ede611a2b 100644
--- a/src/devices/Mpu9250/Mpu6500.cs
+++ b/src/devices/Mpu9250/Mpu6500.cs
@@ -66,7 +66,7 @@ public Mpu6500(I2cDevice i2cDevice)
///
internal Mpu6500(I2cDevice i2cDevice, bool isInternal)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
}
#region Accelerometer
@@ -82,7 +82,6 @@ internal Mpu6500(I2cDevice i2cDevice, bool isInternal)
public AccelerometerRange AccelerometerRange
{
get => _accelerometerRange;
-
set
{
WriteRegister(Register.ACCEL_CONFIG, (byte)((byte)value << 3));
@@ -102,7 +101,6 @@ public AccelerometerRange AccelerometerRange
public AccelerometerBandwidth AccelerometerBandwidth
{
get => _accelerometerBandwidth;
-
set
{
WriteRegister(Register.ACCEL_CONFIG_2, (byte)value);
@@ -122,24 +120,14 @@ public float AccelerationScale
{
get
{
- float val = 0;
- switch (AccelerometerRange)
+ float val = AccelerometerRange switch
{
- case AccelerometerRange.Range02G:
- val = 2.0f;
- break;
- case AccelerometerRange.Range04G:
- val = 4.0f;
- break;
- case AccelerometerRange.Range08G:
- val = 8.0f;
- break;
- case AccelerometerRange.Range16G:
- val = 16.0f;
- break;
- default:
- break;
- }
+ AccelerometerRange.Range02G => 2.0f,
+ AccelerometerRange.Range04G => 4.0f,
+ AccelerometerRange.Range08G => 8.0f,
+ AccelerometerRange.Range16G => 16.0f,
+ _ => 0,
+ };
val = (val * Gravity) / Adc;
return val / (1 + SampleRateDivider);
@@ -181,8 +169,8 @@ private Vector3 GetRawAccelerometer()
///
public AccelerometerLowPowerFrequency AccelerometerLowPowerFrequency
{
- get { return (AccelerometerLowPowerFrequency)ReadByte(Register.LP_ACCEL_ODR); }
- set { WriteRegister(Register.LP_ACCEL_ODR, (byte)value); }
+ get => (AccelerometerLowPowerFrequency)ReadByte(Register.LP_ACCEL_ODR);
+ set => WriteRegister(Register.LP_ACCEL_ODR, (byte)value);
}
#endregion
@@ -200,7 +188,6 @@ public AccelerometerLowPowerFrequency AccelerometerLowPowerFrequency
public GyroscopeRange GyroscopeRange
{
get => _gyroscopeRange;
-
set
{
WriteRegister(Register.GYRO_CONFIG, (byte)((byte)value << 3));
@@ -218,7 +205,6 @@ public GyroscopeRange GyroscopeRange
public GyroscopeBandwidth GyroscopeBandwidth
{
get => _gyroscopeBandwidth;
-
set
{
if (value == GyroscopeBandwidth.Bandwidth8800HzFS32)
@@ -361,7 +347,7 @@ public void SetWakeOnMotion(uint accelerometerThreshold, AccelerometerLowPowerFr
_wakeOnMotion = true;
if (accelerometerThreshold > 1020)
{
- throw new ArgumentException($"{nameof(accelerometerThreshold)} has to be between 0mg and 1020mg");
+ throw new ArgumentException(nameof(accelerometerThreshold), $"Value has to be between 0mg and 1020mg");
}
// LSB = 4mg
@@ -417,19 +403,16 @@ internal void PowerOn()
/// Return true if the version of MPU6500 is the correct one
///
/// True if success
- internal bool CheckVersion()
- {
- // Check if the version is thee correct one
- return ReadByte(Register.WHO_AM_I) == 0x70;
- }
+ // Check if the version is thee correct one
+ internal bool CheckVersion() => ReadByte(Register.WHO_AM_I) == 0x70;
///
/// Get or set the sample diver mode
///
public byte SampleRateDivider
{
- get { return ReadByte(Register.SMPLRT_DIV); }
- set { WriteRegister(Register.SMPLRT_DIV, value); }
+ get => ReadByte(Register.SMPLRT_DIV);
+ set => WriteRegister(Register.SMPLRT_DIV, value);
}
///
@@ -438,8 +421,8 @@ public byte SampleRateDivider
///
public DisableModes DisableModes
{
- get { return (DisableModes)ReadByte(Register.PWR_MGMT_2); }
- set { WriteRegister(Register.PWR_MGMT_2, (byte)value); }
+ get => (DisableModes)ReadByte(Register.PWR_MGMT_2);
+ set => WriteRegister(Register.PWR_MGMT_2, (byte)value);
}
#endregion
@@ -467,10 +450,7 @@ public uint FifoCount
///
public FifoModes FifoModes
{
- get
- {
- return (FifoModes)(ReadByte(Register.FIFO_EN));
- }
+ get => (FifoModes)(ReadByte(Register.FIFO_EN));
set
{
if (value != FifoModes.None)
@@ -508,10 +488,7 @@ public FifoModes FifoModes
/// EXT_SENS_DATA_00 to EXT_SENS_DATA_24
///
/// Data which will be read
- public void ReadFifo(Span readData)
- {
- ReadBytes(Register.FIFO_R_W, readData);
- }
+ public void ReadFifo(Span readData) => ReadBytes(Register.FIFO_R_W, readData);
#endregion
@@ -902,7 +879,7 @@ public void ReadByteFromSlaveDevice(I2cChannel i2cChannel, byte address, byte re
{
if (readBytes.Length > 24)
{
- throw new ArgumentException($"Can't read more than 24 bytes at once");
+ throw new ArgumentException(nameof(readBytes), "Value must be 24 bytes or less.");
}
byte slvAddress = (byte)((byte)Register.I2C_SLV0_ADDR + 3 * (byte)i2cChannel);
diff --git a/src/devices/Mpu9250/Mpu9250.cs b/src/devices/Mpu9250/Mpu9250.cs
index 1419729dcd..9bec077e04 100644
--- a/src/devices/Mpu9250/Mpu9250.cs
+++ b/src/devices/Mpu9250/Mpu9250.cs
@@ -21,7 +21,7 @@ namespace Iot.Device.Imu
public class Mpu9250 : Mpu6500
{
private Ak8963 _ak8963;
- private bool _autoDispose;
+ private bool _shouldDispose;
// Use for the first magnetometer read when switch to continuous 100 Hz
private bool _firstContinuousRead = true;
@@ -117,7 +117,7 @@ public Vector3 ReadMagnetometerWithoutCorrection(bool waitForData = true)
/// The data from the magnetometer
public Vector3 ReadMagnetometer(bool waitForData = true)
{
- var magn = _ak8963.ReadMagnetometer(waitForData, GetTimeout());
+ Vector3 magn = _ak8963.ReadMagnetometer(waitForData, GetTimeout());
return new Vector3(magn.Y, magn.X, -magn.Z);
}
@@ -155,10 +155,7 @@ private TimeSpan GetTimeout()
///
public MeasurementMode MagnetometerMeasurementMode
{
- get
- {
- return _ak8963.MeasurementMode;
- }
+ get => _ak8963.MeasurementMode;
set
{
_ak8963.MeasurementMode = value;
@@ -174,8 +171,8 @@ public MeasurementMode MagnetometerMeasurementMode
///
public OutputBitMode MagnetometerOutputBitMode
{
- get { return _ak8963.OutputBitMode; }
- set { _ak8963.OutputBitMode = value; }
+ get => _ak8963.OutputBitMode;
+ set => _ak8963.OutputBitMode = value;
}
///
@@ -189,8 +186,8 @@ public OutputBitMode MagnetometerOutputBitMode
/// Initialize the MPU9250
///
/// The I2C device
- /// Will automatically dispose the I2C device if true
- public Mpu9250(I2cDevice i2cDevice, bool autoDispose = true)
+ /// Will automatically dispose the I2C device if true
+ public Mpu9250(I2cDevice i2cDevice, bool shouldDispose = true)
: base(i2cDevice, true)
{
Reset();
@@ -208,7 +205,7 @@ public Mpu9250(I2cDevice i2cDevice, bool autoDispose = true)
WriteRegister(Register.USER_CTRL, (byte)UserControls.I2C_MST_EN);
// Speed of 400 kHz
WriteRegister(Register.I2C_MST_CTRL, (byte)I2cBusFrequency.Frequency400kHz);
- _autoDispose = autoDispose;
+ _shouldDispose = shouldDispose;
_ak8963 = new Ak8963(i2cDevice, new Ak8963Attached(), false);
if (!_ak8963.IsVersionCorrect())
{
@@ -267,7 +264,7 @@ public Mpu9250(I2cDevice i2cDevice, bool autoDispose = true)
///
public new void Dispose()
{
- if (_autoDispose)
+ if (_shouldDispose)
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
diff --git a/src/devices/Mpu9250/samples/Program.cs b/src/devices/Mpu9250/samples/Program.cs
index 4b72ecf4cd..4cee27b0fd 100644
--- a/src/devices/Mpu9250/samples/Program.cs
+++ b/src/devices/Mpu9250/samples/Program.cs
@@ -7,6 +7,7 @@
using System.Net;
using System.Threading;
using Iot.Device.Imu;
+using Iot.Device.Magnetometer;
Console.WriteLine("Hello MPU9250!");
@@ -24,11 +25,11 @@
void MagnetometerCalibrationDeepDive(int calibrationCount)
{
I2cConnectionSettings mpui2CConnectionSettingmpus = new (1, Mpu9250.DefaultI2cAddress);
- using Mpu9250 mpu9250 = new Mpu9250(I2cDevice.Create(mpui2CConnectionSettingmpus));
- mpu9250.MagnetometerOutputBitMode = Iot.Device.Magnetometer.OutputBitMode.Output16bit;
- mpu9250.MagnetometerMeasurementMode = Iot.Device.Magnetometer.MeasurementMode.ContinuousMeasurement100Hz;
+ using Mpu9250 mpu9250 = new (I2cDevice.Create(mpui2CConnectionSettingmpus));
+ mpu9250.MagnetometerOutputBitMode = OutputBitMode.Output16bit;
+ mpu9250.MagnetometerMeasurementMode = MeasurementMode.ContinuousMeasurement100Hz;
Console.WriteLine("Please move the magnetometer during calibration");
- using var ioWriter = new StreamWriter("mag.csv");
+ using StreamWriter ioWriter = new ("mag.csv");
// First we read the data without calibration at all
Console.WriteLine("Reading magnetometer data without calibration");
ioWriter.WriteLine($"X;Y;Z");
diff --git a/src/devices/Nrf24l01/Nrf24l01.cs b/src/devices/Nrf24l01/Nrf24l01.cs
index e263587dee..ca72747ef4 100644
--- a/src/devices/Nrf24l01/Nrf24l01.cs
+++ b/src/devices/Nrf24l01/Nrf24l01.cs
@@ -39,32 +39,56 @@ public byte PacketSize
///
/// nRF24L01 Send Address
///
- public byte[] Address { get => ReadTxAddress(); set => SetTxAddress(value); }
+ public byte[] Address
+ {
+ get => ReadTxAddress();
+ set => SetTxAddress(value);
+ }
///
/// nRF24L01 Working Channel
///
- public byte Channel { get => ReadChannel(); set => SetChannel(value); }
+ public byte Channel
+ {
+ get => ReadChannel();
+ set => SetChannel(value);
+ }
///
/// nRF24L01 Output Power
///
- public OutputPower OutputPower { get => ReadOutputPower(); set => SetOutputPower(value); }
+ public OutputPower OutputPower
+ {
+ get => ReadOutputPower();
+ set => SetOutputPower(value);
+ }
///
/// nRF24L01 Send Rate
///
- public DataRate DataRate { get => ReadDataRate(); set => SetDataRate(value); }
+ public DataRate DataRate
+ {
+ get => ReadDataRate();
+ set => SetDataRate(value);
+ }
///
/// nRF24L01 Power Mode
///
- public PowerMode PowerMode { get => ReadPowerMode(); set => SetPowerMode(value); }
+ public PowerMode PowerMode
+ {
+ get => ReadPowerMode();
+ set => SetPowerMode(value);
+ }
///
/// nRF24L01 Working Mode
///
- public WorkingMode WorkingMode { get => ReadWorkwingMode(); set => SetWorkingMode(value); }
+ public WorkingMode WorkingMode
+ {
+ get => ReadWorkwingMode();
+ set => SetWorkingMode(value);
+ }
///
/// nRF24L01 Pipe 0
@@ -127,11 +151,11 @@ public byte PacketSize
public Nrf24l01(SpiDevice sensor, int ce, int irq, byte packetSize, byte channel = 2,
OutputPower outputPower = OutputPower.N00dBm, DataRate dataRate = DataRate.Rate2Mbps, PinNumberingScheme pinNumberingScheme = PinNumberingScheme.Logical, GpioController? gpioController = null, bool shouldDispose = true)
{
- _sensor = sensor;
+ _sensor = sensor ?? throw new ArgumentNullException(nameof(sensor));
_ce = ce;
_irq = irq;
PacketSize = packetSize;
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
Initialize(pinNumberingScheme, outputPower, dataRate, channel, gpioController);
InitializePipe();
diff --git a/src/devices/Nrf24l01/Nrf24l01Pipe.cs b/src/devices/Nrf24l01/Nrf24l01Pipe.cs
index cd187b02df..fc1289ad7b 100644
--- a/src/devices/Nrf24l01/Nrf24l01Pipe.cs
+++ b/src/devices/Nrf24l01/Nrf24l01Pipe.cs
@@ -27,21 +27,37 @@ public Nrf24l01Pipe(Nrf24l01 nrf, byte pipeID)
///
/// Receive Pipe Address
///
- public byte[] Address { get => _nrf.ReadRxAddress(_pipeID); set => _nrf.SetRxAddress(_pipeID, value); }
+ public byte[] Address
+ {
+ get => _nrf.ReadRxAddress(_pipeID);
+ set => _nrf.SetRxAddress(_pipeID, value);
+ }
///
/// Auto Acknowledgment
///
- public bool AutoAck { get => _nrf.ReadAutoAck(_pipeID); set => _nrf.SetAutoAck(_pipeID, value); }
+ public bool AutoAck
+ {
+ get => _nrf.ReadAutoAck(_pipeID);
+ set => _nrf.SetAutoAck(_pipeID, value);
+ }
///
/// Receive Pipe Payload
///
- public byte Payload { get => _nrf.ReadRxPayload(_pipeID); set => _nrf.SetRxPayload(_pipeID, value); }
+ public byte Payload
+ {
+ get => _nrf.ReadRxPayload(_pipeID);
+ set => _nrf.SetRxPayload(_pipeID, value);
+ }
///
/// Enable Pipe
///
- public bool Enable { get => _nrf.ReadRxPipe(_pipeID); set => _nrf.SetRxPipe(_pipeID, value); }
+ public bool Enable
+ {
+ get => _nrf.ReadRxPipe(_pipeID);
+ set => _nrf.SetRxPipe(_pipeID, value);
+ }
}
}
diff --git a/src/devices/Nrf24l01/samples/Program.cs b/src/devices/Nrf24l01/samples/Program.cs
index 7451c3d806..c2a9afb69f 100644
--- a/src/devices/Nrf24l01/samples/Program.cs
+++ b/src/devices/Nrf24l01/samples/Program.cs
@@ -23,8 +23,8 @@
using SpiDevice receiverDevice = SpiDevice.Create(receiverSettings);
// SPI Device, CE Pin, IRQ Pin, Receive Packet Size
-using Nrf24l01 sender = new Nrf24l01(senderDevice, 23, 24, 20);
-using Nrf24l01 receiver = new Nrf24l01(receiverDevice, 5, 6, 20);
+using Nrf24l01 sender = new (senderDevice, 23, 24, 20);
+using Nrf24l01 receiver = new (receiverDevice, 5, 6, 20);
// Set sender send address, receiver pipe0 address (Optional)
byte[] receiverAddress = Encoding.UTF8.GetBytes("NRF24");
sender.Address = receiverAddress;
diff --git a/src/devices/OneWire/OneWireBus.cs b/src/devices/OneWire/OneWireBus.cs
index fb419cbab2..3313017465 100644
--- a/src/devices/OneWire/OneWireBus.cs
+++ b/src/devices/OneWire/OneWireBus.cs
@@ -15,10 +15,7 @@ public partial class OneWireBus
/// Initializes a new instance of the class
///
/// The platform id of the 1-wire bus.
- public OneWireBus(string busId)
- {
- BusId = busId;
- }
+ public OneWireBus(string busId) => BusId = busId;
///
/// The 1-wire device id.
@@ -29,10 +26,7 @@ public OneWireBus(string busId)
/// Enumerate names of all 1-wire busses in the system.
///
/// A list of discovered bus ids.
- public static IEnumerable EnumerateBusIds()
- {
- return EnumerateBusIdsInternal();
- }
+ public static IEnumerable EnumerateBusIds() => EnumerateBusIdsInternal();
///
/// Enumerates all devices currently detected on this bus. Platform can update device list
@@ -54,19 +48,13 @@ public IEnumerable EnumerateDeviceIds(DeviceFamily family = DeviceFamily
/// Max number of devices to scan for before finishing. Use -1 for platform default.
/// Number of scans to do to find numDevices devices. Use -1 for platform default.
/// Task representing the async work.
- public Task ScanForDeviceChangesAsync(int numDevices = -1, int numScans = -1)
- {
- return ScanForDeviceChangesInternalAsync(this, numDevices, numScans);
- }
+ public Task ScanForDeviceChangesAsync(int numDevices = -1, int numScans = -1) => ScanForDeviceChangesInternalAsync(this, numDevices, numScans);
///
/// Start a new scan for device changes on the bus.
///
/// Max number of devices to scan for before finishing. Use -1 for platform default.
/// Number of scans to do to find numDevices devices. Use -1 for platform default.
- public void ScanForDeviceChanges(int numDevices = -1, int numScans = -1)
- {
- ScanForDeviceChangesInternal(this, numDevices, numScans);
- }
+ public void ScanForDeviceChanges(int numDevices = -1, int numScans = -1) => ScanForDeviceChangesInternal(this, numDevices, numScans);
}
}
diff --git a/src/devices/OneWire/samples/Program.cs b/src/devices/OneWire/samples/Program.cs
index 681acb218a..df19097503 100644
--- a/src/devices/OneWire/samples/Program.cs
+++ b/src/devices/OneWire/samples/Program.cs
@@ -20,18 +20,18 @@
else
{
// More advanced way, with rescanning the bus and iterating devices per 1-wire bus
- foreach (var busId in OneWireBus.EnumerateBusIds())
+ foreach (string busId in OneWireBus.EnumerateBusIds())
{
- var bus = new OneWireBus(busId);
+ OneWireBus bus = new (busId);
Console.WriteLine($"Found bus '{bus.BusId}', scanning for devices ...");
await bus.ScanForDeviceChangesAsync();
- foreach (var devId in bus.EnumerateDeviceIds())
+ foreach (string devId in bus.EnumerateDeviceIds())
{
- var dev = new OneWireDevice(busId, devId);
+ OneWireDevice dev = new (busId, devId);
Console.WriteLine($"Found family '{dev.Family}' device '{dev.DeviceId}' on '{bus.BusId}'");
if (OneWireThermometerDevice.IsCompatible(busId, devId))
{
- var devTemp = new OneWireThermometerDevice(busId, devId);
+ OneWireThermometerDevice devTemp = new (busId, devId);
Console.WriteLine("Temperature reported by device: " +
(await devTemp.ReadTemperatureAsync()).DegreesCelsius.ToString("F2") +
"\u00B0C");
diff --git a/src/devices/Pca95x4/Pca95x4.cs b/src/devices/Pca95x4/Pca95x4.cs
index 702495bb94..c5cc99488a 100644
--- a/src/devices/Pca95x4/Pca95x4.cs
+++ b/src/devices/Pca95x4/Pca95x4.cs
@@ -29,7 +29,7 @@ public Pca95x4(I2cDevice i2cDevice, int? interrupt = null, GpioController? gpioC
{
_i2cDevice = i2cDevice;
_interrupt = interrupt;
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
InitializeGpioController(gpioController);
}
@@ -63,7 +63,7 @@ private static bool GetBit(byte data, int bitNumber)
private void InitializeGpioController(GpioController? gpioController)
{
// Only need master controller if there is external pin provided.
- if (_interrupt != null)
+ if (_interrupt is object)
{
_controller = gpioController ?? new GpioController();
_controller.OpenPin((int)_interrupt, PinMode.Input);
@@ -100,12 +100,12 @@ public bool ReadBit(Register register, int bitNumber)
/// The pin value of the interrupt (INT).
public PinValue ReadInterrupt()
{
- if (_controller == null)
+ if (_controller is null)
{
throw new Exception("Master controller has not been initialized.");
}
- if (_interrupt == null)
+ if (_interrupt is null)
{
throw new Exception("INT pin has not been initialized.");
}
@@ -161,10 +161,7 @@ public void InvertInputRegisterPolarity(bool invert)
///
/// The Input Register bit number to invert.
/// Determines if the Input Register bit polarity is inverted.
- public void InvertInputRegisterBitPolarity(int bitNumber, bool invert)
- {
- WriteBit(Register.PolarityInversion, bitNumber, invert);
- }
+ public void InvertInputRegisterBitPolarity(int bitNumber, bool invert) => WriteBit(Register.PolarityInversion, bitNumber, invert);
///
public void Dispose()
diff --git a/src/devices/Pca9685/samples/Program.cs b/src/devices/Pca9685/samples/Program.cs
index 1076779b14..b7bcee222c 100644
--- a/src/devices/Pca9685/samples/Program.cs
+++ b/src/devices/Pca9685/samples/Program.cs
@@ -25,16 +25,18 @@
I2cConnectionSettings settings = new (busId, deviceAddress);
using I2cDevice device = I2cDevice.Create(settings);
-using Pca9685 pca9685 = new Pca9685(device);
+using Pca9685 pca9685 = new (device);
Console.WriteLine(
$"PCA9685 is ready on I2C bus {device.ConnectionSettings.BusId} with address {device.ConnectionSettings.DeviceAddress}");
Console.WriteLine($"PWM Frequency: {pca9685.PwmFrequency}Hz");
Console.WriteLine();
PrintHelp();
+#pragma warning disable SA1011
+
while (true)
{
- var command = Console.ReadLine()?.ToLower()?.Split(' ');
+ string[]? command = Console.ReadLine()?.ToLower()?.Split(' ');
if (command?[0] is not { Length: >0 })
{
return;
@@ -94,12 +96,10 @@
}
}
-ServoMotor CreateServo(Pca9685 pca9685, int channel)
-{
- return new ServoMotor(
+ServoMotor CreateServo(Pca9685 pca9685, int channel) =>
+ new ServoMotor(
pca9685.CreatePwmChannel(channel),
AngleRange, MinPulseWidthMicroseconds, MaxPulseWidthMicroseconds);
-}
void PrintServoDemoHelp()
{
@@ -111,7 +111,7 @@ void PrintServoDemoHelp()
void ServoDemo(Pca9685 pca9685, int channel)
{
- using var servo = CreateServo(pca9685, channel);
+ using ServoMotor servo = CreateServo(pca9685, channel);
PrintServoDemoHelp();
while (true)
diff --git a/src/devices/Pcx857x/Pcx857x.cs b/src/devices/Pcx857x/Pcx857x.cs
index dcb649b72d..bba8caf91b 100644
--- a/src/devices/Pcx857x/Pcx857x.cs
+++ b/src/devices/Pcx857x/Pcx857x.cs
@@ -44,7 +44,7 @@ public Pcx857x(I2cDevice device, int interrupt = -1, GpioController? gpioControl
{
Device = device ?? throw new ArgumentNullException(nameof(device));
_interrupt = interrupt;
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
if (_interrupt != -1)
{
@@ -165,12 +165,9 @@ public void Read(Span pinValues)
}
[MethodImpl(MethodImplOptions.NoInlining)]
- private void ThrowInvalidPin(string argumentName)
- {
- // This is a helper to allow the JIT to inline calling methods.
- // (Methods with throws cannot be inlined.)
- throw new ArgumentOutOfRangeException(argumentName, $"Pin numbers must be in the range of 0 to {PinCount - 1}.");
- }
+ // This is a helper to allow the JIT to inline calling methods.
+ // (Methods with throws cannot be inlined.)
+ private void ThrowInvalidPin(string argumentName) => throw new ArgumentOutOfRangeException(argumentName, $"Pin numbers must be in the range of 0 to {PinCount - 1}.");
private void ValidatePinNumber(int pinNumber)
{
diff --git a/src/devices/Pcx857x/tests/Pcx857xTest.cs b/src/devices/Pcx857x/tests/Pcx857xTest.cs
index f4523a73dd..084cd62674 100644
--- a/src/devices/Pcx857x/tests/Pcx857xTest.cs
+++ b/src/devices/Pcx857x/tests/Pcx857xTest.cs
@@ -91,10 +91,10 @@ public Pcx857xChipMock(int ports)
// Can't coalesce here https://github.com/dotnet/roslyn/issues/29927
public ReadOnlySpan LastReadBuffer =>
- _lastReadBuffer == null ? ReadOnlySpan.Empty : _lastReadBuffer;
+ _lastReadBuffer is null ? ReadOnlySpan.Empty : _lastReadBuffer;
public ReadOnlySpan LastWriteBuffer =>
- _lastWriteBuffer == null ? ReadOnlySpan.Empty : _lastWriteBuffer;
+ _lastWriteBuffer is null ? ReadOnlySpan.Empty : _lastWriteBuffer;
public void Read(Span buffer)
{
diff --git a/src/devices/Pn5180/Pn5180.cs b/src/devices/Pn5180/Pn5180.cs
index dae6746d5b..0f7d025e7d 100644
--- a/src/devices/Pn5180/Pn5180.cs
+++ b/src/devices/Pn5180/Pn5180.cs
@@ -55,8 +55,8 @@ public class Pn5180 : CardTransceiver, IDisposable
///
public LogLevel LogLevel
{
- get { return LogInfo.LogLevel; }
- set { LogInfo.LogLevel = value; }
+ get => LogInfo.LogLevel;
+ set => LogInfo.LogLevel = value;
}
///
@@ -64,8 +64,8 @@ public LogLevel LogLevel
///
public LogTo LogTo
{
- get { return LogInfo.LogTo; }
- set { LogInfo.LogTo = value; }
+ get => LogInfo.LogTo;
+ set => LogInfo.LogTo = value;
}
///
@@ -81,20 +81,20 @@ public Pn5180(SpiDevice spiDevice, int pinBusy, int pinNss, GpioController? gpio
{
if (pinBusy < 0)
{
- throw new ArgumentException($"{pinBusy} can't be negative, it has to be an actual real pin number");
+ throw new ArgumentException(nameof(pinBusy), "Value must be a legal pin number. cannot be negative.");
}
if (pinNss < 0)
{
- throw new ArgumentException($"{pinNss} can't be negative, it has to be an actual real pin number");
+ throw new ArgumentException(nameof(pinBusy), "Value must be a legal pin number. cannot be negative.");
}
LogLevel = logLevel;
LogInfo.Log($"Opening PN5180, pin busy: {pinBusy}, pin NSS: {pinNss}", LogLevel.Debug);
- _spiDevice = spiDevice;
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_gpioController = gpioController ?? new GpioController(PinNumberingScheme.Logical);
- _shouldDispose = shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
_pinBusy = pinBusy;
_pinNss = pinNss;
_gpioController.OpenPin(_pinBusy, PinMode.Input);
@@ -153,7 +153,7 @@ public bool GetIdentifier(Span outputIdentifier)
{
if (outputIdentifier.Length != 16)
{
- throw new ArgumentException($"Identifier must be 16 bytes long");
+ throw new ArgumentException(nameof(outputIdentifier), "Value must be 16 bytes long");
}
return ReadEeprom(EepromAddress.DieIdentifier, outputIdentifier);
@@ -168,7 +168,7 @@ public bool ReadAllEeprom(Span eeprom)
{
if (eeprom.Length != 255)
{
- throw new ArgumentException($"Size of EEPROM is 255 bytes, {nameof(eeprom)} must be 255 bytes");
+ throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must match.");
}
return ReadEeprom(EepromAddress.DieIdentifier, eeprom);
@@ -183,7 +183,7 @@ public bool WriteAllEeprom(Span eeprom)
{
if (eeprom.Length != 255)
{
- throw new ArgumentException($"Size of EEPROM is 255 bytes, {nameof(eeprom)} must be 255 bytes");
+ throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must match.");
}
return WriteEeprom(EepromAddress.DieIdentifier, eeprom);
@@ -199,7 +199,7 @@ public bool ReadEeprom(EepromAddress address, Span eeprom)
{
if ((byte)address + eeprom.Length > 255)
{
- throw new ArgumentException($"Size of EEPROM is 255 bytes, {nameof(address)} + {nameof(eeprom)} must be less than 255");
+ throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must 255 bytes or less.");
}
Span dumpEeprom = stackalloc byte[3];
@@ -238,7 +238,7 @@ public bool WriteEeprom(EepromAddress address, Span eeprom)
{
if ((byte)address + eeprom.Length > 255)
{
- throw new ArgumentException($"Size of EEPROM is 255 bytes, {nameof(address)} + {nameof(eeprom)} must be less than 255");
+ throw new ArgumentException(nameof(eeprom), "Size of EEPROM is 255 bytes. Value must 255 bytes or less.");
}
Span dumpEeprom = stackalloc byte[2 + eeprom.Length];
@@ -292,12 +292,12 @@ public bool SendDataToCard(Span toSend, int numberValidBitsLastByte = 8)
{
if (toSend.Length > 260)
{
- throw new ArgumentException($"Data to send can't be larger than 260 bytes");
+ throw new ArgumentException(nameof(toSend), "Data to send can't be larger than 260 bytes");
}
if ((numberValidBitsLastByte < 1) || (numberValidBitsLastByte > 8))
{
- throw new ArgumentException($"Number of valid bits in last byte can only be between 1 and 8");
+ throw new ArgumentException(nameof(numberValidBitsLastByte), "Number of valid bits in last byte can only be between 1 and 8");
}
Span sendData = stackalloc byte[2 + toSend.Length];
@@ -334,7 +334,7 @@ public bool ReadDataFromCard(Span toRead)
{
if (toRead.Length > 508)
{
- throw new ArgumentException($"Data to read can't be larger than 508 bytes");
+ throw new ArgumentException(nameof(toRead), "Data to read can't be larger than 508 bytes");
}
Span sendData = stackalloc byte[2];
@@ -477,9 +477,9 @@ private int TransceiveClassic(byte targetNumber, ReadOnlySpan dataToSend,
const int MaxTries = 5;
// All the type B protocol 14443-4 is from the ISO14443-4.pdf from ISO website
var card = _activeSelected.Where(m => m.Card.TargetNumber == targetNumber).FirstOrDefault();
- if (card == null)
+ if (card is null)
{
- throw new ArgumentException($"Device with target number {targetNumber} is not part of the list of selected devices. Card may have been removed.");
+ throw new ArgumentException(nameof(targetNumber), $"Device with target number {targetNumber} is not part of the list of selected devices. Card may have been removed.");
}
Span toSend = stackalloc byte[dataToSend.Length + 2];
@@ -660,7 +660,7 @@ private bool SendRBlock(byte targetNumber, RBlock ack, int blockNumber)
{
if (!((blockNumber == 1) || (blockNumber == 0)))
{
- throw new ArgumentException($"{nameof(SendRBlock)}, block number can be only 0 or 1");
+ throw new ArgumentException(nameof(blockNumber), "Value can be only 0 or 1.");
}
Span rBlock = new byte[2] { (byte)(0b1010_1010 | (byte)ack | blockNumber), targetNumber };
@@ -692,17 +692,17 @@ public bool MifareAuthenticate(Span key, MifareCardCommand mifareCommand,
LogInfo.Log($"{nameof(MifareAuthenticate)}: ", LogLevel.Debug);
if (key.Length != 6)
{
- throw new ArgumentException($"Key must be 6 bytes");
+ throw new ArgumentException(nameof(key), "Value must be 6 bytes.");
}
if (cardUid.Length != 4)
{
- throw new ArgumentException($"UID must be 4 bytes");
+ throw new ArgumentException(nameof(cardUid), "Value must be 4 bytes.");
}
if (!((mifareCommand == MifareCardCommand.AuthenticationA) || (mifareCommand == MifareCardCommand.AuthenticationB)))
{
- throw new ArgumentException($"{nameof(MifareCardCommand.AuthenticationA)} and {nameof(MifareCardCommand.AuthenticationB)} are the only supported commands");
+ throw new ArgumentException(nameof(mifareCommand), $"{nameof(MifareCardCommand.AuthenticationA)} and {nameof(MifareCardCommand.AuthenticationB)} are the only supported commands");
}
Span toAuthenticate = stackalloc byte[13];
@@ -819,7 +819,7 @@ private bool RetrieveRadioFrequencyConfiguration(byte config, Span configu
// Page 41 documentation PN5180A0XX-C3.pdf
if ((configuration.Length > 195) || (configuration.Length % 5 != 0) || (configuration.Length == 0))
{
- throw new ArgumentException($"Configuration buffer size must be a positive multiple of 5 and no larger than 195 bytes");
+ throw new ArgumentException(nameof(configuration), "Value must be a positive multiple of 5 and no larger than 195 bytes.");
}
Span rfConfig = stackalloc byte[2];
@@ -859,7 +859,7 @@ private bool UpdateRadioFrequenceConfiguration(byte config, Span configura
// Page 41 documentation PN5180A0XX-C3.pdf
if ((configuration.Length > 252) || (configuration.Length % 6 != 0) || (configuration.Length == 0))
{
- throw new ArgumentException($"Configuration buffer size must be a positive multiple of 6 and no larger than 252 bytes");
+ throw new ArgumentException(nameof(configuration), "Value must be a positive multiple of 6 and no larger than 252 bytes.");
}
Span rfConfig = stackalloc byte[1 + configuration.Length];
@@ -1345,7 +1345,6 @@ public bool CrcReceptionTransfer
crc &= ((config[0] & 0x01) == 0x01);
return crc;
}
-
set
{
if (value)
@@ -1370,7 +1369,7 @@ public void CalculateCrcB(ReadOnlySpan buffer, Span crc)
{
if (crc.Length != 2)
{
- throw new ArgumentException($"CRC B can only be 2 bytes long");
+ throw new ArgumentException(nameof(crc), $"Value must be 2 bytes.");
}
var crcRet = CalculateCrc(buffer, 0xFFFF);
@@ -1388,7 +1387,7 @@ public void CalculateCrcA(ReadOnlySpan buffer, Span crc)
{
if (crc.Length != 2)
{
- throw new ArgumentException($"CRC A can only be 2 bytes long");
+ throw new ArgumentException(nameof(crc), "Value must be 2 bytes.");
}
var crcRet = CalculateCrc(buffer, 0x6363);
@@ -1415,7 +1414,7 @@ private bool GetRxStatus(Span rxStatus)
LogInfo.Log($"{nameof(GetRxStatus)}", LogLevel.Debug);
if (rxStatus.Length != 4)
{
- throw new ArgumentException($"{nameof(rxStatus)} needs to be 4 bytes");
+ throw new ArgumentException(nameof(rxStatus), "Value must be 4 bytes.");
}
try
@@ -1440,7 +1439,7 @@ private bool GetIrqStatus(Span irqStatus)
LogInfo.Log($"{nameof(GetIrqStatus)}", LogLevel.Debug);
if (irqStatus.Length != 4)
{
- throw new ArgumentException($"{nameof(irqStatus)} needs to be 4 bytes");
+ throw new ArgumentException(nameof(irqStatus), "Value must be 4 bytes.");
}
try
@@ -1468,7 +1467,7 @@ private void SpiWriteRegister(Command command, Register register, ReadOnlySpan toSend = stackalloc byte[2 + data.Length];
@@ -1498,7 +1497,7 @@ private void SpiWriteRead(ReadOnlySpan toSend, Span toRead)
private void SpiWrite(ReadOnlySpan toSend)
{
// Both master and slave devices must operate with the same timing.The master device
- // always places data on the MOSI line a half cycle before the clock edge SCK, in order for
+ // always places data on the SDO line a half cycle before the clock edge SCK, in order for
// the slave device to latch the data.
// The BUSY line is used to indicate that the system is BUSY and cannot receive any data
// from a host.Recommendation for the BUSY line handling by the host:
@@ -1536,7 +1535,7 @@ private void SpiWrite(ReadOnlySpan toSend)
private void SpiRead(Span toRead)
{
// Both master and slave devices must operate with the same timing.The master device
- // always places data on the MOSI line a half cycle before the clock edge SCK, in order for
+ // always places data on the SDI line a half cycle before the clock edge SCK, in order for
// the slave device to latch the data.
// The BUSY line is used to indicate that the system is BUSY and cannot receive any data
// from a host.Recommendation for the BUSY line handling by the host:
diff --git a/src/devices/Pn5180/samples/Program.cs b/src/devices/Pn5180/samples/Program.cs
index 7f2303dac1..f24a9bf5c9 100644
--- a/src/devices/Pn5180/samples/Program.cs
+++ b/src/devices/Pn5180/samples/Program.cs
@@ -19,7 +19,7 @@
Console.WriteLine($"Choose the device you want to use");
Console.WriteLine($"1 for hardware Spi like on a Raspberry Pi");
Console.WriteLine($"2 for FT4222");
-var choice = Console.ReadKey().KeyChar;
+char choice = Console.ReadKey().KeyChar;
Console.WriteLine();
Console.WriteLine();
if (choice == '1')
@@ -115,9 +115,9 @@ Pn5180 Ft4222()
Ft4222Spi ftSpi = new Ft4222Spi(new SpiConnectionSettings(0, 1) { ClockFrequency = Pn5180.MaximumSpiClockFrequency, Mode = Pn5180.DefaultSpiMode, DataFlow = DataFlow.MsbFirst });
- GpioController gpioController = new GpioController(PinNumberingScheme.Board, new Ft4222Gpio());
+ using GpioController gpioController = new (PinNumberingScheme.Board, new Ft4222Gpio());
- // REset the device
+ // Reset the device
gpioController.OpenPin(0, PinMode.Output);
gpioController.Write(0, PinValue.Low);
Thread.Sleep(10);
@@ -344,7 +344,7 @@ void ReadAndDisplayData(CreditCard creditCard)
DisplayTags(creditCard.Tags, 0);
// Display Log Entries
var format = Tag.SearchTag(creditCard.Tags, 0x9F4F).FirstOrDefault();
- if (format != null)
+ if (format is object)
{
DisplayLogEntries(creditCard.LogEntries, format.Tags);
}
diff --git a/src/devices/Pn532/AsTarget/TargetFeliCaParameters.cs b/src/devices/Pn532/AsTarget/TargetFeliCaParameters.cs
index f4cce4c207..efd463361b 100644
--- a/src/devices/Pn532/AsTarget/TargetFeliCaParameters.cs
+++ b/src/devices/Pn532/AsTarget/TargetFeliCaParameters.cs
@@ -31,7 +31,7 @@ public byte[] NfcId2
{
if (value.Length != _nfcId2.Length)
{
- throw new ArgumentException($"{nameof(NfcId2)} can only be {_nfcId2.Length} byte long");
+ throw new ArgumentException(nameof(NfcId2), $"Value must be {_nfcId2.Length} bytes.");
}
value.CopyTo(_nfcId2, 0);
@@ -51,7 +51,7 @@ public byte[] Pad
{
if (value.Length != _pad.Length)
{
- throw new ArgumentException($"{nameof(Pad)} can only be {_pad.Length} byte long");
+ throw new ArgumentException(nameof(Pad), $"Value must be {_pad.Length} bytes.");
}
value.CopyTo(_pad, 0);
@@ -72,7 +72,7 @@ public byte[] SystemCode
{
if (value.Length != _systemCode.Length)
{
- throw new ArgumentException($"{nameof(SystemCode)} can only be {_systemCode.Length} byte long");
+ throw new ArgumentException(nameof(SystemCode), $"Value must be {_systemCode.Length} bytes.");
}
value.CopyTo(_systemCode, 0);
diff --git a/src/devices/Pn532/AsTarget/TargetMifareParameters.cs b/src/devices/Pn532/AsTarget/TargetMifareParameters.cs
index 964485fc9f..6dc2b8c748 100644
--- a/src/devices/Pn532/AsTarget/TargetMifareParameters.cs
+++ b/src/devices/Pn532/AsTarget/TargetMifareParameters.cs
@@ -20,15 +20,12 @@ public class TargetMifareParameters
///
public byte[] Atqa
{
- get
- {
- return _atqa;
- }
+ get => _atqa;
set
{
if (value.Length != _atqa.Length)
{
- throw new ArgumentException($"{nameof(Atqa)} has to be {_atqa.Length} byte long");
+ throw new ArgumentException(nameof(Atqa), $"Value must be {_atqa.Length} bytes.");
}
value.CopyTo(_atqa, 0);
@@ -42,15 +39,12 @@ public byte[] Atqa
///
public byte[] NfcId3
{
- get
- {
- return _nfcId3;
- }
+ get => _nfcId3;
set
{
if (value.Length != _nfcId3.Length)
{
- throw new ArgumentException($"{nameof(NfcId3)} has to be {_nfcId3.Length} byte long");
+ throw new ArgumentException(nameof(NfcId3), $"Value must be {_nfcId3.Length} bytes.");
}
value.CopyTo(_nfcId3, 0);
diff --git a/src/devices/Pn532/AsTarget/TargetPiccParameters.cs b/src/devices/Pn532/AsTarget/TargetPiccParameters.cs
index 29cdc35ba4..cdaac4dcc2 100644
--- a/src/devices/Pn532/AsTarget/TargetPiccParameters.cs
+++ b/src/devices/Pn532/AsTarget/TargetPiccParameters.cs
@@ -23,15 +23,12 @@ public class TargetPiccParameters
///
public byte[] NfcId3
{
- get
- {
- return _nfcId3;
- }
+ get => _nfcId3;
set
{
if (value.Length != _nfcId3.Length)
{
- throw new ArgumentException($"{nameof(NfcId3)} can only be {_nfcId3.Length} byte long");
+ throw new ArgumentException(nameof(NfcId3), $"Value must be {_nfcId3.Length} bytes.");
}
value.CopyTo(_nfcId3, 0);
@@ -44,15 +41,12 @@ public byte[] NfcId3
///
public byte[] GeneralTarget
{
- get
- {
- return _generalTarget;
- }
+ get => _generalTarget;
set
{
if (value.Length > 47)
{
- throw new ArgumentException($"{nameof(GeneralTarget)} can only be less than 47 byte long");
+ throw new ArgumentException(nameof(GeneralTarget), "Value must be less than 47 bytes.");
}
_generalTarget = new byte[value.Length];
@@ -65,15 +59,12 @@ public byte[] GeneralTarget
///
public byte[] HistoricalTarget
{
- get
- {
- return _historicalTarget;
- }
+ get => _historicalTarget;
set
{
if (value.Length > 48)
{
- throw new ArgumentException($"{nameof(HistoricalTarget)} can only be less than 48 byte long");
+ throw new ArgumentException(nameof(HistoricalTarget), "Value must be less than 48 bytes.");
}
_historicalTarget = new byte[value.Length];
diff --git a/src/devices/Pn532/Pn532.cs b/src/devices/Pn532/Pn532.cs
index 9a727e53f8..65dae2eb3b 100644
--- a/src/devices/Pn532/Pn532.cs
+++ b/src/devices/Pn532/Pn532.cs
@@ -73,8 +73,8 @@ public class Pn532 : CardTransceiver, IDisposable
///
public LogLevel LogLevel
{
- get { return LogInfo.LogLevel; }
- set { LogInfo.LogLevel = value; }
+ get => LogInfo.LogLevel;
+ set => LogInfo.LogLevel = value;
}
///
@@ -82,8 +82,8 @@ public LogLevel LogLevel
///
public LogTo LogTo
{
- get { return LogInfo.LogTo; }
- set { LogInfo.LogTo = value; }
+ get => LogInfo.LogTo;
+ set => LogInfo.LogTo = value;
}
///
@@ -158,7 +158,7 @@ public Pn532(string portName, LogLevel logLevel = LogLevel.None)
public Pn532(SpiDevice spiDevice, LogLevel logLevel = LogLevel.None)
{
LogLevel = logLevel;
- _spiDevice = spiDevice;
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_controller = new GpioController();
_controller.OpenPin(_pin, PinMode.Output);
_controller.Write(_pin, PinValue.High);
@@ -184,12 +184,12 @@ public Pn532(SpiDevice spiDevice, LogLevel logLevel = LogLevel.None)
///
/// Create a PN532 using I2C
///
- /// The I2C device
+ /// The I2C device
/// /// The log level
- public Pn532(I2cDevice i2CDevice, LogLevel logLevel = LogLevel.None)
+ public Pn532(I2cDevice i2cDevice, LogLevel logLevel = LogLevel.None)
{
LogLevel = logLevel;
- _i2cDevice = i2CDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
WakeUp();
bool ret = SetSecurityAccessModule();
LogInfo.Log($"Setting SAM changed: {ret}", LogLevel.Info);
@@ -391,11 +391,7 @@ public bool RunSelfTest(DiagnoseMode diagnoseMode)
///
public uint VirtualCardTimeout
{
- get
- {
- return _virtualCardTimeout * 50;
- }
-
+ get => _virtualCardTimeout * 50;
set
{
// Timeout defines the time-out only in Virtual card configuration (Mode = 0x02).
@@ -405,7 +401,7 @@ public uint VirtualCardTimeout
// The maximum value for the timeout is 12.75 sec (Timeout = 0xFF).
if (value / 50 > 0xFF)
{
- throw new ArgumentException($"{nameof(VirtualCardTimeout)} can't be more than 12750 milliseconds.");
+ throw new ArgumentException(nameof(VirtualCardTimeout), "Value must be 12750 milliseconds or less.");
}
_virtualCardTimeout = value / 50;
@@ -419,11 +415,7 @@ public uint VirtualCardTimeout
///
public SecurityAccessModuleMode SecurityAccessModuleMode
{
- get
- {
- return _securityAccessModuleMode;
- }
-
+ get => _securityAccessModuleMode;
set
{
bool ret = SetSecurityAccessModule();
@@ -481,11 +473,7 @@ private bool IsPn532()
///
public ParametersFlags ParametersFlags
{
- get
- {
- return _parametersFlags;
- }
-
+ get => _parametersFlags;
set
{
if (SetParameters(value))
@@ -822,12 +810,7 @@ public override int Transceive(byte targetNumber, ReadOnlySpan dataToSend,
/// A raw byte array containing the number of cards, the card type and the raw data. Null if nothing has been polled
public byte[]? AutoPoll(byte numberPolling, ushort periodMilliSecond, PollingType[] pollingType)
{
- if (pollingType == null)
- {
- return null;
- }
-
- if (pollingType.Length > 15)
+ if (pollingType is not { Length: >15 })
{
return null;
}
@@ -975,81 +958,65 @@ public bool WriteDataAsTarget(ReadOnlySpan dataToSend)
///
/// Radio Frequency Field Mode
/// True is success
- public bool SetRfField(RfFieldMode rfFieldMode)
- {
- return SetRfConfiguration(RfConfigurationMode.RfField, new byte[1] { (byte)rfFieldMode });
- }
+ public bool SetRfField(RfFieldMode rfFieldMode) =>
+ SetRfConfiguration(RfConfigurationMode.RfField, new byte[1] { (byte)rfFieldMode });
///
/// Set the Various Timing Mode
///
/// Various Timing Mode
/// True is success
- public bool SetVariousTimings(VariousTimingsMode variousTimingsMode)
- {
- return SetRfConfiguration(RfConfigurationMode.VariousTimings, variousTimingsMode.Serialize());
- }
+ public bool SetVariousTimings(VariousTimingsMode variousTimingsMode) =>
+ SetRfConfiguration(RfConfigurationMode.VariousTimings, variousTimingsMode.Serialize());
///
/// Set the Maximum Retry in the 2 WriteRead modes
///
/// The number of retries
/// True is success
- public bool SetMaxRetryWriteRead(byte numberRetries = 0x00)
- {
- return SetRfConfiguration(RfConfigurationMode.MaxRetryCOM, new byte[1] { numberRetries });
- }
+ public bool SetMaxRetryWriteRead(byte numberRetries = 0x00) =>
+ SetRfConfiguration(RfConfigurationMode.MaxRetryCOM, new byte[1] { numberRetries });
///
/// Set the MAximu Retries during the various initialization modes
///
/// Retry modes
/// True is success
- public bool SetMaxRetriesInitialization(MaxRetriesMode maxRetriesMode)
- {
- return SetRfConfiguration(RfConfigurationMode.MaxRetries, maxRetriesMode.Serialize());
- }
+ public bool SetMaxRetriesInitialization(MaxRetriesMode maxRetriesMode) =>
+ SetRfConfiguration(RfConfigurationMode.MaxRetries, maxRetriesMode.Serialize());
///
/// Set the specific 106 kbps card Type A modes
///
/// The mode settings
/// True is success
- public bool SetAnalog106kbpsTypeA(Analog106kbpsTypeAMode analog106Kbps)
- {
- return SetRfConfiguration(RfConfigurationMode.AnalogSettingsB106kbpsTypeA, analog106Kbps.Serialize());
- }
+ public bool SetAnalog106kbpsTypeA(Analog106kbpsTypeAMode analog106Kbps) =>
+ SetRfConfiguration(RfConfigurationMode.AnalogSettingsB106kbpsTypeA, analog106Kbps.Serialize());
///
/// Set the specific 212 424 kbps card modes
///
/// The mode settings
/// True is success
- public bool SetAnalog212_424Kbps(Analog212_424kbpsMode analog212_424)
- {
- return SetRfConfiguration(RfConfigurationMode.AnalogSettingsB212_424kbps, analog212_424.Serialize());
- }
+ public bool SetAnalog212_424Kbps(Analog212_424kbpsMode analog212_424) =>
+ SetRfConfiguration(RfConfigurationMode.AnalogSettingsB212_424kbps, analog212_424.Serialize());
///
/// Set the specific 106 kbps card Type B modes
///
/// The mode settings
/// True is success
- public bool SetAnalogTypeB(AnalogSettingsTypeBMode analogSettings)
- {
- return SetRfConfiguration(RfConfigurationMode.AnalogSettingsTypeB, analogSettings.Serialize());
- }
+ public bool SetAnalogTypeB(AnalogSettingsTypeBMode analogSettings) =>
+ SetRfConfiguration(RfConfigurationMode.AnalogSettingsTypeB, analogSettings.Serialize());
///
/// Configure analog mode
///
/// Settings
/// True is success
- public bool SetAnalog212_424_848kbps(Analog212_424_848kbpsMode analog212_424_848Kbps)
- {
- return SetRfConfiguration(RfConfigurationMode.AnalogSettingsB212_424_848ISO_IEC14443_4,
+ public bool SetAnalog212_424_848kbps(Analog212_424_848kbpsMode analog212_424_848Kbps) =>
+ SetRfConfiguration(RfConfigurationMode.AnalogSettingsB212_424_848ISO_IEC14443_4,
analog212_424_848Kbps.Serialize());
- }
private bool SetRfConfiguration(RfConfigurationMode rfConfigurationMode, byte[] configurationData)
{
@@ -1159,10 +1126,8 @@ public bool WriteRegisterSfr(SfrRegister[] registers, Span registerValue)
/// The register to write
/// The value of the register
/// True if success
- public bool WriteRegister(ushort register, byte registerValue)
- {
- return WriteRegister(new ushort[] { register }, new byte[] { registerValue });
- }
+ public bool WriteRegister(ushort register, byte registerValue) =>
+ WriteRegister(new ushort[] { register }, new byte[] { registerValue });
///
/// Write an array of register
@@ -1290,7 +1255,7 @@ public bool PowerDown(WakeUpEnable wakeUpEnable)
///
public void WakeUp()
{
- if (_serialPort != null)
+ if (_serialPort is object)
{
// Wakeup the device send the magic 0x55 with a long preamble and SAM Command
LogInfo.Log("Waking up device", LogLevel.Debug);
@@ -1322,7 +1287,7 @@ public void WakeUp()
_spiDevice.Write(wakeUp);
}
- else if (_i2cDevice != null)
+ else if (_i2cDevice is object)
{
LogInfo.Log("Waking up PN522 on I2C mode", LogLevel.Debug);
byte[] samMessage = CreateWriteMessage(CommandSet.SAMConfiguration,
@@ -1373,7 +1338,7 @@ public void WakeUp()
/// True if success
public bool SetSerialBaudRate(BaudRate baudRate)
{
- if (_serialPort == null)
+ if (_serialPort is null)
{
return false;
}
@@ -1443,7 +1408,7 @@ public bool SetSerialBaudRate(BaudRate baudRate)
private void DumpSerial()
{
- if (_serialPort != null)
+ if (_serialPort is object)
{
LogInfo.Log($"Serial Available bytes and dumped: {_serialPort.BytesToRead}", LogLevel.Debug);
while (_serialPort.BytesToRead > 0)
@@ -1463,17 +1428,17 @@ private int WriteCommand(CommandSet commandSet, ReadOnlySpan writeData)
LogInfo.Log(
$"{nameof(WriteCommand)}: {nameof(CommandSet)} {commandSet} Bytes to send: {BitConverter.ToString(writeData.ToArray())}",
LogLevel.Debug);
- if (_spiDevice != null)
+ if (_spiDevice is object)
{
return WriteCommandSPI(commandSet, writeData);
}
- if (_i2cDevice != null)
+ if (_i2cDevice is object)
{
return WriteCommandI2C(commandSet, writeData);
}
- if (_serialPort != null)
+ if (_serialPort is object)
{
return WriteCommandSerial(commandSet, writeData);
}
@@ -2064,13 +2029,13 @@ private bool CheckAckFrame()
_spiDevice.Read(ackReceived);
_controller.Write(_pin, PinValue.High);
}
- else if (_i2cDevice != null)
+ else if (_i2cDevice is object)
{
Span i2cackReceived = stackalloc byte[7];
_i2cDevice.Read(i2cackReceived);
i2cackReceived.Slice(1).CopyTo(ackReceived);
}
- else if (_serialPort != null)
+ else if (_serialPort is object)
{
try
{
@@ -2099,7 +2064,7 @@ private bool IsReady()
ret = _spiDevice.ReadByte();
_controller.Write(_pin, PinValue.High);
}
- else if (_i2cDevice != null)
+ else if (_i2cDevice is object)
{
try
{
@@ -2111,7 +2076,7 @@ private bool IsReady()
}
}
- else if (_serialPort != null)
+ else if (_serialPort is object)
{
return _serialPort.BytesToRead > 0;
}
diff --git a/src/devices/Pn532/README.md b/src/devices/Pn532/README.md
index fe691e73fc..44c38e3009 100644
--- a/src/devices/Pn532/README.md
+++ b/src/devices/Pn532/README.md
@@ -27,13 +27,13 @@ byte[] retData = null;
while ((!Console.KeyAvailable))
{
retData = pn532.ListPassiveTarget(MaxTarget.One, TargetBaudRate.B106kbpsTypeA);
- if (retData != null)
+ if (retData is object)
break;
// Give time to PN532 to process
Thread.Sleep(200);
}
-if (retData == null)
+if (retData is null)
return;
// You need to remove the first element at it's the number of tags read
@@ -48,7 +48,7 @@ byte[] retData = null;
while ((!Console.KeyAvailable))
{
retData = pn532.AutoPoll(5, 300, new PollingType[] { PollingType.Passive106kbpsISO144443_4B });
- if (retData != null)
+ if (retData is object)
{
if (retData.Length >= 3)
break;
@@ -58,7 +58,7 @@ while ((!Console.KeyAvailable))
Thread.Sleep(200);
}
-if (retData == null)
+if (retData is null)
return;
// Check how many tags and the type
@@ -78,10 +78,10 @@ PN532 implement a ReadWrite function that allows to use a high level Mifare card
Once detected and selected like in the previous example, this fully dump the content of a classical Mifare 1K card:
```csharp
-if (decrypted != null)
+if (decrypted is object)
{
Console.WriteLine($"Tg: {decrypted.TargetNumber}, ATQA: {decrypted.Atqa} SAK: {decrypted.Sak}, NFCID: {BitConverter.ToString(decrypted.NfcId)}");
- if (decrypted.Ats != null)
+ if (decrypted.Ats is object)
Console.WriteLine($", ATS: {BitConverter.ToString(decrypted.Ats)}");
MifareCard mifareCard = new MifareCard(pn532, decrypted.TargetNumber) { BlockNumber = 0, Command = MifareCardCommand.AuthenticationA };
@@ -148,13 +148,13 @@ static void AsTarget(Pn532 pn532)
new TargetMifareParameters() { Atqa = new byte[] { 0x08, 0x00 }, Sak = 0x60 },
new TargetFeliCaParameters() { NfcId2 = new byte[] { 0x01, 0xFE, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7 }, Pad = new byte[] { 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7 } },
new TargetPiccParameters() { NfcId3 = new byte[] { 0xAA, 0x99, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, GeneralTarget = new byte[0], HistoricalTarget = new byte[0] });
- if (modeInitialized != null)
+ if (modeInitialized is object)
break;
// Give time to PN532 to process
Thread.Sleep(200);
}
- if (modeInitialized == null)
+ if (modeInitialized is null)
return;
Console.WriteLine($"PN532 as a target: ISDep: {modeInitialized.IsDep}, IsPicc {modeInitialized.IsISO14443_4Picc}, {modeInitialized.TargetBaudRate}, {modeInitialized.TargetFramingType}");
diff --git a/src/devices/Pn532/samples/Program.cs b/src/devices/Pn532/samples/Program.cs
index 84eb61088d..1f3a245652 100644
--- a/src/devices/Pn532/samples/Program.cs
+++ b/src/devices/Pn532/samples/Program.cs
@@ -24,8 +24,7 @@
pn532.LogLevel = LogLevel.None;
}
-var version = pn532.FirmwareVersion;
-if (version != null)
+if (pn532.FirmwareVersion is FirmwareVersion version)
{
Console.WriteLine(
$"Is it a PN532!: {version.IsPn532}, Version: {version.Version}, Version supported: {version.VersionSupported}");
@@ -79,7 +78,7 @@ void ReadMiFare(Pn532 pn532)
while ((!Console.KeyAvailable))
{
retData = pn532.ListPassiveTarget(MaxTarget.One, TargetBaudRate.B106kbpsTypeA);
- if (retData != null)
+ if (retData is object)
{
break;
}
@@ -88,22 +87,22 @@ void ReadMiFare(Pn532 pn532)
Thread.Sleep(200);
}
- if (retData == null)
+ if (retData is null)
{
return;
}
var decrypted = pn532.TryDecode106kbpsTypeA(retData.AsSpan().Slice(1));
- if (decrypted != null)
+ if (decrypted is object)
{
Console.WriteLine(
$"Tg: {decrypted.TargetNumber}, ATQA: {decrypted.Atqa} SAK: {decrypted.Sak}, NFCID: {BitConverter.ToString(decrypted.NfcId)}");
- if (decrypted.Ats != null)
+ if (decrypted.Ats is object)
{
Console.WriteLine($", ATS: {BitConverter.ToString(decrypted.Ats)}");
}
- MifareCard mifareCard = new MifareCard(pn532, decrypted.TargetNumber)
+ MifareCard mifareCard = new (pn532, decrypted.TargetNumber)
{
BlockNumber = 0, Command = MifareCardCommand.AuthenticationA
};
@@ -203,7 +202,7 @@ void ReadCreditCard(Pn532 pn532)
while ((!Console.KeyAvailable))
{
retData = pn532.AutoPoll(5, 300, new PollingType[] { PollingType.Passive106kbpsISO144443_4B });
- if (retData != null)
+ if (retData is object)
{
if (retData.Length >= 3)
{
@@ -215,7 +214,7 @@ void ReadCreditCard(Pn532 pn532)
Thread.Sleep(200);
}
- if (retData == null)
+ if (retData is null)
{
return;
}
@@ -223,7 +222,7 @@ void ReadCreditCard(Pn532 pn532)
// Check how many tags and the type
Console.WriteLine($"Num tags: {retData[0]}, Type: {(PollingType)retData[1]}");
var decrypted = pn532.TryDecodeData106kbpsTypeB(retData.AsSpan().Slice(3));
- if (decrypted != null)
+ if (decrypted is object)
{
Console.WriteLine(
$"{decrypted.TargetNumber}, Serial: {BitConverter.ToString(decrypted.NfcId)}, App Data: {BitConverter.ToString(decrypted.ApplicationData)}, " +
diff --git a/src/devices/README.md b/src/devices/README.md
index b56a8dcaee..45830e1c31 100755
--- a/src/devices/README.md
+++ b/src/devices/README.md
@@ -371,7 +371,7 @@ private int _pinToUse;
public MyBinding(int pinToUse, GpioController controller = null, PinNumberingScheme pinNumberingScheme = PinNumberingScheme.Logical, bool shouldDispose = true)
{
- _shouldDispose = gpioController == null || shouldDispose;
+ _shouldDispose = gpioController is null || shouldDispose;
_controller = gpioController ?? new GpioController(pinNumberingScheme);
_pinToUse = pinToUse;
_controller.OpenPin(_pinToUse);
diff --git a/src/devices/RGBLedMatrix/RgbLedMatrix.cs b/src/devices/RGBLedMatrix/RgbLedMatrix.cs
index ed2555b3e3..cc84254ef1 100644
--- a/src/devices/RGBLedMatrix/RgbLedMatrix.cs
+++ b/src/devices/RGBLedMatrix/RgbLedMatrix.cs
@@ -234,10 +234,8 @@ public void FillRectangle(int x, int y, int width, int height, byte red, byte gr
/// blue color value
/// true if to draw on back buffer, false to draw on the forground buffer
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public unsafe void Fill(byte red, byte green, byte blue, bool backBuffer = false)
- {
+ public unsafe void Fill(byte red, byte green, byte blue, bool backBuffer = false) =>
FillRectangle(0, 0, Width, Height, red, green, blue, backBuffer);
- }
///
/// Set color of specific pixel on the forground buffer display
@@ -248,10 +246,8 @@ public unsafe void Fill(byte red, byte green, byte blue, bool backBuffer = false
/// green color value
/// blue color value
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void SetPixel(int column, int row, byte red, byte green, byte blue)
- {
+ public void SetPixel(int column, int row, byte red, byte green, byte blue) =>
SetPixel(column, row, red, green, blue, _colorsBuffer);
- }
///
/// Set color of specific pixel on the background buffer display
@@ -262,10 +258,8 @@ public void SetPixel(int column, int row, byte red, byte green, byte blue)
/// green color value
/// blue color value
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public void SetBackBufferPixel(int column, int row, byte red, byte green, byte blue)
- {
+ public void SetBackBufferPixel(int column, int row, byte red, byte green, byte blue) =>
SetPixel(column, row, red, green, blue, _colorsBackBuffer);
- }
private void SetPixel(int column, int row, byte red, byte green, byte blue, byte[] colorsBuffer)
{
@@ -350,7 +344,7 @@ public void SwapBuffers()
///
public void Dispose()
{
- if (_controller != null)
+ if (_controller is object)
{
StopRendering();
diff --git a/src/devices/RGBLedMatrix/samples/Program.cs b/src/devices/RGBLedMatrix/samples/Program.cs
index 00ee6ca32b..39b5a56660 100644
--- a/src/devices/RGBLedMatrix/samples/Program.cs
+++ b/src/devices/RGBLedMatrix/samples/Program.cs
@@ -22,18 +22,18 @@
CityData[] citiesData = new CityData[]
{
- new CityData("New York", "US", "America/New_York"),
- new CityData("Redmond", "US", "America/Los_Angeles"),
- new CityData("Toronto", "CA", "America/Toronto"),
- new CityData("Mexico", "MX", "America/Mexico_City"),
- new CityData("Madrid", "ES", "Europe/Madrid"),
- new CityData("London", "UK", "Europe/London"),
- new CityData("Paris", "FR", "Europe/Paris"),
- new CityData("Rome", "IT", "Europe/Rome"),
- new CityData("Moscow", "RU", "Europe/Moscow"),
- new CityData("Casablanca", "MA", "Africa/Casablanca"),
- new CityData("Cairo", "EG", "Africa/Cairo"),
- new CityData("Riyadh", "SA", "Asia/Riyadh")
+ new ("New York", "US", "America/New_York"),
+ new ("Redmond", "US", "America/Los_Angeles"),
+ new ("Toronto", "CA", "America/Toronto"),
+ new ("Mexico", "MX", "America/Mexico_City"),
+ new ("Madrid", "ES", "Europe/Madrid"),
+ new ("London", "UK", "Europe/London"),
+ new ("Paris", "FR", "Europe/Paris"),
+ new ("Rome", "IT", "Europe/Rome"),
+ new ("Moscow", "RU", "Europe/Moscow"),
+ new ("Casablanca", "MA", "Africa/Casablanca"),
+ new ("Cairo", "EG", "Africa/Cairo"),
+ new ("Riyadh", "SA", "Asia/Riyadh")
};
Console.WriteLine($"Hello Matrix World!");
@@ -650,17 +650,4 @@ void ScrollText(
}
}
-internal struct CityData
-{
- public CityData(string city, string countryCode, string zoneId)
- {
- City = city;
- CountryCode = countryCode;
- ZoneId = zoneId;
-
- }
-
- public string City { get; }
- public string CountryCode { get; }
- public string ZoneId { get; }
-}
+internal record CityData(string City, string CountryCode, string ZoneId);
diff --git a/src/devices/RadioReceiver/Devices/Tea5767/Tea5767.cs b/src/devices/RadioReceiver/Devices/Tea5767/Tea5767.cs
index a9028c4c17..856419210d 100644
--- a/src/devices/RadioReceiver/Devices/Tea5767/Tea5767.cs
+++ b/src/devices/RadioReceiver/Devices/Tea5767/Tea5767.cs
@@ -50,7 +50,7 @@ public class Tea5767 : RadioReceiverBase
/// FM frequency.
public Tea5767(I2cDevice i2cDevice, FrequencyRange frequencyRange, Frequency frequency)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
FrequencyRange = frequencyRange;
Frequency = frequency;
@@ -260,9 +260,7 @@ private byte[] ReadRegisters()
return readBuffer.ToArray();
}
- private void SaveRegisters()
- {
+ private void SaveRegisters() =>
_i2cDevice.Write(_registers);
- }
}
}
diff --git a/src/devices/RadioTransmitter/Devices/Kt0803/Kt0803.cs b/src/devices/RadioTransmitter/Devices/Kt0803/Kt0803.cs
index 68e6c7d82c..08539cbef4 100644
--- a/src/devices/RadioTransmitter/Devices/Kt0803/Kt0803.cs
+++ b/src/devices/RadioTransmitter/Devices/Kt0803/Kt0803.cs
@@ -78,7 +78,7 @@ public Region Region
public Kt0803(I2cDevice i2cDevice, double frequency, Region region,
TransmissionPower power = TransmissionPower.Power108dBuV, PgaGain pga = PgaGain.Pga00dB)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
Frequency = frequency;
TransmissionPower = power;
PgaGain = pga;
diff --git a/src/devices/RadioTransmitter/samples/Program.cs b/src/devices/RadioTransmitter/samples/Program.cs
index b16016b956..318307d2a6 100644
--- a/src/devices/RadioTransmitter/samples/Program.cs
+++ b/src/devices/RadioTransmitter/samples/Program.cs
@@ -8,6 +8,6 @@
I2cConnectionSettings settings = new (1, Kt0803.DefaultI2cAddress);
using I2cDevice device = I2cDevice.Create(settings);
-using Kt0803 radio = new Kt0803(device, 106.6, Region.China);
+using Kt0803 radio = new (device, 106.6, Region.China);
Console.WriteLine($"The radio is running on FM {radio.Frequency.ToString("0.0")}MHz");
Console.ReadKey();
diff --git a/src/devices/Rtc/Devices/Ds1307/Ds1307.cs b/src/devices/Rtc/Devices/Ds1307/Ds1307.cs
index b9ddd42a28..9b630da395 100644
--- a/src/devices/Rtc/Devices/Ds1307/Ds1307.cs
+++ b/src/devices/Rtc/Devices/Ds1307/Ds1307.cs
@@ -25,7 +25,7 @@ public class Ds1307 : RtcBase
/// The I2C device used for communication.
public Ds1307(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
}
///
diff --git a/src/devices/Rtc/Devices/Ds3231/Ds3231.cs b/src/devices/Rtc/Devices/Ds3231/Ds3231.cs
index fbe2ae9a21..789fba0c8b 100644
--- a/src/devices/Rtc/Devices/Ds3231/Ds3231.cs
+++ b/src/devices/Rtc/Devices/Ds3231/Ds3231.cs
@@ -31,7 +31,7 @@ public class Ds3231 : RtcBase
/// The I2C device used for communication.
public Ds3231(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
}
///
diff --git a/src/devices/Rtc/Devices/Pcf8563/Pcf8563.cs b/src/devices/Rtc/Devices/Pcf8563/Pcf8563.cs
index 8954c23961..a1dc14e298 100644
--- a/src/devices/Rtc/Devices/Pcf8563/Pcf8563.cs
+++ b/src/devices/Rtc/Devices/Pcf8563/Pcf8563.cs
@@ -25,7 +25,7 @@ public class Pcf8563 : RtcBase
/// The I2C device used for communication.
public Pcf8563(I2cDevice i2cDevice)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
// Set "Normal Mode"
Span ctrl1Config = stackalloc byte[]
diff --git a/src/devices/Rtc/RtcBase.cs b/src/devices/Rtc/RtcBase.cs
index 9f00571b7a..701a5b2de3 100644
--- a/src/devices/Rtc/RtcBase.cs
+++ b/src/devices/Rtc/RtcBase.cs
@@ -13,7 +13,11 @@ public abstract class RtcBase : IDisposable
///
/// The Device's
///
- public virtual DateTime DateTime { get => ReadTime(); set => SetTime(value); }
+ public virtual DateTime DateTime
+ {
+ get => ReadTime();
+ set => SetTime(value);
+ }
///
/// Set the device time
diff --git a/src/devices/Rtc/samples/Program.cs b/src/devices/Rtc/samples/Program.cs
index bcf57c1422..bdf1535988 100644
--- a/src/devices/Rtc/samples/Program.cs
+++ b/src/devices/Rtc/samples/Program.cs
@@ -7,7 +7,7 @@
I2cConnectionSettings settings = new (1, Ds3231.DefaultI2cAddress);
I2cDevice device = I2cDevice.Create(settings);
-using Ds3231 rtc = new Ds3231(device);
+using Ds3231 rtc = new (device);
// set time
rtc.DateTime = DateTime.Now;
diff --git a/src/devices/Seesaw/SeesawBase.cs b/src/devices/Seesaw/SeesawBase.cs
index f77a09abc4..c7a6724bc0 100644
--- a/src/devices/Seesaw/SeesawBase.cs
+++ b/src/devices/Seesaw/SeesawBase.cs
@@ -30,7 +30,7 @@ public partial class Seesaw : IDisposable
/// will be disposed when the along with the SeeSaw device
public Seesaw(I2cDevice i2cDevice)
{
- I2cDevice = i2cDevice;
+ I2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
Initialize(i2cDevice);
}
@@ -55,10 +55,8 @@ public Seesaw(I2cDevice i2cDevice)
///
/// Performs a soft reset of the SeeSaw module.
///
- public void SoftwareReset()
- {
+ public void SoftwareReset() =>
WriteByte(SeesawModule.Status, SeesawFunction.StatusSwrst, 0xFF);
- }
///
/// Initializes the Seesaw device.
diff --git a/src/devices/Seesaw/samples/Seesaw.Sample.BlinkingLights.cs b/src/devices/Seesaw/samples/Seesaw.Sample.BlinkingLights.cs
index 271a8148c3..aa7c31d786 100644
--- a/src/devices/Seesaw/samples/Seesaw.Sample.BlinkingLights.cs
+++ b/src/devices/Seesaw/samples/Seesaw.Sample.BlinkingLights.cs
@@ -21,7 +21,7 @@
int sleep = initialSleep;
Volume? volume = null;
-TimeEnvelope[] envelopes = new TimeEnvelope[] { new TimeEnvelope(1000), new TimeEnvelope(1000), new TimeEnvelope(4000) };
+TimeEnvelope[] envelopes = new TimeEnvelope[] { new (1000), new (1000), new (4000) };
Console.WriteLine("Hello World!");
@@ -83,7 +83,7 @@
}
// behavior for buttonOne
- if (volume != null)
+ if (volume is object)
{
var update = true;
var value = 0;
diff --git a/src/devices/Seesaw/samples/Seesaw.Sample.Capabilities.cs b/src/devices/Seesaw/samples/Seesaw.Sample.Capabilities.cs
index 15989ced28..16a312f148 100644
--- a/src/devices/Seesaw/samples/Seesaw.Sample.Capabilities.cs
+++ b/src/devices/Seesaw/samples/Seesaw.Sample.Capabilities.cs
@@ -10,7 +10,7 @@
const byte AdafruitSeesawBreakoutI2cBus = 0x1;
using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(AdafruitSeesawBreakoutI2cBus, AdafruitSeesawBreakoutI2cAddress));
-using Seesaw ssDevice = new Seesaw(i2cDevice);
+using Seesaw ssDevice = new (i2cDevice);
Console.WriteLine();
Console.WriteLine($"Seesaw Version: {ssDevice.Version}");
Console.WriteLine();
diff --git a/src/devices/Seesaw/samples/Seesaw.Sample.SoilSensor.cs b/src/devices/Seesaw/samples/Seesaw.Sample.SoilSensor.cs
index 3452809d4f..5fefb9bb5a 100644
--- a/src/devices/Seesaw/samples/Seesaw.Sample.SoilSensor.cs
+++ b/src/devices/Seesaw/samples/Seesaw.Sample.SoilSensor.cs
@@ -10,7 +10,7 @@
const byte AdafruitSeesawSoilSensorI2cBus = 0x1;
using I2cDevice i2cDevice = I2cDevice.Create(new I2cConnectionSettings(AdafruitSeesawSoilSensorI2cBus, AdafruitSeesawSoilSensorI2cAddress));
-using Seesaw ssDevice = new Seesaw(i2cDevice);
+using Seesaw ssDevice = new (i2cDevice);
while (true)
{
Console.WriteLine($"Temperature: {ssDevice.GetTemperature()}'C");
diff --git a/src/devices/Seesaw/samples/Volume.cs b/src/devices/Seesaw/samples/Volume.cs
index 13101c85fe..bd8bb39478 100644
--- a/src/devices/Seesaw/samples/Volume.cs
+++ b/src/devices/Seesaw/samples/Volume.cs
@@ -6,10 +6,8 @@
internal class Volume
{
- public static Volume EnableVolume(Seesaw seesawDevice)
- {
- return new Volume(seesawDevice);
- }
+ public static Volume EnableVolume(Seesaw seesawDevice) =>
+ new Volume(seesawDevice);
private Seesaw _seesawDevice;
private int _lastValue = 0;
@@ -28,10 +26,8 @@ public int GetVolumeValue()
return (int)value;
}
- private void Init()
- {
+ private void Init() =>
_lastValue = GetVolumeValue();
- }
public (bool update, int value) GetSleepForVolume(int sleep)
{
diff --git a/src/devices/SenseHat/SenseHatAccelerometerAndGyroscope.cs b/src/devices/SenseHat/SenseHatAccelerometerAndGyroscope.cs
index 363f13e7ed..74938a2c25 100644
--- a/src/devices/SenseHat/SenseHatAccelerometerAndGyroscope.cs
+++ b/src/devices/SenseHat/SenseHatAccelerometerAndGyroscope.cs
@@ -32,7 +32,7 @@ public SenseHatAccelerometerAndGyroscope(
private static I2cDevice CreateDefaultI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
}
diff --git a/src/devices/SenseHat/SenseHatJoystick.cs b/src/devices/SenseHat/SenseHatJoystick.cs
index affef5d3e7..4987553752 100644
--- a/src/devices/SenseHat/SenseHatJoystick.cs
+++ b/src/devices/SenseHat/SenseHatJoystick.cs
@@ -69,7 +69,7 @@ public void Read()
private static I2cDevice CreateDefaultI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
diff --git a/src/devices/SenseHat/SenseHatLedMatrixI2c.cs b/src/devices/SenseHat/SenseHatLedMatrixI2c.cs
index 7acc81b653..e761b93157 100644
--- a/src/devices/SenseHat/SenseHatLedMatrixI2c.cs
+++ b/src/devices/SenseHat/SenseHatLedMatrixI2c.cs
@@ -40,7 +40,7 @@ public override void Write(ReadOnlySpan colors)
{
if (colors.Length != NumberOfPixels)
{
- throw new ArgumentException($"`{nameof(colors)}` must have exactly {NumberOfPixels} elements.");
+ throw new ArgumentException(nameof(colors), $"Value must be {NumberOfPixels} elements. Length: {nameof(colors)}.");
}
Span buffer = stackalloc byte[FrameBufferLength + 1];
@@ -146,14 +146,11 @@ private static (byte r, byte g, byte b) DestructColor(Color color)
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static int PositionToAddress(int x, int y)
- {
- return y * 24 + x;
- }
+ private static int PositionToAddress(int x, int y) => y * 24 + x;
private static I2cDevice CreateDefaultI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
diff --git a/src/devices/SenseHat/SenseHatLedMatrixSysFs.cs b/src/devices/SenseHat/SenseHatLedMatrixSysFs.cs
index 6422e78c43..df8c1e70de 100644
--- a/src/devices/SenseHat/SenseHatLedMatrixSysFs.cs
+++ b/src/devices/SenseHat/SenseHatLedMatrixSysFs.cs
@@ -43,7 +43,7 @@ public override void Write(ReadOnlySpan colors)
{
if (colors.Length != NumberOfPixels)
{
- throw new ArgumentException($"`{nameof(colors)}` must have exactly {NumberOfPixels} elements.");
+ throw new ArgumentException(nameof(colors), $"Value must be {NumberOfPixels} elements. Length: {colors.Length}");
}
StartWritingColors();
@@ -88,22 +88,16 @@ public override void SetPixel(int x, int y, Color color)
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void StartWritingColors()
- {
+ private void StartWritingColors() =>
_deviceFile.Seek(0, SeekOrigin.Begin);
- }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void StartWritingColor(int x, int y)
- {
+ private void StartWritingColor(int x, int y) =>
_deviceFile.Seek(PositionToIndex(x, y) * PixelLength, SeekOrigin.Begin);
- }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private void EndWriting()
- {
+ private void EndWriting() =>
_deviceFile.Flush();
- }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void WriteColor(Color color)
diff --git a/src/devices/SenseHat/SenseHatPressureAndTemperature.cs b/src/devices/SenseHat/SenseHatPressureAndTemperature.cs
index 8b662f7906..f0d5ce0129 100644
--- a/src/devices/SenseHat/SenseHatPressureAndTemperature.cs
+++ b/src/devices/SenseHat/SenseHatPressureAndTemperature.cs
@@ -26,7 +26,7 @@ public SenseHatPressureAndTemperature(I2cDevice? i2cDevice = null)
private static I2cDevice CreateDefaultI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
}
diff --git a/src/devices/SenseHat/SenseHatTemperatureAndHumidity.cs b/src/devices/SenseHat/SenseHatTemperatureAndHumidity.cs
index 31150dc179..84b53f023a 100644
--- a/src/devices/SenseHat/SenseHatTemperatureAndHumidity.cs
+++ b/src/devices/SenseHat/SenseHatTemperatureAndHumidity.cs
@@ -26,7 +26,7 @@ public SenseHatTemperatureAndHumidity(I2cDevice? i2cDevice = null)
private static I2cDevice CreateDefaultI2cDevice()
{
- var settings = new I2cConnectionSettings(1, I2cAddress);
+ I2cConnectionSettings settings = new (1, I2cAddress);
return I2cDevice.Create(settings);
}
}
diff --git a/src/devices/SenseHat/samples/AccelerometerAndGyroscope.Sample.cs b/src/devices/SenseHat/samples/AccelerometerAndGyroscope.Sample.cs
index c93c0d0d63..1f27418a9b 100644
--- a/src/devices/SenseHat/samples/AccelerometerAndGyroscope.Sample.cs
+++ b/src/devices/SenseHat/samples/AccelerometerAndGyroscope.Sample.cs
@@ -14,14 +14,12 @@ internal class AccelerometerAndGyroscope
{
public static void Run()
{
- using (var ag = new SenseHatAccelerometerAndGyroscope())
+ using SenseHatAccelerometerAndGyroscope ag = new ();
+ while (true)
{
- while (true)
- {
- Console.WriteLine($"Acceleration={ag.Acceleration}");
- Console.WriteLine($"AngularRate={ag.AngularRate}");
- Thread.Sleep(100);
- }
+ Console.WriteLine($"Acceleration={ag.Acceleration}");
+ Console.WriteLine($"AngularRate={ag.AngularRate}");
+ Thread.Sleep(100);
}
}
}
diff --git a/src/devices/SenseHat/samples/Joystick.Sample.cs b/src/devices/SenseHat/samples/Joystick.Sample.cs
index 79195e16e5..fcae067ad9 100644
--- a/src/devices/SenseHat/samples/Joystick.Sample.cs
+++ b/src/devices/SenseHat/samples/Joystick.Sample.cs
@@ -14,37 +14,35 @@ internal class Joystick
{
public static void Run()
{
- using (var j = new SenseHatJoystick())
+ using SenseHatJoystick j = new ();
+ while (true)
{
- while (true)
- {
- j.Read();
+ j.Read();
- Console.Clear();
- if (j.HoldingUp)
- {
- Console.Write("U");
- }
+ Console.Clear();
+ if (j.HoldingUp)
+ {
+ Console.Write("U");
+ }
- if (j.HoldingDown)
- {
- Console.Write("D");
- }
+ if (j.HoldingDown)
+ {
+ Console.Write("D");
+ }
- if (j.HoldingLeft)
- {
- Console.Write("L");
- }
+ if (j.HoldingLeft)
+ {
+ Console.Write("L");
+ }
- if (j.HoldingRight)
- {
- Console.Write("R");
- }
+ if (j.HoldingRight)
+ {
+ Console.Write("R");
+ }
- if (j.HoldingButton)
- {
- Console.Write("!");
- }
+ if (j.HoldingButton)
+ {
+ Console.Write("!");
}
}
}
diff --git a/src/devices/SenseHat/samples/LedMatrix.Sample.cs b/src/devices/SenseHat/samples/LedMatrix.Sample.cs
index 52d49256e1..f2e9f5d7a7 100644
--- a/src/devices/SenseHat/samples/LedMatrix.Sample.cs
+++ b/src/devices/SenseHat/samples/LedMatrix.Sample.cs
@@ -17,13 +17,11 @@ public static void Run()
// another implementation which can be used is: SenseHatLedMatrixSysFs
// I2C implementation does not require installing anything
// SysFs implementation is faster and has arguably better colors
- using (var ledMatrix = new SenseHatLedMatrixI2c())
- {
- WriteDemo(ledMatrix);
+ using SenseHatLedMatrixI2c ledMatrix = new ();
+ WriteDemo(ledMatrix);
- // Uncomment to see demo of SetPixel/Fill
- // SetPixelDemo(m);
- }
+ // Uncomment to see demo of SetPixel/Fill
+ // SetPixelDemo(m);
}
// Not used by default but much simpler to understand
@@ -74,13 +72,11 @@ private static void Frame(Span colors, float time)
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- private static Color Pixel(Vector2 uv, float time)
- {
- return Color.FromArgb(
+ private static Color Pixel(Vector2 uv, float time) =>
+ Color.FromArgb(
Col(0.5 + 0.5 * Math.Cos(time + uv.X)),
Col(0.5 + 0.5 * Math.Cos(time + uv.Y + 2.0)),
Col(0.5 + 0.5 * Math.Cos(time + uv.X + 4.0)));
- }
private static byte Col(double x)
{
diff --git a/src/devices/SenseHat/samples/Magnetometer.Sample.cs b/src/devices/SenseHat/samples/Magnetometer.Sample.cs
index 6fa890ba11..0b34a1ff45 100644
--- a/src/devices/SenseHat/samples/Magnetometer.Sample.cs
+++ b/src/devices/SenseHat/samples/Magnetometer.Sample.cs
@@ -15,58 +15,56 @@ internal class Magnetometer
{
public static void Run()
{
- using (var magnetometer = new SenseHatMagnetometer())
- using (var ledMatrix = new SenseHatLedMatrixI2c())
+ using SenseHatMagnetometer magnetometer = new ();
+ using SenseHatLedMatrixI2c ledMatrix = new ();
+ Console.WriteLine("Move SenseHat around in every direction until dot on the LED matrix stabilizes when not moving.");
+ ledMatrix.Fill();
+ Stopwatch sw = Stopwatch.StartNew();
+ Vector3 min = magnetometer.MagneticInduction;
+ Vector3 max = magnetometer.MagneticInduction;
+ while (min == max)
{
- Console.WriteLine("Move SenseHat around in every direction until dot on the LED matrix stabilizes when not moving.");
- ledMatrix.Fill();
- Stopwatch sw = Stopwatch.StartNew();
- Vector3 min = magnetometer.MagneticInduction;
- Vector3 max = magnetometer.MagneticInduction;
- while (min == max)
- {
- Vector3 sample = magnetometer.MagneticInduction;
- min = Vector3.Min(min, sample);
- max = Vector3.Max(max, sample);
- Thread.Sleep(50);
- }
+ Vector3 sample = magnetometer.MagneticInduction;
+ min = Vector3.Min(min, sample);
+ max = Vector3.Max(max, sample);
+ Thread.Sleep(50);
+ }
- const int intervals = 8;
- Color[] data = new Color[64];
+ const int intervals = 8;
+ Color[] data = new Color[64];
- while (true)
- {
- Vector3 sample = magnetometer.MagneticInduction;
- min = Vector3.Min(min, sample);
- max = Vector3.Max(max, sample);
- Vector3 size = max - min;
- Vector3 pos = Vector3.Divide(Vector3.Multiply((sample - min), intervals - 1), size);
- int x = Math.Clamp((int)pos.X, 0, intervals - 1);
+ while (true)
+ {
+ Vector3 sample = magnetometer.MagneticInduction;
+ min = Vector3.Min(min, sample);
+ max = Vector3.Max(max, sample);
+ Vector3 size = max - min;
+ Vector3 pos = Vector3.Divide(Vector3.Multiply((sample - min), intervals - 1), size);
+ int x = Math.Clamp((int)pos.X, 0, intervals - 1);
- // reverse y to match magnetometer coordinate system
- int y = intervals - 1 - Math.Clamp((int)pos.Y, 0, intervals - 1);
- int idx = SenseHatLedMatrix.PositionToIndex(x, y);
+ // reverse y to match magnetometer coordinate system
+ int y = intervals - 1 - Math.Clamp((int)pos.Y, 0, intervals - 1);
+ int idx = SenseHatLedMatrix.PositionToIndex(x, y);
- // fading
- for (int i = 0; i < 64; i++)
- {
- data[i] = Color.FromArgb((byte)Math.Clamp(data[i].R - 1, 0, 255), data[i].G, data[i].B);
- }
+ // fading
+ for (int i = 0; i < 64; i++)
+ {
+ data[i] = Color.FromArgb((byte)Math.Clamp(data[i].R - 1, 0, 255), data[i].G, data[i].B);
+ }
- Color col = data[idx];
- col = Color.FromArgb(Math.Clamp(col.R + 20, 0, 255), col.G, col.B);
- Vector2 pos2 = new Vector2(sample.X, sample.Y);
- Vector2 center2 = Vector2.Multiply(new Vector2(min.X + max.X, min.Y + max.Y), 0.5f);
- float max2 = Math.Max(size.X, size.Y);
- float distFromCenter = (pos2 - center2).Length();
+ Color col = data[idx];
+ col = Color.FromArgb(Math.Clamp(col.R + 20, 0, 255), col.G, col.B);
+ Vector2 pos2 = new Vector2(sample.X, sample.Y);
+ Vector2 center2 = Vector2.Multiply(new Vector2(min.X + max.X, min.Y + max.Y), 0.5f);
+ float max2 = Math.Max(size.X, size.Y);
+ float distFromCenter = (pos2 - center2).Length();
- data[idx] = Color.FromArgb(0, 255, (byte)Math.Clamp(255 * distFromCenter / max2, 0, 255));
+ data[idx] = Color.FromArgb(0, 255, (byte)Math.Clamp(255 * distFromCenter / max2, 0, 255));
- ledMatrix.Write(data);
- data[idx] = col;
+ ledMatrix.Write(data);
+ data[idx] = col;
- Thread.Sleep(50);
- }
+ Thread.Sleep(50);
}
}
}
diff --git a/src/devices/SenseHat/samples/PressureAndTemperature.Sample.cs b/src/devices/SenseHat/samples/PressureAndTemperature.Sample.cs
index 4a2127cd69..742c26f94f 100644
--- a/src/devices/SenseHat/samples/PressureAndTemperature.Sample.cs
+++ b/src/devices/SenseHat/samples/PressureAndTemperature.Sample.cs
@@ -19,19 +19,17 @@ public static void Run()
// set this to the current sea level pressure in the area for correct altitude readings
var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
- using (var pt = new SenseHatPressureAndTemperature())
+ using SenseHatPressureAndTemperature pt = new ();
+ while (true)
{
- while (true)
- {
- var tempValue = pt.Temperature;
- var preValue = pt.Pressure;
- var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);
+ var tempValue = pt.Temperature;
+ var preValue = pt.Pressure;
+ var altValue = WeatherHelper.CalculateAltitude(preValue, defaultSeaLevelPressure, tempValue);
- Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
- Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
- Console.WriteLine($"Altitude: {altValue:0.##}m");
- Thread.Sleep(1000);
- }
+ Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
+ Console.WriteLine($"Pressure: {preValue.Hectopascals:0.##}hPa");
+ Console.WriteLine($"Altitude: {altValue:0.##}m");
+ Thread.Sleep(1000);
}
}
}
diff --git a/src/devices/SenseHat/samples/Program.cs b/src/devices/SenseHat/samples/Program.cs
index 330c14c803..8bbf18223a 100644
--- a/src/devices/SenseHat/samples/Program.cs
+++ b/src/devices/SenseHat/samples/Program.cs
@@ -19,7 +19,7 @@
// set this to the current sea level pressure in the area for correct altitude readings
var defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;
-using SenseHat sh = new SenseHat();
+using SenseHat sh = new ();
int n = 0;
int x = 3, y = 3;
diff --git a/src/devices/SenseHat/samples/TemperatureAndHumidity.Sample.cs b/src/devices/SenseHat/samples/TemperatureAndHumidity.Sample.cs
index e7c54fa397..4e6b517a7b 100644
--- a/src/devices/SenseHat/samples/TemperatureAndHumidity.Sample.cs
+++ b/src/devices/SenseHat/samples/TemperatureAndHumidity.Sample.cs
@@ -16,22 +16,20 @@ internal class TemperatureAndHumidity
{
public static void Run()
{
- using (var th = new SenseHatTemperatureAndHumidity())
+ using SenseHatTemperatureAndHumidity th = new ();
+ while (true)
{
- while (true)
- {
- var tempValue = th.Temperature;
- var humValue = th.Humidity;
+ var tempValue = th.Temperature;
+ var humValue = th.Humidity;
- Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
- Console.WriteLine($"Relative humidity: {humValue:0.#}%");
+ Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
+ Console.WriteLine($"Relative humidity: {humValue:0.#}%");
- // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
- Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
- Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
+ // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
+ Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
+ Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(tempValue, humValue).DegreesCelsius:0.#}\u00B0C");
- Thread.Sleep(1000);
- }
+ Thread.Sleep(1000);
}
}
}
diff --git a/src/devices/ShiftRegister/ShiftRegister.cs b/src/devices/ShiftRegister/ShiftRegister.cs
index 33ef044e98..a7db607d39 100644
--- a/src/devices/ShiftRegister/ShiftRegister.cs
+++ b/src/devices/ShiftRegister/ShiftRegister.cs
@@ -38,7 +38,7 @@ public class ShiftRegister : IDisposable
/// True (the default) if the GPIO controller shall be disposed when disposing this instance.
public ShiftRegister(ShiftRegisterPinMapping pinMapping, int bitLength, GpioController? gpioController = null, bool shouldDispose = true)
{
- _shouldDispose = shouldDispose || (gpioController == null);
+ _shouldDispose = shouldDispose || gpioController is null;
_controller = gpioController ?? new GpioController();
_pinMapping = pinMapping;
_serial = _pinMapping.SerialDataInput;
@@ -56,7 +56,7 @@ public ShiftRegister(ShiftRegisterPinMapping pinMapping, int bitLength, GpioCont
/// Bit length of register, including chained registers.
public ShiftRegister(SpiDevice spiDevice, int bitLength)
{
- _spiDevice = spiDevice;
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
_bitLength = bitLength;
}
@@ -95,7 +95,7 @@ public void ShiftClear()
{
if (_bitLength % 8 > 0)
{
- throw new ArgumentNullException($"{nameof(ShiftClear)}: Only supported for registers with bit lengths evenly divisible by 8.");
+ throw new ArgumentNullException(nameof(ShiftClear), "Only supported for registers with bit lengths evenly divisible by 8.");
}
for (int i = 0; i < _bitLength / 8; i++)
@@ -114,7 +114,7 @@ public void ShiftBit(PinValue value)
{
if (_controller is null || _pinMapping.SerialDataInput < 0)
{
- throw new ArgumentNullException($"{nameof(ShiftBit)}: GpioController was not provided or {nameof(_pinMapping.SerialDataInput)} not mapped to pin");
+ throw new ArgumentNullException(nameof(ShiftBit), "GpioController was not provided or {nameof(_pinMapping.SerialDataInput)} not mapped to pin");
}
// writes value to serial data pin
@@ -165,7 +165,7 @@ public void Latch()
{
if (_controller is null || _pinMapping.LatchEnable < 0)
{
- throw new ArgumentNullException($"{nameof(Latch)}: GpioController was not provided or {nameof(_pinMapping.LatchEnable)} not mapped to pin");
+ throw new Exception($"{nameof(Latch)}: GpioController was not provided or {nameof(_pinMapping.LatchEnable)} not mapped to pin");
}
// latches value on rising edge of register clock (LE)
@@ -185,7 +185,7 @@ public bool OutputEnable
{
if (_controller is null || _pinMapping.OutputEnable < 0)
{
- throw new ArgumentNullException($"{nameof(OutputEnable)}: {nameof(_pinMapping.OutputEnable)} not mapped to non-zero pin value");
+ throw new Exception($"{nameof(OutputEnable)}: {nameof(_pinMapping.OutputEnable)} not mapped to non-zero pin value");
}
_controller.Write(_pinMapping.OutputEnable, value ? 0 : 1);
@@ -223,7 +223,7 @@ private void SetupPins()
}
else
{
- throw new ArgumentException($"{nameof(ShiftRegister)} -- {nameof(ShiftRegisterPinMapping)} values must be non-zero; Values: {nameof(ShiftRegisterPinMapping.SerialDataInput)}: {_serial}; {nameof(ShiftRegisterPinMapping.LatchEnable)}: {_latch}; {nameof(ShiftRegisterPinMapping.Clock)}: {_clock};.");
+ throw new Exception($"{nameof(ShiftRegister)} -- {nameof(ShiftRegisterPinMapping)} values must be non-zero; Values: {nameof(ShiftRegisterPinMapping.SerialDataInput)}: {_serial}; {nameof(ShiftRegisterPinMapping.LatchEnable)}: {_latch}; {nameof(ShiftRegisterPinMapping.Clock)}: {_clock};.");
}
// this pin assignment is optional
diff --git a/src/devices/ShiftRegister/samples/Program.cs b/src/devices/ShiftRegister/samples/Program.cs
index 3c252f1378..4f61195b65 100644
--- a/src/devices/ShiftRegister/samples/Program.cs
+++ b/src/devices/ShiftRegister/samples/Program.cs
@@ -22,7 +22,7 @@
Console.WriteLine($"Driver for {nameof(ShiftRegister)}");
Console.WriteLine($"Register bit length: {sr.BitLength}");
-var interfaceType = sr.UsesSpi ? "SPI" : "GPIO";
+string interfaceType = sr.UsesSpi ? "SPI" : "GPIO";
Console.WriteLine($"Using {interfaceType}");
sr.OutputEnable = true;
@@ -163,7 +163,7 @@ void ShiftBytes(ShiftRegister sr, int value)
{
if (sr.BitLength > 32)
{
- throw new ArgumentException($"{nameof(ShiftBytes)}: bit length must be 8-32.");
+ throw new Exception($"{nameof(ShiftBytes)}: bit length must be 8-32.");
}
for (int i = (sr.BitLength / 8) - 1; i > 0; i--)
diff --git a/src/devices/Sht3x/Sht3x.cs b/src/devices/Sht3x/Sht3x.cs
index 5e8191950c..619a115046 100644
--- a/src/devices/Sht3x/Sht3x.cs
+++ b/src/devices/Sht3x/Sht3x.cs
@@ -35,7 +35,7 @@ public Temperature Temperature
{
get
{
- ReadTempAndHumi();
+ ReadTempAndHumidity();
return Temperature.FromDegreesCelsius(_temperature);
}
}
@@ -49,7 +49,7 @@ public Ratio Humidity
{
get
{
- ReadTempAndHumi();
+ ReadTempAndHumidity();
return Ratio.FromPercent(_humidity);
}
}
@@ -97,10 +97,8 @@ public void Dispose()
///
/// SHT3x Soft Reset
///
- public void Reset()
- {
+ public void Reset() =>
Write(Register.SHT_RESET);
- }
///
/// Set SHT3x Heater
@@ -121,7 +119,7 @@ private void SetHeater(bool isOn)
///
/// Read Temperature and Humidity
///
- private void ReadTempAndHumi()
+ private void ReadTempAndHumidity()
{
Span writeBuff = stackalloc byte[]
{
diff --git a/src/devices/Sht3x/samples/Program.cs b/src/devices/Sht3x/samples/Program.cs
index 2f0d9764c6..68e4381f10 100644
--- a/src/devices/Sht3x/samples/Program.cs
+++ b/src/devices/Sht3x/samples/Program.cs
@@ -10,11 +10,11 @@
I2cConnectionSettings settings = new (1, (byte)I2cAddress.AddrLow);
using I2cDevice device = I2cDevice.Create(settings);
-using Sht3x sensor = new Sht3x(device);
+using Sht3x sensor = new (device);
while (true)
{
- var tempValue = sensor.Temperature;
- var humValue = sensor.Humidity;
+ Temperature tempValue = sensor.Temperature;
+ Ratio humValue = sensor.Humidity;
Console.WriteLine($"Temperature: {tempValue.DegreesCelsius:0.#}\u00B0C");
Console.WriteLine($"Relative humidity: {humValue:0.#}%");
diff --git a/src/devices/Shtc3/Shtc3.cs b/src/devices/Shtc3/Shtc3.cs
index cec74739f1..9c23d0c17f 100644
--- a/src/devices/Shtc3/Shtc3.cs
+++ b/src/devices/Shtc3/Shtc3.cs
@@ -33,12 +33,7 @@ public class Shtc3 : IDisposable
/// The I2C device used for communication.
public Shtc3(I2cDevice i2cDevice)
{
- if (i2cDevice == null)
- {
- throw new ArgumentNullException(nameof(i2cDevice));
- }
-
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
Wakeup();
_status = Status.Idle;
@@ -51,13 +46,7 @@ public Shtc3(I2cDevice i2cDevice)
///
/// Set Shtc3 state
///
- internal Status Status
- {
- get
- {
- return _status;
- }
- }
+ internal Status Status => _status;
///
/// Try read Temperature and Humidity
@@ -158,10 +147,7 @@ public void Sleep()
///
/// SHTC3 Wakeup
///
- private void Wakeup()
- {
- Write(Register.SHTC3_WAKEUP);
- }
+ private void Wakeup() => Write(Register.SHTC3_WAKEUP);
///
/// SHTC3 Soft Reset
@@ -179,13 +165,7 @@ public void Reset()
///
/// Sensor Id
///
- public int? Id
- {
- get
- {
- return _id = _id ?? ReadId();
- }
- }
+ public int? Id => _id = _id ?? ReadId();
///
/// Read Id
@@ -226,10 +206,8 @@ public int? Id
///
/// Id to test
///
- private static bool ValidShtc3Id(int id)
- {
- return (id & 0b_0000_1000_0011_1111) == 0b_0000_1000_0000_0111;
- }
+ private static bool ValidShtc3Id(int id) =>
+ (id & 0b_0000_1000_0011_1111) == 0b_0000_1000_0000_0111;
///
/// 8-bit CRC Checksum Calculation
diff --git a/src/devices/Shtc3/samples/Program.cs b/src/devices/Shtc3/samples/Program.cs
index 059adcff63..a7f1ba1973 100644
--- a/src/devices/Shtc3/samples/Program.cs
+++ b/src/devices/Shtc3/samples/Program.cs
@@ -10,7 +10,7 @@
I2cConnectionSettings settings = new (1, Iot.Device.Shtc3.Shtc3.DefaultI2cAddress);
using I2cDevice device = I2cDevice.Create(settings);
-using Shtc3 sensor = new Shtc3(device);
+using Shtc3 sensor = new (device);
Console.WriteLine($"Sensor Id: {sensor.Id}");
while (true)
{
diff --git a/src/devices/Si7021/Si7021.cs b/src/devices/Si7021/Si7021.cs
index 8b93154893..7ae937b6ea 100644
--- a/src/devices/Si7021/Si7021.cs
+++ b/src/devices/Si7021/Si7021.cs
@@ -63,7 +63,7 @@ public bool Heater
/// Si7021 Read Resolution
public Si7021(I2cDevice i2cDevice, Resolution resolution = Resolution.Resolution1)
{
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
SetResolution(resolution);
}
diff --git a/src/devices/Si7021/samples/Program.cs b/src/devices/Si7021/samples/Program.cs
index d9544a8120..15ceb85270 100644
--- a/src/devices/Si7021/samples/Program.cs
+++ b/src/devices/Si7021/samples/Program.cs
@@ -10,7 +10,7 @@
I2cConnectionSettings settings = new (1, Si7021.DefaultI2cAddress);
using I2cDevice device = I2cDevice.Create(settings);
-using Si7021 sensor = new Si7021(device, Resolution.Resolution1);
+using Si7021 sensor = new (device, Resolution.Resolution1);
while (true)
{
var tempValue = sensor.Temperature;
diff --git a/src/devices/Sn74hc595/Sn74hc595.cs b/src/devices/Sn74hc595/Sn74hc595.cs
index e36c82545a..d99c4a9f49 100644
--- a/src/devices/Sn74hc595/Sn74hc595.cs
+++ b/src/devices/Sn74hc595/Sn74hc595.cs
@@ -38,7 +38,7 @@ public void ClearStorage(bool latch = true)
{
if (GpioController is null || _pinMapping.SrClr == 0)
{
- throw new ArgumentNullException($"{nameof(ClearStorage)}: GpioController was not provided or {nameof(_pinMapping.SrClr)} not mapped to pin");
+ throw new Exception($"{nameof(ClearStorage)}: GpioController was not provided or {nameof(_pinMapping.SrClr)} not mapped to pin");
}
GpioController.Write(_pinMapping.SrClr, 0);
diff --git a/src/devices/Sn74hc595/samples/Program.cs b/src/devices/Sn74hc595/samples/Program.cs
index 21f0aa4274..a1e6c1cf9c 100644
--- a/src/devices/Sn74hc595/samples/Program.cs
+++ b/src/devices/Sn74hc595/samples/Program.cs
@@ -7,7 +7,7 @@
using System.Threading;
using Iot.Device.Multiplexing;
-using Sn74hc595 sr = new Sn74hc595(Sn74hc595PinMapping.Complete);
+using Sn74hc595 sr = new (Sn74hc595PinMapping.Complete);
// SpiConnectionSettings settings = new (0, 0);
// using var spiDevice = SpiDevice.Create(settings);
// var sr = new Sn74hc595(spiDevice, Sn74hc595.PinMapping.Standard);
@@ -20,7 +20,7 @@
Console.WriteLine($"Driver for {nameof(Iot.Device.Multiplexing.Sn74hc595)}");
Console.WriteLine($"Register bit length: {sr.BitLength}");
-var interfaceType = sr.UsesSpi ? "SPI" : "GPIO";
+string interfaceType = sr.UsesSpi ? "SPI" : "GPIO";
Console.WriteLine($"Using {interfaceType}");
if (!sr.UsesSpi)
@@ -156,7 +156,7 @@ void ShiftBytes(Sn74hc595 sr, int value)
{
if (sr.BitLength > 32)
{
- throw new ArgumentException($"{nameof(ShiftBytes)}: bit length must be 8-32.");
+ throw new Exception($"{nameof(ShiftBytes)}: bit length must be 8-32.");
}
for (int i = (sr.BitLength / 8) - 1; i > 0; i--)
diff --git a/src/devices/SocketCan/CanRaw.cs b/src/devices/SocketCan/CanRaw.cs
index 0c8e3ee3ed..3f6bb9e75d 100644
--- a/src/devices/SocketCan/CanRaw.cs
+++ b/src/devices/SocketCan/CanRaw.cs
@@ -73,7 +73,7 @@ public bool TryReadFrame(Span data, out int frameLength, out CanId id)
{
if (data.Length < CanFrame.MaxLength)
{
- throw new ArgumentException($"Buffer length must be at minimum {CanFrame.MaxLength} bytes", nameof(data));
+ throw new ArgumentException(nameof(data), $"Value must be a minimum of {CanFrame.MaxLength} bytes.");
}
CanFrame frame = new CanFrame();
@@ -123,7 +123,7 @@ public void Filter(CanId id)
{
if (!id.IsValid)
{
- throw new ArgumentException($"{nameof(id)} must be a valid CanId");
+ throw new ArgumentException(nameof(id), "Value must be a valid CanId");
}
Span filters = stackalloc Interop.CanFilter[1];
diff --git a/src/devices/SocketCan/Interop.cs b/src/devices/SocketCan/Interop.cs
index 306ac92204..3013f93b6f 100644
--- a/src/devices/SocketCan/Interop.cs
+++ b/src/devices/SocketCan/Interop.cs
@@ -83,10 +83,8 @@ public static unsafe int Read(SafeHandle handle, Span buffer)
}
}
- public static void CloseSocket(IntPtr fd)
- {
+ public static void CloseSocket(IntPtr fd) =>
CloseSocket((int)fd);
- }
public static IntPtr CreateCanRawSocket(string networkInterface)
{
@@ -104,10 +102,8 @@ public static IntPtr CreateCanRawSocket(string networkInterface)
}
public static bool SetCanRawSocketOption(SafeHandle handle, CanSocketOption optName, ReadOnlySpan data)
- where T : struct
- {
- return SetSocketOption(handle, SOL_CAN_RAW, optName, data);
- }
+ where T : struct =>
+ SetSocketOption(handle, SOL_CAN_RAW, optName, data);
private static unsafe bool SetSocketOption(SafeHandle handle, int level, CanSocketOption optName, ReadOnlySpan data)
where T : struct
@@ -140,7 +136,7 @@ private static unsafe int GetInterfaceIndex(int fd, string name)
if (name.Length >= MaxLen)
{
- throw new ArgumentException($"`{name}` exceeds maximum allowed length of {MaxLen} size", nameof(name));
+ throw new ArgumentException(nameof(name), $"Value exceeds maximum allowed length of {MaxLen} size.");
}
ifreq ifr = new ifreq();
diff --git a/src/devices/SocketCan/samples/Program.cs b/src/devices/SocketCan/samples/Program.cs
index a52f81ddcb..5803d0b322 100644
--- a/src/devices/SocketCan/samples/Program.cs
+++ b/src/devices/SocketCan/samples/Program.cs
@@ -12,7 +12,7 @@
Standard = 0x1A // arbitrary id
};
-Dictionary samples = new Dictionary
+Dictionary samples = new ()
{
{ "send", SendExample },
{ "receive", ReceiveAllExample },
@@ -69,7 +69,7 @@ void ReceiveAllExample()
{
Console.WriteLine("Listening for any id");
- using CanRaw can = new CanRaw();
+ using CanRaw can = new ();
byte[] buffer = new byte[8];
while (true)
@@ -96,7 +96,7 @@ void ReceiveOnAddressExample()
{
Console.WriteLine($"Listening for id = 0x{id.Value:X2}");
- using CanRaw can = new CanRaw();
+ using CanRaw can = new ();
byte[] buffer = new byte[8];
can.Filter(id);
diff --git a/src/devices/SoftPwm/SoftwarePwmChannel.cs b/src/devices/SoftPwm/SoftwarePwmChannel.cs
index dd73c253a6..a9ec1b6a41 100644
--- a/src/devices/SoftPwm/SoftwarePwmChannel.cs
+++ b/src/devices/SoftPwm/SoftwarePwmChannel.cs
@@ -41,7 +41,6 @@ public class SoftwarePwmChannel : PwmChannel
public override int Frequency
{
get => _frequency;
-
set
{
if (value <= 0)
@@ -58,7 +57,6 @@ public override int Frequency
public override double DutyCycle
{
get => _dutyCycle;
-
set
{
if (value < 0.0 || value > 1.0)
@@ -99,17 +97,8 @@ public SoftwarePwmChannel(int pinNumber, int frequency = 400, double dutyCycle =
_frequency = frequency;
_dutyCycle = dutyCycle;
-
- if (controller is null)
- {
- _controller = new GpioController();
- _shouldDispose = true;
- }
- else
- {
- _controller = controller;
- _shouldDispose = shouldDispose;
- }
+ _shouldDispose = shouldDispose || controller is null;
+ _controller = controller ?? new ();
UpdatePulseWidthParameters();
@@ -166,16 +155,10 @@ private void Run()
}
/// Starts the PWM channel.
- public override void Start()
- {
- _isRunning = true;
- }
+ public override void Start() => _isRunning = true;
/// Stops the PWM channel.
- public override void Stop()
- {
- _isRunning = false;
- }
+ public override void Stop() => _isRunning = false;
///
protected override void Dispose(bool disposing)
diff --git a/src/devices/SoftwareSpi/SoftwareSpi.cs b/src/devices/SoftwareSpi/SoftwareSpi.cs
index 4adc533b12..27ec483eb6 100644
--- a/src/devices/SoftwareSpi/SoftwareSpi.cs
+++ b/src/devices/SoftwareSpi/SoftwareSpi.cs
@@ -14,34 +14,33 @@ namespace Iot.Device.Spi
public class SoftwareSpi : SpiDevice
{
private readonly int _clk;
- private readonly int _miso;
- private readonly int _mosi;
+ private readonly int _sdi;
+ private readonly int _sdo;
private readonly int _cs;
private readonly SpiConnectionSettings _settings;
private readonly bool _shouldDispose;
- private GpioController _controller;
+ private GpioController _gpioController;
///
/// Software implementation of the SPI.
///
/// Note that there is a ChipSelectLine in the SPIConnectionSettings as well, either that or the cs property will be used.
/// Clock pin.
- /// Master Input Slave Output pin. Optional, set to -1 to ignore
- /// Master Output Slave Input pin.
+ /// Serial data in pin. Optional, set to -1 to ignore
+ /// Serial data out pin.
/// Chip select pin (or negated chip select). Optional, set to -1 to ignore.
/// Settings of the SPI connection.
- /// GPIO controller used for pins.
+ /// GPIO controller used for pins.
/// True to dispose the Gpio Controller
- public SoftwareSpi(int clk, int miso, int mosi, int cs = -1, SpiConnectionSettings? settings = null, GpioController? controller = null, bool shouldDispose = true)
+ public SoftwareSpi(int clk, int sdi, int sdo, int cs = -1, SpiConnectionSettings? settings = null, GpioController? gpioController = null, bool shouldDispose = true)
{
- _controller = controller ?? new GpioController();
- _shouldDispose = controller == null ? true : shouldDispose;
-
+ _shouldDispose = shouldDispose || gpioController is null;
+ _gpioController = gpioController ?? new GpioController();
_settings = settings ?? new SpiConnectionSettings(-1, -1);
_clk = clk;
- _miso = miso;
- _mosi = mosi;
+ _sdi = sdi;
+ _sdo = sdo;
if (_cs != -1 && _settings.ChipSelectLine != -1 && _cs != _settings.ChipSelectLine)
{
@@ -57,16 +56,16 @@ public SoftwareSpi(int clk, int miso, int mosi, int cs = -1, SpiConnectionSettin
_cs = _settings.ChipSelectLine;
}
- _controller.OpenPin(_clk, PinMode.Output);
- if (_miso != -1)
+ _gpioController.OpenPin(_clk, PinMode.Output);
+ if (_sdi != -1)
{
- _controller.OpenPin(_miso, PinMode.Input);
+ _gpioController.OpenPin(_sdi, PinMode.Input);
}
- _controller.OpenPin(_mosi, PinMode.Output);
+ _gpioController.OpenPin(_sdo, PinMode.Output);
if (_cs != -1)
{
- _controller.OpenPin(_cs, PinMode.Output);
+ _gpioController.OpenPin(_cs, PinMode.Output);
}
// aka. CPOL - tells us which state of the clock means idle (false means 'low' or 'ground' or '0')
@@ -77,10 +76,10 @@ public SoftwareSpi(int clk, int miso, int mosi, int cs = -1, SpiConnectionSettin
if (_cs != -1)
{
- _controller.Write(_cs, !(bool)_settings.ChipSelectLineActiveState);
+ _gpioController.Write(_cs, !(bool)_settings.ChipSelectLineActiveState);
}
- _controller.Write(_clk, idle);
+ _gpioController.Write(_clk, idle);
// TODO: To respect ClockFrequency we need to inject the right delays here
// and have some very accurate way to measure time.
@@ -103,11 +102,11 @@ public SoftwareSpi(int clk, int miso, int mosi, int cs = -1, SpiConnectionSettin
_bitTransfer = new ScopeData(
enter: () =>
{
- _controller.Write(_clk, !idle);
+ _gpioController.Write(_clk, !idle);
},
exit: () =>
{
- _controller.Write(_clk, idle);
+ _gpioController.Write(_clk, idle);
});
}
else
@@ -115,8 +114,8 @@ public SoftwareSpi(int clk, int miso, int mosi, int cs = -1, SpiConnectionSettin
_bitTransfer = new ScopeData(
exit: () =>
{
- _controller.Write(_clk, !idle);
- _controller.Write(_clk, idle);
+ _gpioController.Write(_clk, !idle);
+ _gpioController.Write(_clk, idle);
});
}
@@ -125,11 +124,11 @@ public SoftwareSpi(int clk, int miso, int mosi, int cs = -1, SpiConnectionSettin
_chipSelect = new ScopeData(
enter: () =>
{
- _controller.Write(_cs, _settings.ChipSelectLineActiveState);
+ _gpioController.Write(_cs, _settings.ChipSelectLineActiveState);
},
exit: () =>
{
- _controller.Write(_cs, !(bool)_settings.ChipSelectLineActiveState);
+ _gpioController.Write(_cs, !(bool)_settings.ChipSelectLineActiveState);
});
}
else
@@ -149,7 +148,7 @@ public override void TransferFullDuplex(ReadOnlySpan dataToWrite, Span dataToWrite)
private bool ReadWriteBit(bool bitToWrite)
{
- // _mosi is checked higher up the call path
- _controller.Write(_mosi, bitToWrite);
- return (bool)_controller.Read(_miso);
+ // sdo is checked higher up the call path
+ _gpioController.Write(_sdo, bitToWrite);
+ return (bool)_gpioController.Read(_sdi);
}
- private void WriteBit(bool bitToWrite)
- {
- _controller.Write(_mosi, bitToWrite);
- }
+ private void WriteBit(bool bitToWrite) => _gpioController.Write(_sdo, bitToWrite);
///
public override void Read(Span data)
@@ -222,10 +218,7 @@ public override void Read(Span data)
}
///
- public override void Write(ReadOnlySpan data)
- {
- TransferWriteOnly(data);
- }
+ public override void Write(ReadOnlySpan data) => TransferWriteOnly(data);
///
public override void WriteByte(byte data)
@@ -248,8 +241,8 @@ protected override void Dispose(bool disposing)
{
if (_shouldDispose)
{
- _controller?.Dispose();
- _controller = null!;
+ _gpioController?.Dispose();
+ _gpioController = null!;
}
base.Dispose(disposing);
@@ -271,15 +264,9 @@ public ScopeData(Action? enter = null, Action? exit = null)
_exit = exit ?? new Action(() => { });
}
- public void Enter()
- {
- _enter.Invoke();
- }
+ public void Enter() => _enter.Invoke();
- public void Exit()
- {
- _exit.Invoke();
- }
+ public void Exit() => _exit.Invoke();
}
private struct Scope : IDisposable
diff --git a/src/devices/Ssd1351/Ssd1351.cs b/src/devices/Ssd1351/Ssd1351.cs
index 44e736b7dd..87f09ffc08 100644
--- a/src/devices/Ssd1351/Ssd1351.cs
+++ b/src/devices/Ssd1351/Ssd1351.cs
@@ -22,7 +22,7 @@ public partial class Ssd1351 : IDisposable
private readonly int _dcPinId;
private readonly int _resetPinId;
private readonly int _spiBufferSize;
- private readonly bool _disposeGpioController;
+ private readonly bool _shouldDispose;
private SpiDevice _spiDevice;
private GpioController _gpioDevice;
@@ -45,13 +45,13 @@ public Ssd1351(SpiDevice spiDevice, int dataCommandPin, int resetPin, int spiBuf
{
if (!InRange((uint)spiBufferSize, 0x1000, 0x10000))
{
- throw new ArgumentException($"SPI Buffer Size must be between 4096 and 65536.", nameof(spiBufferSize));
+ throw new ArgumentException(nameof(spiBufferSize), "Value must be between 4096 and 65536.");
}
_gpioDevice = gpioController ?? new GpioController();
- _disposeGpioController = gpioController == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || gpioController is null;
- _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
+ _spiDevice = spiDevice ?? throw new ArgumentException(nameof(spiDevice));
_dcPinId = dataCommandPin;
_resetPinId = resetPin;
@@ -65,7 +65,7 @@ public Ssd1351(SpiDevice spiDevice, int dataCommandPin, int resetPin, int spiBuf
}
///
- /// Convert a color structure to a byte tuple represening the colour in 565 format.
+ /// Convert a color structure to a byte tuple representing the colour in 565 format.
///
/// The color to be converted.
///
@@ -139,7 +139,7 @@ public void FillRect(Color color, byte x, byte y, byte w, byte h)
}
}
- // specifiy a location for the rows and columns on the display where the data is to be written
+ // specify a location for the rows and columns on the display where the data is to be written
SetColumnAddress(x, (byte)(x + w - 1));
SetRowAddress(y, (byte)(y + h - 1));
@@ -278,7 +278,7 @@ private void SendSPI(Span data, bool blnIsCommand = false)
///
public void Dispose()
{
- if (_disposeGpioController)
+ if (_shouldDispose)
{
_gpioDevice?.Dispose();
_gpioDevice = null!;
diff --git a/src/devices/Ssd1351/Ssd1351Commands.cs b/src/devices/Ssd1351/Ssd1351Commands.cs
index b1298ded6e..3a1e5fa97d 100644
--- a/src/devices/Ssd1351/Ssd1351Commands.cs
+++ b/src/devices/Ssd1351/Ssd1351Commands.cs
@@ -425,7 +425,7 @@ public void SetGpio(GpioMode pin0Mode = GpioMode.OutputLow, GpioMode pin1Mode =
/// If this parameter is null or an empty array then the gray leves are set to default.
public void SetGrayLevels(byte[]? grayLevels = null)
{
- if (grayLevels == null || grayLevels.Length == 0)
+ if (grayLevels is null || grayLevels.Length == 0)
{
SendCommand(Ssd1351Command.SetDefaultGrayLevels);
}
diff --git a/src/devices/Ssd1351/Ssd1351Imaging.cs b/src/devices/Ssd1351/Ssd1351Imaging.cs
index c4397029f1..720d75742c 100644
--- a/src/devices/Ssd1351/Ssd1351Imaging.cs
+++ b/src/devices/Ssd1351/Ssd1351Imaging.cs
@@ -44,7 +44,7 @@ public void SendBitmap(Bitmap bm, Point sourcePoint, Rectangle destinationRect)
if (bm.PixelFormat != PixelFormat.Format32bppArgb)
{
- throw new ArgumentException($"Pixel format {bm.PixelFormat.ToString()} not supported.", nameof(bm.PixelFormat));
+ throw new ArgumentException(nameof(bm), $"Pixel format {bm.PixelFormat.ToString()} not supported.");
}
// get the pixel data and send it to the display
@@ -70,7 +70,7 @@ public Span GetBitmapPixelData(Bitmap bm, Rectangle sourceRect)
if (bm.PixelFormat != PixelFormat.Format32bppArgb)
{
- throw new ArgumentException($"Pixel format {bm.PixelFormat.ToString()} not supported.", nameof(bm.PixelFormat));
+ throw new ArgumentException(nameof(bm), $"Pixel format {bm.PixelFormat.ToString()} not supported.");
}
// allocate the working arrays.
diff --git a/src/devices/Ssd1351/samples/Program.cs b/src/devices/Ssd1351/samples/Program.cs
index 298bb2fedc..5acc64dbef 100644
--- a/src/devices/Ssd1351/samples/Program.cs
+++ b/src/devices/Ssd1351/samples/Program.cs
@@ -11,10 +11,10 @@
const int pinID_DC = 23;
const int pinID_Reset = 24;
-using Bitmap dotnetBM = new Bitmap(128, 128);
-using System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dotnetBM);
+using Bitmap dotnetBM = new (128, 128);
+using Graphics g = Graphics.FromImage(dotnetBM);
using SpiDevice displaySPI = SpiDevice.Create(new SpiConnectionSettings(0, 0) { Mode = SpiMode.Mode3, DataBitLength = 8, ClockFrequency = 12_000_000 /* 12MHz */ });
-using Ssd1351 ssd1351 = new Ssd1351(displaySPI, pinID_DC, pinID_Reset);
+using Ssd1351 ssd1351 = new (displaySPI, pinID_DC, pinID_Reset);
ssd1351.ResetDisplayAsync().Wait();
InitDisplayForAdafruit(ssd1351);
diff --git a/src/devices/Ssd13xx/Ssd1306.cs b/src/devices/Ssd13xx/Ssd1306.cs
index 9d83549cb1..e9f868b8b4 100644
--- a/src/devices/Ssd13xx/Ssd1306.cs
+++ b/src/devices/Ssd13xx/Ssd1306.cs
@@ -28,19 +28,13 @@ public Ssd1306(I2cDevice i2cDevice)
/// Sends command to the device
///
/// Command being send
- public void SendCommand(ISsd1306Command command)
- {
- SendCommand((ICommand)command);
- }
+ public void SendCommand(ISsd1306Command command) => SendCommand((ICommand)command);
///
/// Sends command to the device
///
/// Command being send
- public override void SendCommand(ISharedCommand command)
- {
- SendCommand(command);
- }
+ public override void SendCommand(ISharedCommand command) => SendCommand(command);
///
/// Send a command to the display controller.
@@ -48,16 +42,12 @@ public override void SendCommand(ISharedCommand command)
/// The command to send to the display controller.
private void SendCommand(ICommand command)
{
- byte[] commandBytes = command.GetBytes();
-
- if (commandBytes == null)
- {
- throw new ArgumentNullException(nameof(commandBytes));
- }
+#pragma warning disable SA1011
+ byte[]? commandBytes = command?.GetBytes();
- if (commandBytes.Length == 0)
+ if (commandBytes is not { Length: >0 })
{
- throw new ArgumentException("The command did not contain any bytes to send.");
+ throw new ArgumentNullException(nameof(command), "Argument is either null or there were no bytes to send.");
}
Span writeBuffer = SliceGenericBuffer(commandBytes.Length + 1);
diff --git a/src/devices/Ssd13xx/Ssd1327.cs b/src/devices/Ssd13xx/Ssd1327.cs
index 6d11bf9fce..04e13797f2 100644
--- a/src/devices/Ssd13xx/Ssd1327.cs
+++ b/src/devices/Ssd13xx/Ssd1327.cs
@@ -31,20 +31,14 @@ public Ssd1327(I2cDevice i2cDevice)
///
/// Start address
/// End address
- public void SetColumnAddress(byte startAddress = 0x08, byte endAddress = 0x37)
- {
- SendCommand(new Ssd1327Cmnds.SetColumnAddress(startAddress, endAddress));
- }
+ public void SetColumnAddress(byte startAddress = 0x08, byte endAddress = 0x37) => SendCommand(new Ssd1327Cmnds.SetColumnAddress(startAddress, endAddress));
///
/// Sets row address
///
/// Start address
/// End address
- public void SetRowAddress(byte startAddress = 0x00, byte endAddress = 0x5f)
- {
- SendCommand(new Ssd1327Cmnds.SetRowAddress(startAddress, endAddress));
- }
+ public void SetRowAddress(byte startAddress = 0x00, byte endAddress = 0x5f) => SendCommand(new Ssd1327Cmnds.SetRowAddress(startAddress, endAddress));
///
/// Clears the display
@@ -74,19 +68,13 @@ public void SendCommand(byte command)
/// Sends command to the device
///
/// Command being send
- public void SendCommand(ISsd1327Command command)
- {
- SendCommand((ICommand)command);
- }
+ public void SendCommand(ISsd1327Command command) => SendCommand((ICommand)command);
///
/// Sends command to the device
///
/// Command being send
- public override void SendCommand(ISharedCommand command)
- {
- SendCommand(command);
- }
+ public override void SendCommand(ISharedCommand command) => SendCommand(command);
///
/// Send data to the display controller.
@@ -101,16 +89,12 @@ public void SendData(byte data)
private void SendCommand(ICommand command)
{
- byte[] commandBytes = command.GetBytes();
-
- if (commandBytes == null)
- {
- throw new ArgumentNullException(nameof(commandBytes));
- }
+#pragma warning disable SA1011
+ byte[]? commandBytes = command?.GetBytes();
- if (commandBytes.Length == 0)
+ if (commandBytes is not { Length: >0 })
{
- throw new ArgumentException("The command did not contain any bytes to send.");
+ throw new ArgumentException(nameof(command), "Argument is either null or there were no bytes to send.");
}
foreach (var item in commandBytes)
diff --git a/src/devices/Ssd13xx/Ssd13xx.cs b/src/devices/Ssd13xx/Ssd13xx.cs
index 0c1e084cf8..0618008c09 100644
--- a/src/devices/Ssd13xx/Ssd13xx.cs
+++ b/src/devices/Ssd13xx/Ssd13xx.cs
@@ -29,7 +29,7 @@ public abstract class Ssd13xx : IDisposable
public Ssd13xx(I2cDevice i2cDevice, int bufferSize = DefaultBufferSize)
{
_genericBuffer = new byte[bufferSize];
- _i2cDevice = i2cDevice;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
}
///
@@ -56,7 +56,7 @@ internal static bool InRange(uint value, uint start, uint end)
/// The data to send to the display controller.
public virtual void SendData(byte[] data)
{
- if (data == null)
+ if (data is null)
{
throw new ArgumentNullException(nameof(data));
}
@@ -81,10 +81,7 @@ public void Dispose()
///
/// Requested length
/// Span of bytes pointing to the command buffer
- protected Span SliceGenericBuffer(int length)
- {
- return SliceGenericBuffer(0, length);
- }
+ protected Span SliceGenericBuffer(int length) => SliceGenericBuffer(0, length);
///
/// Acquires span of specific length at specific position in command buffer.
diff --git a/src/devices/Ssd13xx/samples/Ssd1306Extensions.cs b/src/devices/Ssd13xx/samples/Ssd1306Extensions.cs
index 1bd4e98ca3..7ff09ac9aa 100644
--- a/src/devices/Ssd13xx/samples/Ssd1306Extensions.cs
+++ b/src/devices/Ssd13xx/samples/Ssd1306Extensions.cs
@@ -22,7 +22,7 @@ internal static void DisplayImage(this Ssd1306 s, Image image)
{
Int16 width = 128;
Int16 pages = 4;
- List buffer = new List();
+ List buffer = new ();
for (int page = 0; page < pages; page++)
{
diff --git a/src/devices/Tcs3472x/Tcs3472x.cs b/src/devices/Tcs3472x/Tcs3472x.cs
index 5a1dfbb1a4..8bf5131a70 100644
--- a/src/devices/Tcs3472x/Tcs3472x.cs
+++ b/src/devices/Tcs3472x/Tcs3472x.cs
@@ -23,7 +23,7 @@ public class Tcs3472x : IDisposable
private byte _integrationTimeByte;
private double _integrationTime;
private bool _isLongTime;
- private bool _autoDisposable;
+ private bool _shouldDispose;
private Gain _gain;
///
@@ -34,10 +34,7 @@ public class Tcs3472x : IDisposable
///
public double IntegrationTime
{
- get
- {
- return _integrationTime;
- }
+ get => _integrationTime;
set
{
_integrationTime = value;
@@ -50,10 +47,7 @@ public double IntegrationTime
///
public Gain Gain
{
- get
- {
- return _gain;
- }
+ get => _gain;
set
{
_gain = value;
@@ -72,13 +66,13 @@ public Gain Gain
/// The I2C Device class
/// The time to wait for sensor to read the data, minimum is 0.024 seconds, maximum in the constructor is 0.7 seconds
/// The gain when integrating the color measurement
- /// true to dispose the I2C Device class at dispose
+ /// true to dispose the I2C Device class at dispose
public Tcs3472x(I2cDevice i2cDevice, double integrationTime = 0.0024, Gain gain = Gain.Gain16X,
- bool autoDisposable = true)
+ bool shouldDispose = true)
{
_i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
// Maximum is 700 ms for the initialization. Value can be changed for a long one but not during this initialization phase
- _autoDisposable = autoDisposable;
+ _shouldDispose = shouldDispose;
_i2cDevice.WriteByte((byte)(Registers.COMMAND_BIT | Registers.ID));
ChipId = (TCS3472Type)_i2cDevice.ReadByte();
_isLongTime = false;
@@ -170,10 +164,8 @@ private void PowerOff()
/// Set/Clear the colors and clear interrupts
///
/// true to set all interrupts, false to clear
- public void SetInterrupt(bool state)
- {
+ public void SetInterrupt(bool state) =>
SetInterrupt(InterruptState.All, state);
- }
///
/// Set/clear a specific interrupt persistence
@@ -246,16 +238,14 @@ private byte I2cRead8(Registers reg)
return _i2cDevice.ReadByte();
}
- private void WriteRegister(Registers reg, byte data)
- {
+ private void WriteRegister(Registers reg, byte data) =>
_i2cDevice.Write(new byte[] { (byte)(Registers.COMMAND_BIT | reg), data });
- }
///
public void Dispose()
{
PowerOff();
- if (_autoDisposable)
+ if (_shouldDispose)
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
diff --git a/src/devices/Tcs3472x/samples/Program.cs b/src/devices/Tcs3472x/samples/Program.cs
index 9ac83e7fc6..70410b5fde 100644
--- a/src/devices/Tcs3472x/samples/Program.cs
+++ b/src/devices/Tcs3472x/samples/Program.cs
@@ -9,7 +9,7 @@
Console.WriteLine("Hello TCS3472x!");
I2cConnectionSettings i2cSettings = new (1, Tcs3472x.DefaultI2cAddress);
using I2cDevice i2cDevice = I2cDevice.Create(i2cSettings);
-using Tcs3472x tcs3472X = new Tcs3472x(i2cDevice);
+using Tcs3472x tcs3472X = new (i2cDevice);
while (!Console.KeyAvailable)
{
Console.WriteLine($"ID: {tcs3472X.ChipId} Gain: {tcs3472X.Gain} Time to wait: {tcs3472X.IsClearInterrupt}");
diff --git a/src/devices/Tm1637/Tm1637.cs b/src/devices/Tm1637/Tm1637.cs
index d46d8c01cc..26f9478d53 100644
--- a/src/devices/Tm1637/Tm1637.cs
+++ b/src/devices/Tm1637/Tm1637.cs
@@ -52,10 +52,8 @@ public Tm1637(int pinClk, int pinDio, PinNumberingScheme pinNumberingScheme = Pi
{
_pinClk = pinClk;
_pinDio = pinDio;
- _controller = gpioController != null
- ? (GpioController)gpioController
- : new GpioController(pinNumberingScheme);
- _shouldDispose = gpioController == null ? true : shouldDispose;
+ _controller = gpioController ?? new GpioController(pinNumberingScheme);
+ _shouldDispose = shouldDispose || gpioController is null;
_controller.OpenPin(_pinClk, PinMode.Output);
_controller.OpenPin(_pinDio, PinMode.Output);
_brightness = 7;
@@ -69,15 +67,12 @@ public Tm1637(int pinClk, int pinDio, PinNumberingScheme pinNumberingScheme = Pi
///
public byte[] CharacterOrder
{
- get
- {
- return _charactersOrder;
- }
+ get => _charactersOrder;
set
{
if (value.Length != MaxCharacters)
{
- throw new ArgumentException($"Size of {nameof(CharacterOrder)} can only be 6 length");
+ throw new ArgumentException(nameof(CharacterOrder), $"Value must be 6 bytes.");
}
// Check if we have all values from 0 to 5
@@ -102,11 +97,7 @@ public byte[] CharacterOrder
///
public bool ScreenOn
{
- get
- {
- return _screenOn;
- }
-
+ get => _screenOn;
set
{
_screenOn = value;
@@ -119,15 +110,12 @@ public bool ScreenOn
///
public byte Brightness
{
- get
- {
- return _brightness;
- }
+ get => _brightness;
set
{
if (value > 7)
{
- throw new ArgumentException($"{nameof(Brightness)} can't be more than 7");
+ throw new ArgumentException(nameof(Brightness), "Value must be less than 8.");
}
_brightness = value;
@@ -225,7 +213,7 @@ private void Display(ReadOnlySpan rawData)
{
if (rawData.Length > MaxCharacters)
{
- throw new ArgumentException($"Maximum number of segments for TM1637 is {MaxCharacters}");
+ throw new ArgumentException(nameof(rawData), $"Maximum number of segments for TM1637 is {MaxCharacters}");
}
// Prepare the buffer with the right order to transfer
@@ -296,7 +284,7 @@ public void Display(byte characterPosition, Character rawData)
{
if (characterPosition > MaxCharacters)
{
- throw new ArgumentException($"Maximum number of characters for TM1637 is {MaxCharacters}");
+ throw new ArgumentException(nameof(characterPosition), $"Maximum number of characters for TM1637 is {MaxCharacters}");
}
// Recreate the buffer in correct order
diff --git a/src/devices/Tm1637/samples/Program.cs b/src/devices/Tm1637/samples/Program.cs
index 9242b9b90b..ce50677e88 100644
--- a/src/devices/Tm1637/samples/Program.cs
+++ b/src/devices/Tm1637/samples/Program.cs
@@ -6,7 +6,7 @@
using Iot.Device.Tm1637;
Console.WriteLine("Hello Tm1637!");
-using Tm1637 tm1637 = new Tm1637(20, 21);
+using Tm1637 tm1637 = new (20, 21);
tm1637.Brightness = 7;
tm1637.ScreenOn = true;
tm1637.ClearDisplay();
diff --git a/src/devices/UFireIse/UFireIse.cs b/src/devices/UFireIse/UFireIse.cs
index 9f6b009846..269de0c7db 100644
--- a/src/devices/UFireIse/UFireIse.cs
+++ b/src/devices/UFireIse/UFireIse.cs
@@ -42,7 +42,6 @@ public class UFireIse : IDisposable
public bool TemperatureCompensation
{
get => _temperatureCompensation;
-
set
{
_temperatureCompensation = value;
@@ -59,15 +58,8 @@ public bool TemperatureCompensation
/// Initializes a new instance of the class.
///
/// The I2C device to be used
- public UFireIse(I2cDevice i2cDevice)
- {
- if (i2cDevice == null)
- {
- throw new ArgumentNullException("i2cDevice can not be null");
- }
-
- _device = i2cDevice;
- }
+ public UFireIse(I2cDevice i2cDevice) =>
+ _device = i2cDevice ?? throw new ArgumentException(nameof(i2cDevice));
///
/// Read a value from the ISE Probe Interface, typical measure are in the millivolt range.
@@ -170,51 +162,40 @@ public void CalibrateFromTwoValuesHighValue(ElectricPotential solution)
/// Returns the firmware version of the device. The manufacturer do not provide any information about the format of the version number, see https://www.ufire.co/docs/uFire_ISE/api.html#getversion
///
/// Firmware version
- public byte GetVersion()
- {
- return ReadByte(Register.ISE_VERSION_REGISTER);
- }
+ public byte GetVersion() =>
+ ReadByte(Register.ISE_VERSION_REGISTER);
///
/// Dual point uses two measures for low and high points. It needs the measured value (reading value) and the known value (reference value). Calling SetDualPointCalibration saves both the reading and reference value.
/// When there are high and low calibration points, the device will automatically use them to adjust readings.To disable dual-point adjustment, call ResetCalibration to remove all calibration data.
///
/// The known value (reference value) for calibrate the high value
- public ElectricPotential GetCalibrateHighReference()
- {
- return new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_REFHIGH_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
- }
+ public ElectricPotential GetCalibrateHighReference() =>
+ new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_REFHIGH_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
///
/// Dual point uses two measures for low and high points. It needs the measured value (reading value) and the known value (reference value). Calling SetDualPointCalibration saves both the reading and reference value.
/// When there are high and low calibration points, the device will automatically use them to adjust readings.To disable dual-point adjustment, call ResetCalibration to remove all calibration data.
///
/// The known value (reference value) for calibrate the low value
- public ElectricPotential GetCalibrateLowReference()
- {
- return new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_REFLOW_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
- }
+ public ElectricPotential GetCalibrateLowReference() =>
+ new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_REFLOW_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
///
/// Dual point uses two measures for low and high points. It needs the measured value (reading value) and the known value (reference value). Calling SetDualPointCalibration saves both the reading and reference value.
/// When there are high and low calibration points, the device will automatically use them to adjust readings.To disable dual-point adjustment, call ResetCalibration to remove all calibration data.
///
/// The measured value (reading value) for calibrate the high value
- public ElectricPotential GetCalibrateHighReading()
- {
- return new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_READHIGH_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
-
- }
+ public ElectricPotential GetCalibrateHighReading() =>
+ new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_READHIGH_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
///
/// Dual point uses two measures for low and high points. It needs the measured value (reading value) and the known value (reference value). Calling SetDualPointCalibration saves both the reading and reference value.
/// When there are high and low calibration points, the device will automatically use them to adjust readings.To disable dual-point adjustment, call ResetCalibration to remove all calibration data.
///
/// The measured value (reading value) for calibrate the low value
- public ElectricPotential GetCalibrateLowReading()
- {
- return new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_READLOW_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
- }
+ public ElectricPotential GetCalibrateLowReading() =>
+ new ElectricPotential(ReadFloat(Register.ISE_CALIBRATE_READLOW_REGISTER), UnitsNet.Units.ElectricPotentialUnit.Millivolt);
///
/// Resets all the stored calibration information.It is possible to run without calibration.
diff --git a/src/devices/UFireIse/UFireOrp.cs b/src/devices/UFireIse/UFireOrp.cs
index a9b23d6efc..5595768b44 100644
--- a/src/devices/UFireIse/UFireOrp.cs
+++ b/src/devices/UFireIse/UFireOrp.cs
@@ -58,9 +58,7 @@ public bool TryMeasureOxidationReductionPotential(out ElectricPotential orp)
return double.IsNaN(mV.Value) || double.IsInfinity(mV.Value);
}
- private float GetProbePotential()
- {
- return ReadEeprom(Register.POTENTIAL_REGISTER);
- }
+ private float GetProbePotential() =>
+ ReadEeprom(Register.POTENTIAL_REGISTER);
}
}
diff --git a/src/devices/UFireIse/UFirePh.cs b/src/devices/UFireIse/UFirePh.cs
index bae49627be..0116b750bd 100644
--- a/src/devices/UFireIse/UFirePh.cs
+++ b/src/devices/UFireIse/UFirePh.cs
@@ -48,7 +48,7 @@ public bool TryMeasurepH(out float pH, Temperature? temp = null)
pH = Convert.ToSingle(Math.Abs(7.0 - (mV.Millivolts / ProbeMvToPh)));
- if (temp != null)
+ if (temp is object)
{
double distanceFrom7 = Math.Abs(7 - Math.Round(Ph));
double distanceFrom25 = Math.Floor(Math.Abs(25 - Math.Round(temp.Value.DegreesCelsius)) / 10);
@@ -92,73 +92,55 @@ public bool TryMeasurepH(out float pH, Temperature? temp = null)
/// Calibrates the probe using a single point using a pH value.
///
/// pH value
- public void CalibrateSingle(float solutionpH)
- {
+ public void CalibrateSingle(float solutionpH) =>
CalibrateSingle(PhToMillivolts(solutionpH));
- }
///
/// Calibrates the dual-point values for the high reading and saves them in the devices's EEPROM.
///
/// The pH of the calibration solution
- public void CalibrateProbeHigh(float solutionpH)
- {
+ public void CalibrateProbeHigh(float solutionpH) =>
CalibrateProbeHigh(PhToMillivolts(solutionpH));
- }
///
/// Returns the dual-point calibration high-reference value.
///
///
- public new float GetCalibrateHighReference()
- {
- return MVtopH(GetCalibrateHighReference());
- }
+ public new float GetCalibrateHighReference() =>
+ MVtopH(GetCalibrateHighReference());
///
/// Returns the dual-point calibration high-reading value.
///
///
- public new float GetCalibrateHighReading()
- {
- return MVtopH(GetCalibrateHighReading());
- }
+ public new float GetCalibrateHighReading() =>
+ MVtopH(GetCalibrateHighReading());
///
/// Calibrates the dual-point values for the low reading and saves them in the devices's EEPROM.
///
/// the pH of the calibration solution
- public void CalibrateProbeLow(float solutionpH)
- {
+ public void CalibrateProbeLow(float solutionpH) =>
CalibrateProbeLow(PhToMillivolts(solutionpH));
- }
///
/// Returns the dual-point calibration low-reference value.
///
///
- public new float GetCalibrateLowReference()
- {
- return MVtopH(GetCalibrateLowReference());
- }
+ public new float GetCalibrateLowReference() =>
+ MVtopH(GetCalibrateLowReference());
///
/// Returns the dual-point calibration low-reading value.
///
///
- public new float GetCalibrateLowReading()
- {
- return MVtopH(GetCalibrateLowReading());
- }
+ public new float GetCalibrateLowReading() =>
+ MVtopH(GetCalibrateLowReading());
- private float PhToMillivolts(float pH)
- {
- return (7 - pH) * ProbeMvToPh;
- }
+ private float PhToMillivolts(float pH) =>
+ (7 - pH) * ProbeMvToPh;
- private float MVtopH(float mV)
- {
- return Convert.ToSingle(Math.Abs(7.0 - (mV / ProbeMvToPh)));
- }
+ private float MVtopH(float mV) =>
+ Convert.ToSingle(Math.Abs(7.0 - (mV / ProbeMvToPh)));
}
}
diff --git a/src/devices/UFireIse/samples/Program.cs b/src/devices/UFireIse/samples/Program.cs
index 1b5a58d484..82134f296a 100644
--- a/src/devices/UFireIse/samples/Program.cs
+++ b/src/devices/UFireIse/samples/Program.cs
@@ -58,7 +58,7 @@ void Basic(I2cDevice device)
void Orp(I2cDevice device)
{
- using UFireOrp uFireOrp = new UFireOrp(device);
+ using UFireOrp uFireOrp = new (device);
if (uFireOrp.TryMeasureOxidationReductionPotential(out ElectricPotential orp))
{
Console.WriteLine("Eh:" + orp.Millivolts);
diff --git a/src/devices/Uln2003/Uln2003.cs b/src/devices/Uln2003/Uln2003.cs
index bb54cb0574..f0615ca1ca 100644
--- a/src/devices/Uln2003/Uln2003.cs
+++ b/src/devices/Uln2003/Uln2003.cs
@@ -74,7 +74,7 @@ public Uln2003(int pin1, int pin2, int pin3, int pin4, GpioController? controlle
_pin4 = pin4;
_controller = controller ?? new GpioController();
- _shouldDispose = controller == null ? true : shouldDispose;
+ _shouldDispose = shouldDispose || controller is null;
_stepsToRotate = stepsToRotate;
_controller.OpenPin(_pin1, PinMode.Output);
diff --git a/src/devices/Vl53L0X/Vl53L0X.cs b/src/devices/Vl53L0X/Vl53L0X.cs
index 91d2ce581a..5efcf84d22 100644
--- a/src/devices/Vl53L0X/Vl53L0X.cs
+++ b/src/devices/Vl53L0X/Vl53L0X.cs
@@ -25,7 +25,7 @@ public class Vl53L0X : IDisposable
///
public const byte DefaultI2cAddress = 0x29;
- private readonly bool _autoDisposable;
+ private readonly bool _shouldDispose;
private readonly int _operationTimeout;
// Default address can be found in documentation
@@ -52,10 +52,7 @@ public class Vl53L0X : IDisposable
///
public bool HighResolution
{
- get
- {
- return _highResolution;
- }
+ get => _highResolution;
set
{
_highResolution = value;
@@ -68,11 +65,11 @@ public bool HighResolution
///
/// The I2C Device
/// Timeout for reading data, by default 500 milliseonds
- /// True to dispose the I2C Device at dispose
- public Vl53L0X(I2cDevice i2cDevice, int operationTimeoutMilliseconds = 500, bool autoDisposable = true)
+ /// True to dispose the I2C Device at dispose
+ public Vl53L0X(I2cDevice i2cDevice, int operationTimeoutMilliseconds = 500, bool shouldDispose = true)
{
- _i2cDevice = i2cDevice ?? throw new ArgumentException($"{nameof(i2cDevice)} can't be null.");
- _autoDisposable = autoDisposable;
+ _i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
+ _shouldDispose = shouldDispose;
_operationTimeout = operationTimeoutMilliseconds;
Reset();
Init();
@@ -97,7 +94,7 @@ public static void ChangeI2cAddress(I2cDevice i2cDevice, byte newAddress)
{
if (newAddress > 0x7F)
{
- throw new ArgumentException($"{nameof(newAddress)} can't exceed 0x7F");
+ throw new ArgumentException(nameof(newAddress), "Value can't exceed 0x7F");
}
try
@@ -146,7 +143,7 @@ public void StartContinuousMeasurement(int periodMilliseconds = 0)
/// Reads the measurement when the mode is set to continuious.
///
/// The range in millimeters, a maximum value is returned depending on the various settings
- private ushort ReadContinuousMeasrurementMillimeters()
+ private ushort ReadContinuousMeasurementMillimeters()
{
Stopwatch stopWatch = Stopwatch.StartNew();
var expirationMilliseconds = stopWatch.ElapsedMilliseconds + _operationTimeout;
@@ -154,7 +151,7 @@ private ushort ReadContinuousMeasrurementMillimeters()
{
if (stopWatch.ElapsedMilliseconds > expirationMilliseconds)
{
- throw new IOException($"{nameof(ReadContinuousMeasrurementMillimeters)} timeout error");
+ throw new IOException($"{nameof(ReadContinuousMeasurementMillimeters)} timeout error");
}
}
@@ -169,7 +166,7 @@ private ushort ReadContinuousMeasrurementMillimeters()
/// Get the distance depending on the measurement mode
///
public ushort Distance =>
- MeasurementMode == MeasurementMode.Continuous ? DistanceContinous : GetDistanceOnce(true);
+ MeasurementMode == MeasurementMode.Continuous ? DistanceContinuous : GetDistanceOnce(true);
///
/// Get/Set the measurement mode used to return the distance property
@@ -181,7 +178,7 @@ private ushort ReadContinuousMeasrurementMillimeters()
/// It is recommended to used this method to gethigher quality measurements
///
/// Returns the distance in millimeters, if any error, returns the maximum range so 8190
- public ushort DistanceContinous
+ public ushort DistanceContinuous
{
get
{
@@ -190,7 +187,7 @@ public ushort DistanceContinous
StartContinuousMeasurement();
}
- return ReadContinuousMeasrurementMillimeters();
+ return ReadContinuousMeasurementMillimeters();
}
}
@@ -259,7 +256,7 @@ public ushort DistanceSingleMeasurement
}
}
- return ReadContinuousMeasrurementMillimeters();
+ return ReadContinuousMeasurementMillimeters();
}
}
@@ -413,11 +410,7 @@ internal bool SetVcselPulsePeriod(VcselType type, PeriodPulse periodPclks)
///
public Precision Precision
{
- get
- {
- return _precision;
- }
-
+ get => _precision;
set
{
_precision = value;
@@ -1140,7 +1133,7 @@ public void SetSignalRateLimit(double limitMcps)
{
if ((limitMcps < 0) || (limitMcps > 511.99))
{
- throw new ArgumentException($"{nameof(limitMcps)} can't be negative and more than 511.99");
+ throw new ArgumentException(nameof(limitMcps), "Value can't be negative or greater than 511.99");
}
// Q9.7 fixed point format (9 integer bits, 7 fractional bits)
@@ -1177,7 +1170,7 @@ private bool PerformSingleRefCalibration(byte vhvInitByte)
///
public void Dispose()
{
- if (_autoDisposable)
+ if (_shouldDispose)
{
_i2cDevice?.Dispose();
_i2cDevice = null!;
diff --git a/src/devices/Vl53L0X/samples/Program.cs b/src/devices/Vl53L0X/samples/Program.cs
index 5fb31fc0c1..94d6ba954c 100644
--- a/src/devices/Vl53L0X/samples/Program.cs
+++ b/src/devices/Vl53L0X/samples/Program.cs
@@ -7,7 +7,7 @@
using Iot.Device.Vl53L0X;
Console.WriteLine("Hello VL53L0X!");
-using Vl53L0X vL53L0X = new Vl53L0X(I2cDevice.Create(new I2cConnectionSettings(1, Vl53L0X.DefaultI2cAddress)));
+using Vl53L0X vL53L0X = new (I2cDevice.Create(new I2cConnectionSettings(1, Vl53L0X.DefaultI2cAddress)));
Console.WriteLine($"Rev: {vL53L0X.Information.Revision}, Prod: {vL53L0X.Information.ProductId}, Mod: {vL53L0X.Information.ModuleId}");
Console.WriteLine($"Offset in µm: {vL53L0X.Information.OffsetMicrometers}, Signal rate fixed 400 µm: {vL53L0X.Information.SignalRateMeasuementFixed400Micrometers}");
vL53L0X.MeasurementMode = MeasurementMode.Continuous;
diff --git a/src/devices/Ws28xx/Ws28xx.cs b/src/devices/Ws28xx/Ws28xx.cs
index e0b33a54ec..222492f157 100644
--- a/src/devices/Ws28xx/Ws28xx.cs
+++ b/src/devices/Ws28xx/Ws28xx.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
+using System;
using System.Device.Spi;
using Iot.Device.Graphics;
@@ -28,7 +29,7 @@ public class Ws28xx
/// The bitmap that represents the screen or led strip.
public Ws28xx(SpiDevice spiDevice, BitmapImage image)
{
- _spiDevice = spiDevice;
+ _spiDevice = spiDevice ?? throw new ArgumentNullException(nameof(spiDevice));
Image = image;
}