UdpConnection.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. var parsedAddress = IPAddress.Parse(ipAddress);
  22. client = new UdpClient(new IPEndPoint(parsedAddress, port));
  23. }
  24. public void Listen() => Task.Run(async () =>
  25. {
  26. listening = true;
  27. while (listening)
  28. {
  29. var result = await client.ReceiveAsync();
  30. string receivedStr = Encoding.UTF8.GetString(result.Buffer);
  31. var data = receivedStr.Split(':');
  32. if (data.Length == 2)
  33. {
  34. var name = data[0];
  35. if (name.Equals("ACC"))
  36. {
  37. onAccData(AccData.FromString(data[1]));
  38. }else if (name.Equals("ECG"))
  39. {
  40. onEcgData(EcgData.FromString(data[1]));
  41. }else if (name.Equals("HR"))
  42. {
  43. //TODO
  44. }
  45. }
  46. //Debug.Log($"RECEIVED DATA VIA UDP: {receivedStr}");
  47. }
  48. });
  49. public void StopListening()
  50. {
  51. listening = false;
  52. }
  53. }
  54. }