TrackerIndexManager.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using UnityEngine;
  5. using Valve.VR;
  6. using Debug = UnityEngine.Debug;
  7. namespace Tracking
  8. {
  9. public class TrackerIndexManager : MonoBehaviour
  10. {
  11. private IEnumerable<IViveTracker> trackers;
  12. private void OnEnable()
  13. {
  14. SteamVR_Events.DeviceConnected.Listen(OnDeviceConnected);
  15. trackers = GetComponentsInChildren<IViveTracker>();
  16. }
  17. private void OnDeviceConnected(int index, bool connected)
  18. {
  19. if (index < 0) return;
  20. if (!connected || OpenVR.System == null) return;
  21. var deviceClass = OpenVR.System.GetTrackedDeviceClass((uint) index);
  22. if (deviceClass != ETrackedDeviceClass.GenericTracker) return;
  23. SetIndexForSerialNumber(index);
  24. SetBatteryLevelForIndex(index);
  25. }
  26. private void SetBatteryLevelForIndex(int index)
  27. {
  28. var error = ETrackedPropertyError.TrackedProp_Success;
  29. var batteryLevel = OpenVR.System.GetFloatTrackedDeviceProperty((uint) index,
  30. ETrackedDeviceProperty.Prop_DeviceBatteryPercentage_Float, ref error);
  31. if (error != ETrackedPropertyError.TrackedProp_Success)
  32. {
  33. Debug.LogWarning($"Could not get serial number for tracker at index {index}");
  34. }
  35. else
  36. {
  37. var t = trackers.FirstOrDefault(tracker => (int) tracker.TrackedObject.index == index);
  38. if (t != null) t.BatteryLevel = batteryLevel;
  39. }
  40. }
  41. private void SetIndexForSerialNumber(int index)
  42. {
  43. var error = ETrackedPropertyError.TrackedProp_Success;
  44. var serialNumberBuilder = new StringBuilder();
  45. OpenVR.System.GetStringTrackedDeviceProperty((uint) index,
  46. ETrackedDeviceProperty.Prop_SerialNumber_String, serialNumberBuilder, 64, ref error);
  47. if (error != ETrackedPropertyError.TrackedProp_Success)
  48. {
  49. Debug.LogError($"Could not get serial number for tracker at index {index}");
  50. }
  51. else
  52. {
  53. var t = trackers.FirstOrDefault(tracker => tracker.Id == serialNumberBuilder.ToString());
  54. t?.TrackedObject.SetDeviceIndex(index);
  55. }
  56. }
  57. }
  58. }