PolarReceiver.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Threading.Tasks;
  3. using UniRx;
  4. using UnityEngine;
  5. using UnityEngine.Serialization;
  6. namespace Sensors.Polar
  7. {
  8. [System.Serializable]
  9. public struct PolarSensorConfig
  10. {
  11. public int port;
  12. public string ipAddress;
  13. [Tooltip("25, 50, 100 or 200")] public int accSampleRate; //TODO: let user choose between 25, 50, 100, 200
  14. public PolarSensorConfig(int port = 9099, string ipAddress = "0.0.0.0", int accSampleRate = 25)
  15. {
  16. this.port = port;
  17. this.ipAddress = ipAddress;
  18. this.accSampleRate = accSampleRate;
  19. }
  20. }
  21. public struct PolarSensorData
  22. {
  23. public Vector3 Acc;
  24. public float EcgValue;
  25. }
  26. public class PolarReceiver
  27. {
  28. private UdpConnection connection;
  29. private PolarSensorData sensorData;
  30. private readonly Subject<EcgData> rawEcgDataSubject = new Subject<EcgData>();
  31. private readonly Subject<AccData> rawAccDataSubject = new Subject<AccData>();
  32. public IObservable<EcgData> RawEcgData => rawEcgDataSubject.AsObservable();
  33. public IObservable<AccData> RawAccData => rawAccDataSubject.AsObservable();
  34. public PolarSensorConfig SensorConfig { get; private set; }
  35. public PolarSensorData SensorData => sensorData;
  36. public PolarReceiver(PolarSensorConfig config)
  37. {
  38. SensorConfig = config;
  39. }
  40. public void StartListening()
  41. {
  42. connection = new UdpConnection(SensorConfig.ipAddress, SensorConfig.port, OnAccData, OnEcgData);
  43. connection.Listen();
  44. Debug.Log("PolarReceiver: Listening!");
  45. }
  46. public void Dispose()
  47. {
  48. rawAccDataSubject.Dispose();
  49. rawEcgDataSubject.Dispose();
  50. connection.StopListening();
  51. }
  52. private async void OnAccData(AccData data)
  53. {
  54. rawAccDataSubject.OnNext(data);
  55. await UpdateSensorDataForAcc(data);
  56. }
  57. private async Task UpdateSensorDataForAcc(AccData data)
  58. {
  59. foreach (var item in data.Values)
  60. {
  61. sensorData.Acc = item;
  62. await Task.Delay(1000 / SensorConfig.accSampleRate);
  63. }
  64. }
  65. private void OnEcgData(EcgData data)
  66. {
  67. rawEcgDataSubject.OnNext(data);
  68. sensorData.EcgValue = data.Values[0]; //TODO
  69. }
  70. }
  71. }