Motion Fixes (#1589)

* fix stalling when server is offline

* add retry timer to fail server connections, fix alt slot number

* fix alt slot key issue

* fix crash when saving controller config with empty fields

* code fixes

* add index check in motion hid update, made HandleResponse async

Co-authored-by: Emmanuel <nhv3@localhost.localdomain>
This commit is contained in:
emmauss 2020-10-28 19:52:07 +00:00 committed by GitHub
parent c9841dab38
commit 9f13f957af
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 218 additions and 139 deletions

View file

@ -25,6 +25,7 @@ namespace Ryujinx.Motion
private readonly Dictionary<int, UdpClient> _clients;
private bool[] _clientErrorStatus = new bool[Enum.GetValues(typeof(PlayerIndex)).Length];
private long[] _clientRetryTimer = new long[Enum.GetValues(typeof(PlayerIndex)).Length];
public Client()
{
@ -63,18 +64,25 @@ namespace Ryujinx.Motion
public void RegisterClient(int player, string host, int port)
{
if (_clients.ContainsKey(player))
if (_clients.ContainsKey(player) || !CanConnect(player))
{
return;
}
try
lock (_clients)
{
lock (_clients)
if (_clients.ContainsKey(player) || !CanConnect(player))
{
return;
}
UdpClient client = null;
try
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(host), port);
UdpClient client = new UdpClient(host, port);
client = new UdpClient(host, port);
_clients.Add(player, client);
_hosts.Add(player, endPoint);
@ -86,23 +94,39 @@ namespace Ryujinx.Motion
ReceiveLoop(player);
});
}
}
catch (FormatException fex)
{
if (!_clientErrorStatus[player])
catch (FormatException fex)
{
Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error {fex.Message}");
if (!_clientErrorStatus[player])
{
Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error {fex.Message}");
_clientErrorStatus[player] = true;
_clientErrorStatus[player] = true;
}
}
}
catch (SocketException ex)
{
if (!_clientErrorStatus[player])
catch (SocketException sex)
{
Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error code {ex.ErrorCode}");
if (!_clientErrorStatus[player])
{
Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to connect to motion source at {host}:{port}. Error code {sex.ErrorCode}");
_clientErrorStatus[player] = true;
}
RemoveClient(player);
client?.Dispose();
SetRetryTimer(player);
}
catch (Exception ex)
{
_clientErrorStatus[player] = true;
RemoveClient(player);
client?.Dispose();
SetRetryTimer(player);
}
}
}
@ -113,9 +137,10 @@ namespace Ryujinx.Motion
{
if (_motionData.ContainsKey(player))
{
input = _motionData[player][slot];
return true;
if (_motionData[player].TryGetValue(slot, out input))
{
return true;
}
}
}
@ -124,6 +149,13 @@ namespace Ryujinx.Motion
return false;
}
private void RemoveClient(int clientId)
{
_clients?.Remove(clientId);
_hosts?.Remove(clientId);
}
private void Send(byte[] data, int clientId)
{
if (_clients.TryGetValue(clientId, out UdpClient _client))
@ -143,146 +175,185 @@ namespace Ryujinx.Motion
_clientErrorStatus[clientId] = true;
_clients.Remove(clientId);
_hosts.Remove(clientId);
RemoveClient(clientId);
_client?.Dispose();
SetRetryTimer(clientId);
}
catch (ObjectDisposedException dex)
{
_clientErrorStatus[clientId] = true;
RemoveClient(clientId);
_client?.Dispose();
SetRetryTimer(clientId);
}
}
}
}
private byte[] Receive(int clientId)
private byte[] Receive(int clientId, int timeout = 0)
{
if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint))
if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint) && _clients.TryGetValue(clientId, out UdpClient _client))
{
if (_clients.TryGetValue(clientId, out UdpClient _client))
if (_client != null && _client.Client != null && _client.Client.Connected)
{
if (_client != null && _client.Client != null)
_client.Client.ReceiveTimeout = timeout;
var result = _client?.Receive(ref endPoint);
if (result.Length > 0)
{
if (_client.Client.Connected)
{
try
{
var result = _client?.Receive(ref endPoint);
if (result.Length > 0)
{
_clientErrorStatus[clientId] = false;
}
return result;
}
catch (SocketException ex)
{
if (!_clientErrorStatus[clientId])
{
Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to receive data from motion source at {endPoint}. Error code {ex.ErrorCode}");
}
_clientErrorStatus[clientId] = true;
_clients.Remove(clientId);
_hosts.Remove(clientId);
_client?.Dispose();
}
}
_clientErrorStatus[clientId] = false;
}
return result;
}
}
return new byte[0];
throw new Exception($"Client {clientId} is not registered.");
}
private void SetRetryTimer(int clientId)
{
var elapsedMs = PerformanceCounter.ElapsedMilliseconds;
_clientRetryTimer[clientId] = elapsedMs;
}
private void ResetRetryTimer(int clientId)
{
_clientRetryTimer[clientId] = 0;
}
private bool CanConnect(int clientId)
{
return _clientRetryTimer[clientId] == 0 ? true : PerformanceCounter.ElapsedMilliseconds - 5000 > _clientRetryTimer[clientId];
}
public void ReceiveLoop(int clientId)
{
while (_active)
if (_hosts.TryGetValue(clientId, out IPEndPoint endPoint) && _clients.TryGetValue(clientId, out UdpClient _client))
{
byte[] data = Receive(clientId);
if (data.Length == 0)
if (_client != null && _client.Client != null && _client.Client.Connected)
{
continue;
}
try
{
while (_active)
{
byte[] data = Receive(clientId);
if (data.Length == 0)
{
continue;
}
#pragma warning disable CS4014
HandleResponse(data, clientId);
Task.Run(() => HandleResponse(data, clientId));
#pragma warning restore CS4014
}
}
catch (SocketException ex)
{
if (!_clientErrorStatus[clientId])
{
Logger.Warning?.PrintMsg(LogClass.Hid, $"Unable to receive data from motion source at {endPoint}. Error code {ex.ErrorCode}");
}
_clientErrorStatus[clientId] = true;
RemoveClient(clientId);
_client?.Dispose();
SetRetryTimer(clientId);
}
catch (ObjectDisposedException)
{
_clientErrorStatus[clientId] = true;
RemoveClient(clientId);
_client?.Dispose();
SetRetryTimer(clientId);
}
}
}
}
#pragma warning disable CS1998
public async Task HandleResponse(byte[] data, int clientId)
public void HandleResponse(byte[] data, int clientId)
#pragma warning restore CS1998
{
ResetRetryTimer(clientId);
MessageType type = (MessageType)BitConverter.ToUInt32(data.AsSpan().Slice(16, 4));
data = data.AsSpan().Slice(16).ToArray();
using (MemoryStream mem = new MemoryStream(data))
using MemoryStream mem = new MemoryStream(data);
using BinaryReader reader = new BinaryReader(mem);
switch (type)
{
using (BinaryReader reader = new BinaryReader(mem))
{
switch (type)
case MessageType.Protocol:
break;
case MessageType.Info:
ControllerInfoResponse contollerInfo = reader.ReadStruct<ControllerInfoResponse>();
break;
case MessageType.Data:
ControllerDataResponse inputData = reader.ReadStruct<ControllerDataResponse>();
Vector3 accelerometer = new Vector3()
{
case MessageType.Protocol:
break;
case MessageType.Info:
ControllerInfoResponse contollerInfo = reader.ReadStruct<ControllerInfoResponse>();
break;
case MessageType.Data:
ControllerDataResponse inputData = reader.ReadStruct<ControllerDataResponse>();
X = -inputData.AccelerometerX,
Y = inputData.AccelerometerZ,
Z = -inputData.AccelerometerY
};
Vector3 accelerometer = new Vector3()
Vector3 gyroscrope = new Vector3()
{
X = inputData.GyroscopePitch,
Y = inputData.GyroscopeRoll,
Z = -inputData.GyroscopeYaw
};
ulong timestamp = inputData.MotionTimestamp;
InputConfig config = ConfigurationState.Instance.Hid.InputConfig.Value.Find(x => x.PlayerIndex == (PlayerIndex)clientId);
lock (_motionData)
{
int slot = inputData.Shared.Slot;
if (_motionData.ContainsKey(clientId))
{
if (_motionData[clientId].ContainsKey(slot))
{
X = -inputData.AccelerometerX,
Y = inputData.AccelerometerZ,
Z = -inputData.AccelerometerY
};
var previousData = _motionData[clientId][slot];
Vector3 gyroscrope = new Vector3()
{
X = inputData.GyroscopePitch,
Y = inputData.GyroscopeRoll,
Z = -inputData.GyroscopeYaw
};
ulong timestamp = inputData.MotionTimestamp;
InputConfig config = ConfigurationState.Instance.Hid.InputConfig.Value.Find(x => x.PlayerIndex == (PlayerIndex)clientId);
lock (_motionData)
{
int slot = inputData.Shared.Slot;
if (_motionData.ContainsKey(clientId))
{
if (_motionData[clientId].ContainsKey(slot))
{
var previousData = _motionData[clientId][slot];
previousData.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
}
else
{
MotionInput input = new MotionInput();
input.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
_motionData[clientId].Add(slot, input);
}
}
else
{
MotionInput input = new MotionInput();
input.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
_motionData.Add(clientId, new Dictionary<int, MotionInput>() { { slot, input } });
}
previousData.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
}
break;
else
{
MotionInput input = new MotionInput();
input.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
_motionData[clientId].Add(slot, input);
}
}
else
{
MotionInput input = new MotionInput();
input.Update(accelerometer, gyroscrope, timestamp, config.Sensitivity, (float)config.GyroDeadzone);
_motionData.Add(clientId, new Dictionary<int, MotionInput>() { { slot, input } });
}
}
}
break;
}
}