RomaDeviceInfoReceiver.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. using UnityEngine;
  7. namespace LightGlue.Unity.Roma.Networking
  8. {
  9. /// <summary>
  10. /// 接收 Python 上报的设备信息(JSON over UDP)。
  11. /// 典型用途:ESP32 无广播时,从 Python 收图线程“学到”的 source_ip/source_port 回填到 Unity UI。
  12. /// JSON 示例:{"device_ip":"192.168.0.16","device_port":12346,"ts":1710000000.0}
  13. /// </summary>
  14. public sealed class RomaDeviceInfoReceiver : MonoBehaviour
  15. {
  16. [Header("Listen")]
  17. public string bindIp = "0.0.0.0";
  18. public int port = 12350;
  19. public bool autoStartOnEnable = true;
  20. [Header("State (readonly)")]
  21. [SerializeField] private string latestDeviceIp;
  22. [SerializeField] private int latestDevicePort;
  23. [SerializeField] private bool hasLatest;
  24. public string LatestDeviceIp => latestDeviceIp;
  25. public int LatestDevicePort => latestDevicePort;
  26. public bool HasLatest => hasLatest;
  27. public event Action<string, int> OnDeviceInfoUpdated;
  28. private UdpClient _client;
  29. private Thread _thread;
  30. private volatile bool _running;
  31. private readonly object _lock = new object();
  32. private string _pendingIp;
  33. private int _pendingPort;
  34. private bool _hasPending;
  35. [Serializable]
  36. private class DeviceInfoMsg
  37. {
  38. public string device_ip;
  39. public int device_port;
  40. public double ts;
  41. }
  42. private void OnEnable()
  43. {
  44. if (autoStartOnEnable)
  45. StartListening();
  46. }
  47. private void OnDisable()
  48. {
  49. StopListening();
  50. }
  51. private void Update()
  52. {
  53. string ip = null;
  54. int p = 0;
  55. bool has = false;
  56. lock (_lock)
  57. {
  58. if (_hasPending)
  59. {
  60. ip = _pendingIp;
  61. p = _pendingPort;
  62. has = true;
  63. _hasPending = false;
  64. }
  65. }
  66. if (!has || string.IsNullOrWhiteSpace(ip)) return;
  67. latestDeviceIp = ip;
  68. latestDevicePort = p;
  69. hasLatest = true;
  70. OnDeviceInfoUpdated?.Invoke(ip, p);
  71. }
  72. public void StartListening()
  73. {
  74. if (_running) return;
  75. try
  76. {
  77. var ip = IPAddress.Parse(string.IsNullOrWhiteSpace(bindIp) ? "0.0.0.0" : bindIp);
  78. _client = new UdpClient(new IPEndPoint(ip, port));
  79. _client.Client.ReceiveTimeout = 200;
  80. _running = true;
  81. _thread = new Thread(ReceiveLoop) { IsBackground = true, Name = "RomaDeviceInfoReceiver" };
  82. _thread.Start();
  83. Debug.Log($"[RomaDevInfo] Listening on {bindIp}:{port}");
  84. }
  85. catch (Exception ex)
  86. {
  87. Debug.LogWarning($"[RomaDevInfo] Start failed: {ex.Message}");
  88. Cleanup();
  89. }
  90. }
  91. public void StopListening()
  92. {
  93. _running = false;
  94. try { _client?.Close(); } catch { /* ignore */ }
  95. try { _client?.Dispose(); } catch { /* ignore */ }
  96. _client = null;
  97. if (_thread != null && _thread.IsAlive)
  98. {
  99. if (!_thread.Join(500))
  100. {
  101. try { _thread.Interrupt(); } catch { /* ignore */ }
  102. }
  103. }
  104. _thread = null;
  105. }
  106. private void ReceiveLoop()
  107. {
  108. var remote = new IPEndPoint(IPAddress.Any, 0);
  109. while (_running)
  110. {
  111. try
  112. {
  113. byte[] data = _client.Receive(ref remote);
  114. if (data == null || data.Length == 0) continue;
  115. string json = Encoding.UTF8.GetString(data);
  116. DeviceInfoMsg msg = JsonUtility.FromJson<DeviceInfoMsg>(json);
  117. if (msg == null || string.IsNullOrWhiteSpace(msg.device_ip)) continue;
  118. int p = msg.device_port;
  119. lock (_lock)
  120. {
  121. _pendingIp = msg.device_ip;
  122. _pendingPort = p;
  123. _hasPending = true;
  124. }
  125. }
  126. catch (SocketException)
  127. {
  128. continue;
  129. }
  130. catch (ObjectDisposedException)
  131. {
  132. break;
  133. }
  134. catch (ThreadInterruptedException)
  135. {
  136. break;
  137. }
  138. catch (Exception ex)
  139. {
  140. Debug.LogWarning($"[RomaDevInfo] Receive error: {ex.Message}");
  141. }
  142. }
  143. }
  144. private void Cleanup()
  145. {
  146. _running = false;
  147. try { _client?.Close(); } catch { /* ignore */ }
  148. try { _client?.Dispose(); } catch { /* ignore */ }
  149. _client = null;
  150. }
  151. }
  152. }