LightGlueClient.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. using LightGlue.Unity.Config;
  6. using LightGlue.Unity.Networking;
  7. using LightGlue.Unity.Python;
  8. using LightGlue.Unity.Sdk.Core.Networking;
  9. using UnityEngine;
  10. namespace LightGlue.Unity.Sdk.Core
  11. {
  12. /// <summary>
  13. /// SDK 原型版:对外统一的 LightGlue 通信客户端。
  14. /// - 组合 JPEG 接收、Python 结果接收、硬件控制 0x40 发送、Unity->Python 图像发送。
  15. /// - 非 MonoBehaviour,由外部(如 BridgeBehaviour)驱动生命周期和 Tick。
  16. /// </summary>
  17. public sealed class LightGlueClient : IDisposable
  18. {
  19. public enum TransferMode
  20. {
  21. Stdin,
  22. Udp
  23. }
  24. public sealed class Options
  25. {
  26. // Hardware -> Unity image stream
  27. public string HardwareBindIp = "0.0.0.0";
  28. public int HardwarePort = 12346;
  29. public float HardwareTimeoutSeconds = 2.0f;
  30. public int MaxQueuedFrames = 2;
  31. // Unity -> Hardware control (0x40)
  32. public string HardwareControlIp = "192.168.0.106";
  33. public int HardwareControlPort = 8888;
  34. // Unity -> Python image
  35. public TransferMode Mode = TransferMode.Stdin;
  36. public string PythonIp = "127.0.0.1";
  37. public int PythonPort = 12347;
  38. public PythonProcessController PythonController;
  39. // Python -> Unity result
  40. public bool EnableResultReceiver = true;
  41. public string PythonResultBindIp = "127.0.0.1";
  42. public int PythonResultPort = 12348;
  43. public int MaxResultQueueSize = 10;
  44. }
  45. private readonly Options _options;
  46. private CoreUDPJpegReceiver _jpegReceiver;
  47. private CoreUDPResultReceiver _resultReceiver;
  48. private UdpClient _pythonUdpSender;
  49. private IPEndPoint _pythonEndpoint;
  50. private UdpClient _hwControlClient;
  51. private IPEndPoint _hwControlEndpoint;
  52. private PythonProcessController _pythonController;
  53. private StreamWriter _stdinWriter;
  54. private ImageTransmissionConfig _transmissionConfig;
  55. private bool _configEnabled = true;
  56. private byte[] _latestJpeg;
  57. private readonly object _jpegLock = new object();
  58. private float _lastSendTimeMs;
  59. public bool IsRunning { get; private set; }
  60. public LightGlueClient(Options options)
  61. {
  62. _options = options ?? throw new ArgumentNullException(nameof(options));
  63. }
  64. /// <summary>
  65. /// 启动所有内部模块(JPEG 接收、结果接收、硬件控制 UDP、Python 图像发送端)。
  66. /// </summary>
  67. public void Start()
  68. {
  69. if (IsRunning) return;
  70. // JPEG receiver
  71. _jpegReceiver = new CoreUDPJpegReceiver(
  72. _options.HardwareBindIp,
  73. _options.HardwarePort,
  74. _options.HardwareTimeoutSeconds,
  75. _options.MaxQueuedFrames);
  76. try
  77. {
  78. _jpegReceiver.Start();
  79. }
  80. catch (SocketException ex)
  81. {
  82. Debug.LogError($"[SDK][Client] Failed to bind JPEG receiver on {_options.HardwareBindIp}:{_options.HardwarePort}: {ex.Message}");
  83. SafeStop(ref _jpegReceiver);
  84. throw;
  85. }
  86. // Unity -> Python sender
  87. if (_options.Mode == TransferMode.Stdin)
  88. {
  89. _pythonController = _options.PythonController;
  90. TryConnectStdin();
  91. }
  92. else
  93. {
  94. var ip = IPAddress.Parse(string.IsNullOrWhiteSpace(_options.PythonIp) ? "127.0.0.1" : _options.PythonIp);
  95. _pythonEndpoint = new IPEndPoint(ip, _options.PythonPort);
  96. _pythonUdpSender = new UdpClient();
  97. Debug.Log($"[SDK][Client] Unity -> Python UDP sender to {_pythonEndpoint.Address}:{_pythonEndpoint.Port}");
  98. }
  99. // Hardware control (0x40)
  100. try
  101. {
  102. string ctrlIp = string.IsNullOrWhiteSpace(_options.HardwareControlIp)
  103. ? "192.168.0.106"
  104. : _options.HardwareControlIp;
  105. var ip = IPAddress.Parse(ctrlIp);
  106. _hwControlEndpoint = new IPEndPoint(ip, _options.HardwareControlPort);
  107. _hwControlClient = new UdpClient();
  108. Debug.Log($"[SDK][Client] Hardware control UDP -> {_hwControlEndpoint.Address}:{_hwControlEndpoint.Port}");
  109. }
  110. catch (Exception ex)
  111. {
  112. Debug.LogError($"[SDK][Client] Hardware control UDP init failed: {ex.Message}");
  113. _hwControlClient = null;
  114. }
  115. // Result receiver
  116. if (_options.EnableResultReceiver)
  117. {
  118. try
  119. {
  120. _resultReceiver = new CoreUDPResultReceiver(
  121. _options.PythonResultBindIp,
  122. _options.PythonResultPort,
  123. _options.MaxResultQueueSize);
  124. _resultReceiver.Start();
  125. Debug.Log($"[SDK][Client] Result receiver on {_options.PythonResultBindIp}:{_options.PythonResultPort}");
  126. }
  127. catch (Exception ex)
  128. {
  129. Debug.LogError($"[SDK][Client] Result receiver init failed: {ex.Message}");
  130. SafeStop(ref _resultReceiver);
  131. _resultReceiver = null;
  132. }
  133. }
  134. IsRunning = true;
  135. }
  136. public void Stop()
  137. {
  138. if (!IsRunning) return;
  139. SafeStop(ref _jpegReceiver);
  140. SafeStop(ref _resultReceiver);
  141. try { _hwControlClient?.Close(); } catch { /* ignore */ }
  142. _hwControlClient = null;
  143. try { _pythonUdpSender?.Close(); } catch { /* ignore */ }
  144. _pythonUdpSender = null;
  145. _stdinWriter = null;
  146. _pythonController = null;
  147. IsRunning = false;
  148. }
  149. private static void SafeStop<T>(ref T disposable) where T : class, IDisposable
  150. {
  151. if (disposable == null) return;
  152. try { disposable.Dispose(); } catch { /* ignore */ }
  153. disposable = null;
  154. }
  155. private void TryConnectStdin()
  156. {
  157. if (_pythonController == null)
  158. {
  159. Debug.LogWarning("[SDK][Client] PythonProcessController is null, cannot use stdin mode.");
  160. return;
  161. }
  162. if (_pythonController.IsRunning)
  163. {
  164. _stdinWriter = _pythonController.StdinWriter;
  165. if (_stdinWriter != null)
  166. {
  167. Debug.Log("[SDK][Client] Connected to Python stdin.");
  168. }
  169. else
  170. {
  171. Debug.LogWarning("[SDK][Client] Python stdin writer is null.");
  172. }
  173. }
  174. else
  175. {
  176. Debug.LogWarning("[SDK][Client] Python process not running, stdin mode will be retried later.");
  177. }
  178. }
  179. /// <summary>
  180. /// 设置图像传输配置(仅影响 Unity->Python 图像流,不影响硬件 0x40 配置)。
  181. /// </summary>
  182. public void SetTransmissionConfig(ImageTransmissionConfig config)
  183. {
  184. _transmissionConfig = config;
  185. _configEnabled = config != null && config.enableImageTransmission;
  186. }
  187. /// <summary>
  188. /// 下发硬件图像参数(0x40 帧),通常在 UI 点击“应用配置”时调用。
  189. /// </summary>
  190. public void ApplyHardwareConfig(ImageTransmissionConfig config)
  191. {
  192. if (_hwControlClient == null || _hwControlEndpoint == null || config == null)
  193. {
  194. Debug.LogWarning("[SDK][Client] Hardware control not ready or config null, cannot send 0x40 frame.");
  195. return;
  196. }
  197. try
  198. {
  199. byte[] frame = CoreHardwareControlProtocol.BuildParameterSettingFrame(config);
  200. if (frame != null && frame.Length > 0)
  201. {
  202. _hwControlClient.Send(frame, frame.Length, _hwControlEndpoint);
  203. Debug.Log($"[SDK][Client] Sent 0x40 frame -> {_hwControlEndpoint.Address}:{_hwControlEndpoint.Port}");
  204. }
  205. }
  206. catch (SocketException ex)
  207. {
  208. Debug.LogWarning($"[SDK][Client] Hardware control UDP send error: {ex.SocketErrorCode} {ex.Message}");
  209. }
  210. catch (Exception ex)
  211. {
  212. Debug.LogWarning($"[SDK][Client] Hardware control send failed: {ex.Message}");
  213. }
  214. }
  215. /// <summary>
  216. /// 每帧在 Unity 的 Update 中调用,用于驱动 JPEG 队列消费并发送到 Python。
  217. /// </summary>
  218. public void Tick()
  219. {
  220. if (!IsRunning || _jpegReceiver == null) return;
  221. // 确保发送端可用
  222. if (_options.Mode == TransferMode.Stdin)
  223. {
  224. if (_stdinWriter == null)
  225. {
  226. if (_pythonController != null && _pythonController.IsRunning)
  227. {
  228. _stdinWriter = _pythonController.StdinWriter;
  229. }
  230. if (_stdinWriter == null) return;
  231. }
  232. }
  233. else
  234. {
  235. if (_pythonUdpSender == null || _pythonEndpoint == null) return;
  236. }
  237. bool shouldTransmit = _configEnabled;
  238. if (_transmissionConfig != null)
  239. {
  240. shouldTransmit = _transmissionConfig.enableImageTransmission;
  241. }
  242. if (!shouldTransmit)
  243. {
  244. while (_jpegReceiver.TryDequeueJpeg(out _)) { }
  245. return;
  246. }
  247. float nowMs = Time.time * 1000f;
  248. if (_transmissionConfig != null)
  249. {
  250. float intervalMs = _transmissionConfig.reportIntervalMs;
  251. if (intervalMs > 0 && (nowMs - _lastSendTimeMs) < intervalMs)
  252. {
  253. while (_jpegReceiver.TryDequeueJpeg(out _)) { }
  254. return;
  255. }
  256. }
  257. byte[] latest = null;
  258. while (_jpegReceiver.TryDequeueJpeg(out var jpeg))
  259. {
  260. latest = jpeg;
  261. }
  262. if (latest == null) return;
  263. lock (_jpegLock)
  264. {
  265. _latestJpeg = latest;
  266. }
  267. byte[] processed = ProcessImage(latest);
  268. try
  269. {
  270. if (_options.Mode == TransferMode.Stdin)
  271. {
  272. if (_stdinWriter != null)
  273. {
  274. _stdinWriter.BaseStream.Write(processed, 0, processed.Length);
  275. _stdinWriter.BaseStream.Flush();
  276. _lastSendTimeMs = nowMs;
  277. }
  278. }
  279. else
  280. {
  281. _pythonUdpSender.Send(processed, processed.Length, _pythonEndpoint);
  282. _lastSendTimeMs = nowMs;
  283. }
  284. }
  285. catch (SocketException ex)
  286. {
  287. Debug.LogWarning($"[SDK][Client] UDP send error: {ex.SocketErrorCode} {ex.Message}");
  288. }
  289. catch (IOException ex)
  290. {
  291. Debug.LogWarning($"[SDK][Client] Stdin write error: {ex.Message}");
  292. _stdinWriter = null;
  293. }
  294. }
  295. private byte[] ProcessImage(byte[] jpegBytes)
  296. {
  297. if (_transmissionConfig == null)
  298. return jpegBytes;
  299. // 目前保持与现有 Bridge 一致:不在 Unity 端做 resize / 质量压缩,直接转发。
  300. return jpegBytes;
  301. }
  302. public byte[] GetLatestJpegCopy()
  303. {
  304. lock (_jpegLock)
  305. {
  306. return _latestJpeg != null ? (byte[])_latestJpeg.Clone() : null;
  307. }
  308. }
  309. public bool TryGetLatestResult(out LightGlueResult result)
  310. {
  311. if (_resultReceiver != null)
  312. {
  313. return _resultReceiver.TryDequeueResult(out result);
  314. }
  315. result = default(LightGlueResult);
  316. return false;
  317. }
  318. public void Dispose()
  319. {
  320. Stop();
  321. }
  322. }
  323. }