Client.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. using Force.Crc32;
  2. using Ryujinx.Common;
  3. using Ryujinx.Common.Configuration.Hid;
  4. using Ryujinx.Common.Logging;
  5. using Ryujinx.Configuration;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Net;
  10. using System.Net.Sockets;
  11. using System.Numerics;
  12. using System.Threading.Tasks;
  13. namespace Ryujinx.Motion
  14. {
  15. public class Client : IDisposable
  16. {
  17. public const uint Magic = 0x43555344; // DSUC
  18. public const ushort Version = 1001;
  19. private bool _active;
  20. private readonly Dictionary<int, IPEndPoint> _hosts;
  21. private readonly Dictionary<int, Dictionary<int, MotionInput>> _motionData;
  22. private readonly Dictionary<int, UdpClient> _clients;
  23. private bool[] _clientErrorStatus = new bool[Enum.GetValues(typeof(PlayerIndex)).Length];
  24. private long[] _clientRetryTimer = new long[Enum.GetValues(typeof(PlayerIndex)).Length];
  25. public Client()
  26. {
  27. _hosts = new Dictionary<int, IPEndPoint>();
  28. _motionData = new Dictionary<int, Dictionary<int, MotionInput>>();
  29. _clients = new Dictionary<int, UdpClient>();
  30. CloseClients();
  31. }
  32. public void CloseClients()
  33. {
  34. _active = false;
  35. lock (_clients)
  36. {
  37. foreach (var client in _clients)
  38. {
  39. try
  40. {
  41. client.Value?.Dispose();
  42. }
  43. #pragma warning disable CS0168
  44. catch (SocketException ex)
  45. #pragma warning restore CS0168
  46. {
  47. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to dispose motion client. Error code {ex.ErrorCode}");
  48. }
  49. }
  50. _hosts.Clear();
  51. _clients.Clear();
  52. _motionData.Clear();
  53. }
  54. }
  55. public void RegisterClient(int player, string host, int port)
  56. {
  57. if (_clients.ContainsKey(player) || !CanConnect(player))
  58. {
  59. return;
  60. }
  61. lock (_clients)
  62. {
  63. if (_clients.ContainsKey(player) || !CanConnect(player))
  64. {
  65. return;
  66. }
  67. UdpClient client = null;
  68. try
  69. {
  70. IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(host), port);
  71. client = new UdpClient(host, port);
  72. _clients.Add(player, client);
  73. _hosts.Add(player, endPoint);
  74. _active = true;
  75. Task.Run(() =>
  76. {
  77. ReceiveLoop(player);
  78. });
  79. }
  80. catch (FormatException fex)
  81. {
  82. if (!_clientErrorStatus[player])
  83. {
  84. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error {fex.Message}");
  85. _clientErrorStatus[player] = true;
  86. }
  87. }
  88. catch (SocketException sex)
  89. {
  90. if (!_clientErrorStatus[player])
  91. {
  92. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error code {sex.ErrorCode}");
  93. _clientErrorStatus[player] = true;
  94. }
  95. RemoveClient(player);
  96. client?.Dispose();
  97. SetRetryTimer(player);
  98. }
  99. catch (Exception ex)
  100. {
  101. _clientErrorStatus[player] = true;
  102. RemoveClient(player);
  103. client?.Dispose();
  104. SetRetryTimer(player);
  105. }
  106. }
  107. }
  108. public bool TryGetData(int player, int slot, out MotionInput input)
  109. {
  110. lock (_motionData)
  111. {
  112. if (_motionData.ContainsKey(player))
  113. {
  114. if (_motionData[player].TryGetValue(slot, out input))
  115. {
  116. return true;
  117. }
  118. }
  119. }
  120. input = null;
  121. return false;
  122. }
  123. private void RemoveClient(int clientId)
  124. {
  125. _clients?.Remove(clientId);
  126. _hosts?.Remove(clientId);
  127. }
  128. private void Send(byte[] data, int clientId)
  129. {
  130. if (_clients.TryGetValue(clientId, out UdpClient _client))
  131. {
  132. if (_client != null && _client.Client != null && _client.Client.Connected)
  133. {
  134. try
  135. {
  136. _client?.Send(data, data.Length);
  137. }
  138. catch (SocketException ex)
  139. {
  140. if (!_clientErrorStatus[clientId])
  141. {
  142. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to send data request to motion source at {_client.Client.RemoteEndPoint}. Error code {ex.ErrorCode}");
  143. }
  144. _clientErrorStatus[clientId] = true;
  145. RemoveClient(clientId);
  146. _client?.Dispose();
  147. SetRetryTimer(clientId);
  148. }
  149. catch (ObjectDisposedException dex)
  150. {
  151. _clientErrorStatus[clientId] = true;
  152. RemoveClient(clientId);
  153. _client?.Dispose();
  154. SetRetryTimer(clientId);
  155. }
  156. }
  157. }
  158. }
  159. private byte[] Receive(int clientId, int timeout = 0)
  160. {
  161. if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint) && _clients.TryGetValue(clientId, out UdpClient _client))
  162. {
  163. if (_client != null && _client.Client != null && _client.Client.Connected)
  164. {
  165. _client.Client.ReceiveTimeout = timeout;
  166. var result = _client?.Receive(ref endPoint);
  167. if (result.Length > 0)
  168. {
  169. _clientErrorStatus[clientId] = false;
  170. }
  171. return result;
  172. }
  173. }
  174. throw new Exception($"Client {clientId} is not registered.");
  175. }
  176. private void SetRetryTimer(int clientId)
  177. {
  178. var elapsedMs = PerformanceCounter.ElapsedMilliseconds;
  179. _clientRetryTimer[clientId] = elapsedMs;
  180. }
  181. private void ResetRetryTimer(int clientId)
  182. {
  183. _clientRetryTimer[clientId] = 0;
  184. }
  185. private bool CanConnect(int clientId)
  186. {
  187. return _clientRetryTimer[clientId] == 0 ? true : PerformanceCounter.ElapsedMilliseconds - 5000 > _clientRetryTimer[clientId];
  188. }
  189. public void ReceiveLoop(int clientId)
  190. {
  191. if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint) && _clients.TryGetValue(clientId, out UdpClient _client))
  192. {
  193. if (_client != null && _client.Client != null && _client.Client.Connected)
  194. {
  195. try
  196. {
  197. while (_active)
  198. {
  199. byte[] data = Receive(clientId);
  200. if (data.Length == 0)
  201. {
  202. continue;
  203. }
  204. #pragma warning disable CS4014
  205. Task.Run(() => HandleResponse(data, clientId));
  206. #pragma warning restore CS4014
  207. }
  208. }
  209. catch (SocketException ex)
  210. {
  211. if (!_clientErrorStatus[clientId])
  212. {
  213. Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to receive data from motion source at {endPoint}. Error code {ex.ErrorCode}");
  214. }
  215. _clientErrorStatus[clientId] = true;
  216. RemoveClient(clientId);
  217. _client?.Dispose();
  218. SetRetryTimer(clientId);
  219. }
  220. catch (ObjectDisposedException)
  221. {
  222. _clientErrorStatus[clientId] = true;
  223. RemoveClient(clientId);
  224. _client?.Dispose();
  225. SetRetryTimer(clientId);
  226. }
  227. }
  228. }
  229. }
  230. #pragma warning disable CS1998
  231. public void HandleResponse(byte[] data, int clientId)
  232. #pragma warning restore CS1998
  233. {
  234. ResetRetryTimer(clientId);
  235. MessageType type = (MessageType)BitConverter.ToUInt32(data.AsSpan().Slice(16, 4));
  236. data = data.AsSpan().Slice(16).ToArray();
  237. using MemoryStream mem = new MemoryStream(data);
  238. using BinaryReader reader = new BinaryReader(mem);
  239. switch (type)
  240. {
  241. case MessageType.Protocol:
  242. break;
  243. case MessageType.Info:
  244. ControllerInfoResponse contollerInfo = reader.ReadStruct<ControllerInfoResponse>();
  245. break;
  246. case MessageType.Data:
  247. ControllerDataResponse inputData = reader.ReadStruct<ControllerDataResponse>();
  248. Vector3 accelerometer = new Vector3()
  249. {
  250. X = -inputData.AccelerometerX,
  251. Y = inputData.AccelerometerZ,
  252. Z = -inputData.AccelerometerY
  253. };
  254. Vector3 gyroscrope = new Vector3()
  255. {
  256. X = inputData.GyroscopePitch,
  257. Y = inputData.GyroscopeRoll,
  258. Z = -inputData.GyroscopeYaw
  259. };
  260. ulong timestamp = inputData.MotionTimestamp;
  261. InputConfig config = ConfigurationState.Instance.Hid.InputConfig.Value.Find(x => x.PlayerIndex == (PlayerIndex)clientId);
  262. lock (_motionData)
  263. {
  264. int slot = inputData.Shared.Slot;
  265. if (_motionData.ContainsKey(clientId))
  266. {
  267. if (_motionData[clientId].ContainsKey(slot))
  268. {
  269. var previousData = _motionData[clientId][slot];
  270. previousData.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
  271. }
  272. else
  273. {
  274. MotionInput input = new MotionInput();
  275. input.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
  276. _motionData[clientId].Add(slot, input);
  277. }
  278. }
  279. else
  280. {
  281. MotionInput input = new MotionInput();
  282. input.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
  283. _motionData.Add(clientId, new Dictionary<int, MotionInput>() { { slot, input } });
  284. }
  285. }
  286. break;
  287. }
  288. }
  289. public void RequestInfo(int clientId, int slot)
  290. {
  291. if (!_active)
  292. {
  293. return;
  294. }
  295. Header header = GenerateHeader(clientId);
  296. using (MemoryStream mem = new MemoryStream())
  297. {
  298. using (BinaryWriter writer = new BinaryWriter(mem))
  299. {
  300. writer.WriteStruct(header);
  301. ControllerInfoRequest request = new ControllerInfoRequest()
  302. {
  303. Type = MessageType.Info,
  304. PortsCount = 4
  305. };
  306. request.PortIndices[0] = (byte)slot;
  307. writer.WriteStruct(request);
  308. header.Length = (ushort)(mem.Length - 16);
  309. writer.Seek(6, SeekOrigin.Begin);
  310. writer.Write(header.Length);
  311. header.Crc32 = Crc32Algorithm.Compute(mem.ToArray());
  312. writer.Seek(8, SeekOrigin.Begin);
  313. writer.Write(header.Crc32);
  314. byte[] data = mem.ToArray();
  315. Send(data, clientId);
  316. }
  317. }
  318. }
  319. public unsafe void RequestData(int clientId, int slot)
  320. {
  321. if (!_active)
  322. {
  323. return;
  324. }
  325. Header header = GenerateHeader(clientId);
  326. using (MemoryStream mem = new MemoryStream())
  327. {
  328. using (BinaryWriter writer = new BinaryWriter(mem))
  329. {
  330. writer.WriteStruct(header);
  331. ControllerDataRequest request = new ControllerDataRequest()
  332. {
  333. Type = MessageType.Data,
  334. Slot = (byte)slot,
  335. SubscriberType = SubscriberType.Slot
  336. };
  337. writer.WriteStruct(request);
  338. header.Length = (ushort)(mem.Length - 16);
  339. writer.Seek(6, SeekOrigin.Begin);
  340. writer.Write(header.Length);
  341. header.Crc32 = Crc32Algorithm.Compute(mem.ToArray());
  342. writer.Seek(8, SeekOrigin.Begin);
  343. writer.Write(header.Crc32);
  344. byte[] data = mem.ToArray();
  345. Send(data, clientId);
  346. }
  347. }
  348. }
  349. private Header GenerateHeader(int clientId)
  350. {
  351. Header header = new Header()
  352. {
  353. ID = (uint)clientId,
  354. MagicString = Magic,
  355. Version = Version,
  356. Length = 0,
  357. Crc32 = 0
  358. };
  359. return header;
  360. }
  361. public void Dispose()
  362. {
  363. _active = false;
  364. CloseClients();
  365. }
  366. }
  367. }