123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- using Sensors.Bluetooth;
- namespace Sensors.Polar
- {
- public class UdpConnection
- {
- //public int port = 9090;
- //public String ipAddress = "192.168.1.7";
- private readonly UdpClient client;
- private bool listening;
- private readonly Action<AccData> onAccData;
- private readonly Action<EcgData> onEcgData;
- private readonly Action<HRData> onHRData;
- private readonly Action<RawPowermeterData> onPowermeterData;
- public UdpConnection(string ipAddress, int port, Action<AccData> onAccData, Action<EcgData> onEcgData,
- Action<HRData> onHrData, Action<RawPowermeterData> onPowermeterData)
- {
- this.onPowermeterData = onPowermeterData;
- this.onAccData = onAccData;
- this.onEcgData = onEcgData;
- onHRData = onHrData;
- var parsedAddress = IPAddress.Parse(ipAddress);
- client = new UdpClient(new IPEndPoint(parsedAddress, port));
- }
- public void Listen()
- {
- Task.Run(async () =>
- {
- listening = true;
- while (listening)
- {
- var result = await client.ReceiveAsync();
- var receivedStr = Encoding.UTF8.GetString(result.Buffer);
- var data = receivedStr.Split(':');
- if (data.Length == 2)
- {
- var name = data[0];
- if (name.Equals("ACC"))
- onAccData(AccData.FromString(data[1]));
- else if (name.Equals("ECG"))
- onEcgData(EcgData.FromString(data[1]));
- else if (name.Equals("HR")) onHRData(HRData.FromString(data[1]));
- else if (name.Equals("POW")) onPowermeterData(RawPowermeterData.FromString(data[1]));
- }
- //Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
- }
- });
- }
- public void StopListening()
- {
- listening = false;
- }
- }
- }
|