UdpConnection.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Sensors.Bluetooth;
  7. namespace Sensors.Polar
  8. {
  9. public class UdpConnection
  10. {
  11. //public int port = 9090;
  12. //public String ipAddress = "192.168.1.7";
  13. private readonly UdpClient client;
  14. private bool listening;
  15. private readonly Action<AccData> onAccData;
  16. private readonly Action<EcgData> onEcgData;
  17. private readonly Action<HRData> onHRData;
  18. private readonly Action<RawPowermeterData> onPowermeterData;
  19. public UdpConnection(string ipAddress, int port, Action<AccData> onAccData, Action<EcgData> onEcgData,
  20. Action<HRData> onHrData, Action<RawPowermeterData> onPowermeterData)
  21. {
  22. this.onPowermeterData = onPowermeterData;
  23. this.onAccData = onAccData;
  24. this.onEcgData = onEcgData;
  25. onHRData = onHrData;
  26. var parsedAddress = IPAddress.Parse(ipAddress);
  27. client = new UdpClient(new IPEndPoint(parsedAddress, port));
  28. }
  29. public void Listen()
  30. {
  31. Task.Run(async () =>
  32. {
  33. listening = true;
  34. while (listening)
  35. {
  36. var result = await client.ReceiveAsync();
  37. var receivedStr = Encoding.UTF8.GetString(result.Buffer);
  38. var data = receivedStr.Split(':');
  39. if (data.Length == 2)
  40. {
  41. var name = data[0];
  42. if (name.Equals("ACC"))
  43. onAccData(AccData.FromString(data[1]));
  44. else if (name.Equals("ECG"))
  45. onEcgData(EcgData.FromString(data[1]));
  46. else if (name.Equals("HR")) onHRData(HRData.FromString(data[1]));
  47. else if (name.Equals("POW")) onPowermeterData(RawPowermeterData.FromString(data[1]));
  48. }
  49. //Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
  50. }
  51. });
  52. }
  53. public void StopListening()
  54. {
  55. listening = false;
  56. }
  57. }
  58. }