123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- using System;
- using System.Threading.Tasks;
- using UniRx;
- using UnityEngine;
- using UnityEngine.Serialization;
- namespace Sensors.Polar
- {
- [System.Serializable]
- public struct PolarSensorConfig
- {
- public int port;
- public string ipAddress;
- [Tooltip("25, 50, 100 or 200")] public int accSampleRate; //TODO: let user choose between 25, 50, 100, 200
- public PolarSensorConfig(int port = 9099, string ipAddress = "0.0.0.0", int accSampleRate = 25)
- {
- this.port = port;
- this.ipAddress = ipAddress;
- this.accSampleRate = accSampleRate;
- }
- }
- public struct PolarSensorData
- {
- public Vector3 Acc;
- public float EcgValue;
- }
- public class PolarReceiver
- {
- private UdpConnection connection;
- private PolarSensorData sensorData;
- private readonly Subject<EcgData> rawEcgDataSubject = new Subject<EcgData>();
- private readonly Subject<AccData> rawAccDataSubject = new Subject<AccData>();
- public IObservable<EcgData> RawEcgData => rawEcgDataSubject.AsObservable();
- public IObservable<AccData> RawAccData => rawAccDataSubject.AsObservable();
- public PolarSensorConfig SensorConfig { get; private set; }
- public PolarSensorData SensorData => sensorData;
- public PolarReceiver(PolarSensorConfig config)
- {
- SensorConfig = config;
- }
- public void StartListening()
- {
- connection = new UdpConnection(SensorConfig.ipAddress, SensorConfig.port, OnAccData, OnEcgData);
- connection.Listen();
- Debug.Log("PolarReceiver: Listening!");
- }
- public void Dispose()
- {
- rawAccDataSubject.Dispose();
- rawEcgDataSubject.Dispose();
- connection.StopListening();
- }
- private async void OnAccData(AccData data)
- {
- rawAccDataSubject.OnNext(data);
- await UpdateSensorDataForAcc(data);
- }
- private async Task UpdateSensorDataForAcc(AccData data)
- {
- foreach (var item in data.Values)
- {
- sensorData.Acc = item;
- await Task.Delay(1000 / SensorConfig.accSampleRate);
- }
- }
- private void OnEcgData(EcgData data)
- {
- rawEcgDataSubject.OnNext(data);
- sensorData.EcgValue = data.Values[0]; //TODO
- }
- }
- }
|