Skip to content

Commit e9e61b4

Browse files
committed
fix: Update UWP bluetooth manager to deal gracefully with Cancellation events
If a bluetooth device loses power, it can cause a TaskCanceledException to be thrown instead of InvalidOperationException. Make sure we catch all exceptions.
1 parent 6967339 commit e9e61b4

1 file changed

Lines changed: 17 additions & 6 deletions

File tree

Buttplug.Server.Managers.UWPBluetoothManager/UWPBluetoothDeviceInterface.cs

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,8 @@ public UWPBluetoothDeviceInterface(
4949
foreach (var item in aInfo.Characteristics)
5050
{
5151
var c = (from x in aChars
52-
where x.Uuid == item.Value
53-
select x).ToArray();
52+
where x.Uuid == item.Value
53+
select x).ToArray();
5454
if (c.Length != 1)
5555
{
5656
var err = $"Cannot find characteristic ${item.Value} for device {Name}";
@@ -164,20 +164,31 @@ private async Task<ButtplugMessage> WriteValue(uint aMsgId,
164164
_bpLogger.Error("Cancelling device transfer in progress for new transfer.");
165165
}
166166

167-
_currentTask = aChar.WriteValueAsync(aValue.AsBuffer(), aWriteWithResponse ? GattWriteOption.WriteWithResponse : GattWriteOption.WriteWithoutResponse);
168167
try
169168
{
169+
_currentTask = aChar.WriteValueAsync(aValue.AsBuffer(),
170+
aWriteWithResponse ? GattWriteOption.WriteWithResponse : GattWriteOption.WriteWithoutResponse);
170171
var status = await _currentTask;
171172
_currentTask = null;
172173
if (status != GattCommunicationStatus.Success)
173174
{
174-
return _bpLogger.LogErrorMsg(aMsgId, Error.ErrorClass.ERROR_DEVICE, $"GattCommunication Error: {status}");
175+
return _bpLogger.LogErrorMsg(aMsgId, Error.ErrorClass.ERROR_DEVICE,
176+
$"GattCommunication Error: {status}");
175177
}
176178
}
177179
catch (InvalidOperationException e)
178180
{
179-
// This exception will be thrown if the bluetooth device disconnects in the middle of a transfer.
180-
return _bpLogger.LogErrorMsg(aMsgId, Error.ErrorClass.ERROR_DEVICE, $"GattCommunication Error: {e.Message}");
181+
// This exception will be thrown if the bluetooth device disconnects in the middle of
182+
// a transfer.
183+
return _bpLogger.LogErrorMsg(aMsgId, Error.ErrorClass.ERROR_DEVICE,
184+
$"GattCommunication Error: {e.Message}");
185+
}
186+
catch (TaskCanceledException e)
187+
{
188+
// This exception will be thrown if the bluetooth device disconnects in the middle of
189+
// a transfer (happened when MysteryVibe lost power).
190+
return _bpLogger.LogErrorMsg(aMsgId, Error.ErrorClass.ERROR_DEVICE,
191+
$"Device disconnected: {e.Message}");
181192
}
182193

183194
return new Ok(aMsgId);

0 commit comments

Comments
 (0)