From f901bd01a7edfbdb565cc1a27dfab74956df140d Mon Sep 17 00:00:00 2001 From: Martijn Steenbergen Date: Sat, 6 Feb 2021 20:09:56 +0100 Subject: [PATCH] Update Device.IDeviceController.cs **Describe the bug** ```csharp using (YeelightAPI.Device device = new YeelightAPI.Device(ip, port)) { await device.Connect(); await function(device); } ``` When this code tries to connect to a lamp, which is not turned on, it will throw a `System.Net.Internals.SocketExceptionFactory+ExtendedSocketException (113)` with message `No route to host YOURIP:YOURPORT`. This in turn will propogate upward. As I'm using a `using` statement, it will call Dispose in this fashion: ``` at YeelightAPI.Device.Disconnect() at YeelightAPI.Device.Dispose(Boolean disposing) at YeelightAPI.Device.Dispose() ``` In the Disconnect method, [this line](https://github.com/roddone/YeelightAPI/blob/8b8874a8380c5a60925ca28a838e75297783e13c/YeelightAPI/Device.IDeviceController.cs#L160) exists: ```csharp _watchCancellationTokenSource.Cancel(); ``` However, since, we never connected initiated this object, it will throw a `NullReferenceException`. **Expected behavior** A `SocketException` **Actual behaviour** A `NullReferenceException` **Fix** One question mark --- YeelightAPI/Device.IDeviceController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/YeelightAPI/Device.IDeviceController.cs b/YeelightAPI/Device.IDeviceController.cs index 03f4bcb..6f600b8 100644 --- a/YeelightAPI/Device.IDeviceController.cs +++ b/YeelightAPI/Device.IDeviceController.cs @@ -157,7 +157,7 @@ public void Disconnect() _tcpClient = null; try { - _watchCancellationTokenSource.Cancel(); + _watchCancellationTokenSource?.Cancel(); } catch (ObjectDisposedException) { } } @@ -452,4 +452,4 @@ public async Task TurnOn(int? smooth = null, PowerOnMode mode = PowerOnMod #endregion Public Methods } -} \ No newline at end of file +}