summaryrefslogtreecommitdiff
path: root/src/input_common/udp/client.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/input_common/udp/client.cpp')
-rw-r--r--src/input_common/udp/client.cpp226
1 files changed, 177 insertions, 49 deletions
diff --git a/src/input_common/udp/client.cpp b/src/input_common/udp/client.cpp
index 3f4eaf448..7039d6fc3 100644
--- a/src/input_common/udp/client.cpp
+++ b/src/input_common/udp/client.cpp
@@ -2,14 +2,13 @@
2// Licensed under GPLv2 or any later version 2// Licensed under GPLv2 or any later version
3// Refer to the license.txt file included. 3// Refer to the license.txt file included.
4 4
5#include <algorithm>
6#include <array>
7#include <chrono> 5#include <chrono>
8#include <cstring> 6#include <cstring>
9#include <functional> 7#include <functional>
10#include <thread> 8#include <thread>
11#include <boost/asio.hpp> 9#include <boost/asio.hpp>
12#include "common/logging/log.h" 10#include "common/logging/log.h"
11#include "core/settings.h"
13#include "input_common/udp/client.h" 12#include "input_common/udp/client.h"
14#include "input_common/udp/protocol.h" 13#include "input_common/udp/protocol.h"
15 14
@@ -27,11 +26,11 @@ class Socket {
27public: 26public:
28 using clock = std::chrono::system_clock; 27 using clock = std::chrono::system_clock;
29 28
30 explicit Socket(const std::string& host, u16 port, u8 pad_index, u32 client_id, 29 explicit Socket(const std::string& host, u16 port, std::size_t pad_index_, u32 client_id_,
31 SocketCallback callback) 30 SocketCallback callback_)
32 : callback(std::move(callback)), timer(io_service), 31 : callback(std::move(callback_)), timer(io_service),
33 socket(io_service, udp::endpoint(udp::v4(), 0)), client_id(client_id), 32 socket(io_service, udp::endpoint(udp::v4(), 0)), client_id(client_id_),
34 pad_index(pad_index) { 33 pad_index(pad_index_) {
35 boost::system::error_code ec{}; 34 boost::system::error_code ec{};
36 auto ipv4 = boost::asio::ip::make_address_v4(host, ec); 35 auto ipv4 = boost::asio::ip::make_address_v4(host, ec);
37 if (ec.value() != boost::system::errc::success) { 36 if (ec.value() != boost::system::errc::success) {
@@ -94,13 +93,17 @@ private:
94 void HandleSend(const boost::system::error_code& error) { 93 void HandleSend(const boost::system::error_code& error) {
95 boost::system::error_code _ignored{}; 94 boost::system::error_code _ignored{};
96 // Send a request for getting port info for the pad 95 // Send a request for getting port info for the pad
97 Request::PortInfo port_info{1, {pad_index, 0, 0, 0}}; 96 const Request::PortInfo port_info{1, {static_cast<u8>(pad_index), 0, 0, 0}};
98 const auto port_message = Request::Create(port_info, client_id); 97 const auto port_message = Request::Create(port_info, client_id);
99 std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE); 98 std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE);
100 socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint, {}, _ignored); 99 socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint, {}, _ignored);
101 100
102 // Send a request for getting pad data for the pad 101 // Send a request for getting pad data for the pad
103 Request::PadData pad_data{Request::PadData::Flags::Id, pad_index, EMPTY_MAC_ADDRESS}; 102 const Request::PadData pad_data{
103 Request::PadData::Flags::Id,
104 static_cast<u8>(pad_index),
105 EMPTY_MAC_ADDRESS,
106 };
104 const auto pad_message = Request::Create(pad_data, client_id); 107 const auto pad_message = Request::Create(pad_data, client_id);
105 std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE); 108 std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE);
106 socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint, {}, _ignored); 109 socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint, {}, _ignored);
@@ -113,7 +116,7 @@ private:
113 udp::socket socket; 116 udp::socket socket;
114 117
115 u32 client_id{}; 118 u32 client_id{};
116 u8 pad_index{}; 119 std::size_t pad_index{};
117 120
118 static constexpr std::size_t PORT_INFO_SIZE = sizeof(Message<Request::PortInfo>); 121 static constexpr std::size_t PORT_INFO_SIZE = sizeof(Message<Request::PortInfo>);
119 static constexpr std::size_t PAD_DATA_SIZE = sizeof(Message<Request::PadData>); 122 static constexpr std::size_t PAD_DATA_SIZE = sizeof(Message<Request::PadData>);
@@ -131,21 +134,59 @@ static void SocketLoop(Socket* socket) {
131 socket->Loop(); 134 socket->Loop();
132} 135}
133 136
134Client::Client(std::shared_ptr<DeviceStatus> status, const std::string& host, u16 port, 137Client::Client() {
135 u8 pad_index, u32 client_id) 138 LOG_INFO(Input, "Udp Initialization started");
136 : status(std::move(status)) { 139 for (std::size_t client = 0; client < clients.size(); client++) {
137 StartCommunication(host, port, pad_index, client_id); 140 const auto pad = client % 4;
141 StartCommunication(client, Settings::values.udp_input_address,
142 Settings::values.udp_input_port, pad, 24872);
143 // Set motion parameters
144 // SetGyroThreshold value should be dependent on GyroscopeZeroDriftMode
145 // Real HW values are unknown, 0.0001 is an approximate to Standard
146 clients[client].motion.SetGyroThreshold(0.0001f);
147 }
138} 148}
139 149
140Client::~Client() { 150Client::~Client() {
141 socket->Stop(); 151 Reset();
142 thread.join(); 152}
153
154std::vector<Common::ParamPackage> Client::GetInputDevices() const {
155 std::vector<Common::ParamPackage> devices;
156 for (std::size_t client = 0; client < clients.size(); client++) {
157 if (!DeviceConnected(client)) {
158 continue;
159 }
160 std::string name = fmt::format("UDP Controller {}", client);
161 devices.emplace_back(Common::ParamPackage{
162 {"class", "cemuhookudp"},
163 {"display", std::move(name)},
164 {"port", std::to_string(client)},
165 });
166 }
167 return devices;
143} 168}
144 169
145void Client::ReloadSocket(const std::string& host, u16 port, u8 pad_index, u32 client_id) { 170bool Client::DeviceConnected(std::size_t pad) const {
146 socket->Stop(); 171 // Use last timestamp to detect if the socket has stopped sending data
147 thread.join(); 172 const auto now = std::chrono::system_clock::now();
148 StartCommunication(host, port, pad_index, client_id); 173 const auto time_difference = static_cast<u64>(
174 std::chrono::duration_cast<std::chrono::milliseconds>(now - clients[pad].last_motion_update)
175 .count());
176 return time_difference < 1000 && clients[pad].active == 1;
177}
178
179void Client::ReloadUDPClient() {
180 for (std::size_t client = 0; client < clients.size(); client++) {
181 ReloadSocket(Settings::values.udp_input_address, Settings::values.udp_input_port, client);
182 }
183}
184void Client::ReloadSocket(const std::string& host, u16 port, std::size_t pad_index, u32 client_id) {
185 // client number must be determined from host / port and pad index
186 const std::size_t client = pad_index;
187 clients[client].socket->Stop();
188 clients[client].thread.join();
189 StartCommunication(client, host, port, pad_index, client_id);
149} 190}
150 191
151void Client::OnVersion(Response::Version data) { 192void Client::OnVersion(Response::Version data) {
@@ -157,23 +198,36 @@ void Client::OnPortInfo(Response::PortInfo data) {
157} 198}
158 199
159void Client::OnPadData(Response::PadData data) { 200void Client::OnPadData(Response::PadData data) {
201 // Client number must be determined from host / port and pad index
202 const std::size_t client = data.info.id;
160 LOG_TRACE(Input, "PadData packet received"); 203 LOG_TRACE(Input, "PadData packet received");
161 if (data.packet_counter <= packet_sequence) { 204 if (data.packet_counter == clients[client].packet_sequence) {
162 LOG_WARNING( 205 LOG_WARNING(
163 Input, 206 Input,
164 "PadData packet dropped because its stale info. Current count: {} Packet count: {}", 207 "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
165 packet_sequence, data.packet_counter); 208 clients[client].packet_sequence, data.packet_counter);
166 return; 209 return;
167 } 210 }
168 packet_sequence = data.packet_counter; 211 clients[client].active = data.info.is_pad_active;
169 // TODO: Check how the Switch handles motions and how the CemuhookUDP motion 212 clients[client].packet_sequence = data.packet_counter;
170 // directions correspond to the ones of the Switch 213 const auto now = std::chrono::system_clock::now();
171 Common::Vec3f accel = Common::MakeVec<float>(data.accel.x, data.accel.y, data.accel.z); 214 const auto time_difference =
172 Common::Vec3f gyro = Common::MakeVec<float>(data.gyro.pitch, data.gyro.yaw, data.gyro.roll); 215 static_cast<u64>(std::chrono::duration_cast<std::chrono::microseconds>(
173 { 216 now - clients[client].last_motion_update)
174 std::lock_guard guard(status->update_mutex); 217 .count());
218 clients[client].last_motion_update = now;
219 const Common::Vec3f raw_gyroscope = {data.gyro.pitch, data.gyro.roll, -data.gyro.yaw};
220 clients[client].motion.SetAcceleration({data.accel.x, -data.accel.z, data.accel.y});
221 // Gyroscope values are not it the correct scale from better joy.
222 // Dividing by 312 allows us to make one full turn = 1 turn
223 // This must be a configurable valued called sensitivity
224 clients[client].motion.SetGyroscope(raw_gyroscope / 312.0f);
225 clients[client].motion.UpdateRotation(time_difference);
226 clients[client].motion.UpdateOrientation(time_difference);
175 227
176 status->motion_status = {accel, gyro}; 228 {
229 std::lock_guard guard(clients[client].status.update_mutex);
230 clients[client].status.motion_status = clients[client].motion.GetMotion();
177 231
178 // TODO: add a setting for "click" touch. Click touch refers to a device that differentiates 232 // TODO: add a setting for "click" touch. Click touch refers to a device that differentiates
179 // between a simple "tap" and a hard press that causes the touch screen to click. 233 // between a simple "tap" and a hard press that causes the touch screen to click.
@@ -182,41 +236,115 @@ void Client::OnPadData(Response::PadData data) {
182 float x = 0; 236 float x = 0;
183 float y = 0; 237 float y = 0;
184 238
185 if (is_active && status->touch_calibration) { 239 if (is_active && clients[client].status.touch_calibration) {
186 const u16 min_x = status->touch_calibration->min_x; 240 const u16 min_x = clients[client].status.touch_calibration->min_x;
187 const u16 max_x = status->touch_calibration->max_x; 241 const u16 max_x = clients[client].status.touch_calibration->max_x;
188 const u16 min_y = status->touch_calibration->min_y; 242 const u16 min_y = clients[client].status.touch_calibration->min_y;
189 const u16 max_y = status->touch_calibration->max_y; 243 const u16 max_y = clients[client].status.touch_calibration->max_y;
190 244
191 x = (std::clamp(static_cast<u16>(data.touch_1.x), min_x, max_x) - min_x) / 245 x = static_cast<float>(std::clamp(static_cast<u16>(data.touch_1.x), min_x, max_x) -
246 min_x) /
192 static_cast<float>(max_x - min_x); 247 static_cast<float>(max_x - min_x);
193 y = (std::clamp(static_cast<u16>(data.touch_1.y), min_y, max_y) - min_y) / 248 y = static_cast<float>(std::clamp(static_cast<u16>(data.touch_1.y), min_y, max_y) -
249 min_y) /
194 static_cast<float>(max_y - min_y); 250 static_cast<float>(max_y - min_y);
195 } 251 }
196 252
197 status->touch_status = {x, y, is_active}; 253 clients[client].status.touch_status = {x, y, is_active};
254
255 if (configuring) {
256 const Common::Vec3f gyroscope = clients[client].motion.GetGyroscope();
257 const Common::Vec3f accelerometer = clients[client].motion.GetAcceleration();
258 UpdateYuzuSettings(client, accelerometer, gyroscope, is_active);
259 }
198 } 260 }
199} 261}
200 262
201void Client::StartCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id) { 263void Client::StartCommunication(std::size_t client, const std::string& host, u16 port,
264 std::size_t pad_index, u32 client_id) {
202 SocketCallback callback{[this](Response::Version version) { OnVersion(version); }, 265 SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
203 [this](Response::PortInfo info) { OnPortInfo(info); }, 266 [this](Response::PortInfo info) { OnPortInfo(info); },
204 [this](Response::PadData data) { OnPadData(data); }}; 267 [this](Response::PadData data) { OnPadData(data); }};
205 LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port); 268 LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port);
206 socket = std::make_unique<Socket>(host, port, pad_index, client_id, callback); 269 clients[client].socket = std::make_unique<Socket>(host, port, pad_index, client_id, callback);
207 thread = std::thread{SocketLoop, this->socket.get()}; 270 clients[client].thread = std::thread{SocketLoop, clients[client].socket.get()};
271}
272
273void Client::Reset() {
274 for (auto& client : clients) {
275 client.socket->Stop();
276 client.thread.join();
277 }
278}
279
280void Client::UpdateYuzuSettings(std::size_t client, const Common::Vec3<float>& acc,
281 const Common::Vec3<float>& gyro, bool touch) {
282 if (gyro.Length() > 0.2f) {
283 LOG_DEBUG(Input, "UDP Controller {}: gyro=({}, {}, {}), accel=({}, {}, {}), touch={}",
284 client, gyro[0], gyro[1], gyro[2], acc[0], acc[1], acc[2], touch);
285 }
286 UDPPadStatus pad;
287 if (touch) {
288 pad.touch = PadTouch::Click;
289 pad_queue[client].Push(pad);
290 }
291 for (size_t i = 0; i < 3; ++i) {
292 if (gyro[i] > 5.0f || gyro[i] < -5.0f) {
293 pad.motion = static_cast<PadMotion>(i);
294 pad.motion_value = gyro[i];
295 pad_queue[client].Push(pad);
296 }
297 if (acc[i] > 1.75f || acc[i] < -1.75f) {
298 pad.motion = static_cast<PadMotion>(i + 3);
299 pad.motion_value = acc[i];
300 pad_queue[client].Push(pad);
301 }
302 }
303}
304
305void Client::BeginConfiguration() {
306 for (auto& pq : pad_queue) {
307 pq.Clear();
308 }
309 configuring = true;
310}
311
312void Client::EndConfiguration() {
313 for (auto& pq : pad_queue) {
314 pq.Clear();
315 }
316 configuring = false;
208} 317}
209 318
210void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id, 319DeviceStatus& Client::GetPadState(std::size_t pad) {
211 std::function<void()> success_callback, 320 return clients[pad].status;
212 std::function<void()> failure_callback) { 321}
322
323const DeviceStatus& Client::GetPadState(std::size_t pad) const {
324 return clients[pad].status;
325}
326
327std::array<Common::SPSCQueue<UDPPadStatus>, 4>& Client::GetPadQueue() {
328 return pad_queue;
329}
330
331const std::array<Common::SPSCQueue<UDPPadStatus>, 4>& Client::GetPadQueue() const {
332 return pad_queue;
333}
334
335void TestCommunication(const std::string& host, u16 port, std::size_t pad_index, u32 client_id,
336 const std::function<void()>& success_callback,
337 const std::function<void()>& failure_callback) {
213 std::thread([=] { 338 std::thread([=] {
214 Common::Event success_event; 339 Common::Event success_event;
215 SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {}, 340 SocketCallback callback{
216 [&](Response::PadData data) { success_event.Set(); }}; 341 .version = [](Response::Version) {},
342 .port_info = [](Response::PortInfo) {},
343 .pad_data = [&](Response::PadData) { success_event.Set(); },
344 };
217 Socket socket{host, port, pad_index, client_id, std::move(callback)}; 345 Socket socket{host, port, pad_index, client_id, std::move(callback)};
218 std::thread worker_thread{SocketLoop, &socket}; 346 std::thread worker_thread{SocketLoop, &socket};
219 bool result = success_event.WaitFor(std::chrono::seconds(8)); 347 const bool result = success_event.WaitFor(std::chrono::seconds(8));
220 socket.Stop(); 348 socket.Stop();
221 worker_thread.join(); 349 worker_thread.join();
222 if (result) { 350 if (result) {
@@ -228,7 +356,7 @@ void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 clie
228} 356}
229 357
230CalibrationConfigurationJob::CalibrationConfigurationJob( 358CalibrationConfigurationJob::CalibrationConfigurationJob(
231 const std::string& host, u16 port, u8 pad_index, u32 client_id, 359 const std::string& host, u16 port, std::size_t pad_index, u32 client_id,
232 std::function<void(Status)> status_callback, 360 std::function<void(Status)> status_callback,
233 std::function<void(u16, u16, u16, u16)> data_callback) { 361 std::function<void(u16, u16, u16, u16)> data_callback) {
234 362
@@ -248,7 +376,7 @@ CalibrationConfigurationJob::CalibrationConfigurationJob(
248 current_status = Status::Ready; 376 current_status = Status::Ready;
249 status_callback(current_status); 377 status_callback(current_status);
250 } 378 }
251 if (!data.touch_1.is_active) { 379 if (data.touch_1.is_active == 0) {
252 return; 380 return;
253 } 381 }
254 LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x, 382 LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x,