Created
May 3, 2021 09:28
-
-
Save Bunkerbewohner/1dc1ec5b5ab0f7fd94d0b2d3cc62c11d to your computer and use it in GitHub Desktop.
Detecting wireless Buzz! buzzers with Unity engine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using HidSharp; // https://www.nuget.org/packages/HidSharp/ | |
using UnityEngine; | |
namespace Goldsaucer.Askutron.HardwareInput | |
{ | |
public class WirelessBuzzBuzzers : MonoBehaviour | |
{ | |
class ConnectedReceiver | |
{ | |
public DeviceStream stream; | |
} | |
private readonly List<ConnectedReceiver> _connected = new List<ConnectedReceiver>(); | |
private void Start() | |
{ | |
if (!Application.isEditor) | |
{ | |
Detect(); | |
} | |
else | |
{ | |
// do not detect buzzers every time because this crashes the editor | |
// due to some bug in the HID library | |
// Use the reset function of this component to explicitly detect | |
// buzzers once. | |
} | |
} | |
private void Reset() | |
{ | |
Detect(); | |
} | |
public void Detect() | |
{ | |
foreach (var dev in DeviceList.Local.GetAllDevices()) | |
{ | |
Debug.Log("Found device: " + dev.GetFriendlyName()); | |
if (dev.GetFriendlyName().ToLower().Contains("wbuzz")) | |
{ | |
ConnectBuzzer(dev); | |
} | |
else if (dev.GetFriendlyName().ToLower().Contains("buzz")) | |
{ | |
Debug.Log($"Found potential buzzer ${dev.GetFriendlyName()}"); | |
} | |
} | |
} | |
private void ConnectBuzzer(Device device) | |
{ | |
DeviceStream stream; | |
if (device.TryOpen(out stream)) | |
{ | |
stream.Write(new byte[] { 0x0 }, 0, 1); | |
_connected.Add(new ConnectedReceiver() {stream = stream}); | |
Debug.Log("Connected " + device.GetFriendlyName()); | |
} | |
else | |
{ | |
Debug.Log("Could not connect " + device.GetFriendlyName()); | |
} | |
} | |
private void OnDestroy() | |
{ | |
foreach (var receiver in _connected) | |
{ | |
receiver.stream.Dispose(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment