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 rawEcgDataSubject = new Subject(); private readonly Subject rawAccDataSubject = new Subject(); public IObservable RawEcgData => rawEcgDataSubject.AsObservable(); public IObservable 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 } } }