2
0

UdpConnection.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  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 UdpClient client;
  14. private bool listening = false;
  15. private Action<AccData> onAccData;
  16. private Action<EcgData> onEcgData;
  17. public UdpConnection(String ipAddress, int port, Action<AccData> onAccData, Action<EcgData> onEcgData)
  18. {
  19. this.onAccData = onAccData;
  20. this.onEcgData = onEcgData;
  21. client = new UdpClient(new IPEndPoint(IPAddress.Parse(ipAddress), port));
  22. }
  23. public void Listen() => Task.Run(async () =>
  24. {
  25. listening = true;
  26. while (listening)
  27. {
  28. var result = await client.ReceiveAsync();
  29. string receivedStr = Encoding.UTF8.GetString(result.Buffer);
  30. var data = receivedStr.Split(':');
  31. if (data.Length == 2)
  32. {
  33. var name = data[0];
  34. if (name.Equals("ACC"))
  35. {
  36. onAccData(AccData.FromString(data[1]));
  37. }else if (name.Equals("ECG"))
  38. {
  39. onEcgData(EcgData.FromString(data[1]));
  40. }else if (name.Equals("HR"))
  41. {
  42. //TODO
  43. }
  44. }
  45. //Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
  46. }
  47. });
  48. public void StopListening()
  49. {
  50. listening = false;
  51. }
  52. }
  53. }