Skip to content

Commit

Permalink
Gracefully handle new controller connection / disconnection (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
aidy-jenkins authored Jun 11, 2022
1 parent 0d7c6e4 commit 4992751
Showing 1 changed file with 30 additions and 16 deletions.
46 changes: 30 additions & 16 deletions WebVideoGamepad.NET/GamepadReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WebAppHost.NetFramework
Expand Down Expand Up @@ -36,25 +36,42 @@ public GamepadReader(ControllerConfig config)
_controllerConfig = config;
_axisNeutralPoint = config.AxisMaxValue / 2;
_input = new DirectInput();
var devices = _input.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly);

_joysticks = devices.Select(device => new Joystick(_input, device.InstanceGuid)).ToArray();
_ = Task.Run(CheckForControllerChanges);
}

foreach (var joystick in _joysticks)
public void CheckForControllerChanges()
{
while (true)
{
joystick.Acquire();
var devices = _input.GetDevices(DeviceType.Gamepad, DeviceEnumerationFlags.AttachedOnly);

_joysticks = devices.Select(device => new Joystick(_input, device.InstanceGuid)).ToArray();

foreach (var joystick in _joysticks)
{
joystick.Acquire();
}

Thread.Sleep(5000);
}
}

public (DirectionState, ButtonState) ReadState()
{
try
{
DirectionState directionState = default;
ButtonState buttonState = default;
DirectionState directionState = default;
ButtonState buttonState = default;

foreach (var joystick in _joysticks)
var joysticks = _joysticks;

if (joysticks == null)
return default;

foreach (var joystick in joysticks)
{
try
{

joystick.Poll();
var state = joystick.GetCurrentState();

Expand All @@ -65,13 +82,10 @@ public GamepadReader(ControllerConfig config)
foreach (var button in pressedButtons)
buttonState |= ReadButtonState(button);
}

return (directionState, buttonState);
}
catch (Exception ex)
{
throw new Exception("Failed to read controller state", ex);
catch { /* do nothing */ }
}

return (directionState, buttonState);
}

private static ButtonState ReadButtonState((bool pressed, int index) button)
Expand Down

0 comments on commit 4992751

Please sign in to comment.