TrackerIndexManager.cs 2.3 KB

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