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.cpp245
1 files changed, 185 insertions, 60 deletions
diff --git a/src/input_common/udp/client.cpp b/src/input_common/udp/client.cpp
index da5227058..c0bb90048 100644
--- a/src/input_common/udp/client.cpp
+++ b/src/input_common/udp/client.cpp
@@ -2,15 +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 <boost/bind.hpp>
13#include "common/logging/log.h" 10#include "common/logging/log.h"
11#include "core/settings.h"
14#include "input_common/udp/client.h" 12#include "input_common/udp/client.h"
15#include "input_common/udp/protocol.h" 13#include "input_common/udp/protocol.h"
16 14
@@ -28,11 +26,11 @@ class Socket {
28public: 26public:
29 using clock = std::chrono::system_clock; 27 using clock = std::chrono::system_clock;
30 28
31 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_,
32 SocketCallback callback) 30 SocketCallback callback_)
33 : callback(std::move(callback)), timer(io_service), 31 : callback(std::move(callback_)), timer(io_service),
34 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_),
35 pad_index(pad_index) { 33 pad_index(pad_index_) {
36 boost::system::error_code ec{}; 34 boost::system::error_code ec{};
37 auto ipv4 = boost::asio::ip::make_address_v4(host, ec); 35 auto ipv4 = boost::asio::ip::make_address_v4(host, ec);
38 if (ec.value() != boost::system::errc::success) { 36 if (ec.value() != boost::system::errc::success) {
@@ -65,7 +63,7 @@ public:
65 } 63 }
66 64
67private: 65private:
68 void HandleReceive(const boost::system::error_code& error, std::size_t bytes_transferred) { 66 void HandleReceive(const boost::system::error_code&, std::size_t bytes_transferred) {
69 if (auto type = Response::Validate(receive_buffer.data(), bytes_transferred)) { 67 if (auto type = Response::Validate(receive_buffer.data(), bytes_transferred)) {
70 switch (*type) { 68 switch (*type) {
71 case Type::Version: { 69 case Type::Version: {
@@ -92,16 +90,20 @@ private:
92 StartReceive(); 90 StartReceive();
93 } 91 }
94 92
95 void HandleSend(const boost::system::error_code& error) { 93 void HandleSend(const boost::system::error_code&) {
96 boost::system::error_code _ignored{}; 94 boost::system::error_code _ignored{};
97 // Send a request for getting port info for the pad 95 // Send a request for getting port info for the pad
98 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}};
99 const auto port_message = Request::Create(port_info, client_id); 97 const auto port_message = Request::Create(port_info, client_id);
100 std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE); 98 std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE);
101 socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint, {}, _ignored); 99 socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint, {}, _ignored);
102 100
103 // Send a request for getting pad data for the pad 101 // Send a request for getting pad data for the pad
104 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 };
105 const auto pad_message = Request::Create(pad_data, client_id); 107 const auto pad_message = Request::Create(pad_data, client_id);
106 std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE); 108 std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE);
107 socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint, {}, _ignored); 109 socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint, {}, _ignored);
@@ -114,7 +116,7 @@ private:
114 udp::socket socket; 116 udp::socket socket;
115 117
116 u32 client_id{}; 118 u32 client_id{};
117 u8 pad_index{}; 119 std::size_t pad_index{};
118 120
119 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>);
120 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>);
@@ -132,49 +134,100 @@ static void SocketLoop(Socket* socket) {
132 socket->Loop(); 134 socket->Loop();
133} 135}
134 136
135Client::Client(std::shared_ptr<DeviceStatus> status, const std::string& host, u16 port, 137Client::Client() {
136 u8 pad_index, u32 client_id) 138 LOG_INFO(Input, "Udp Initialization started");
137 : status(std::move(status)) { 139 for (std::size_t client = 0; client < clients.size(); client++) {
138 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 }
139} 148}
140 149
141Client::~Client() { 150Client::~Client() {
142 socket->Stop(); 151 Reset();
143 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;
144} 168}
145 169
146void Client::ReloadSocket(const std::string& host, u16 port, u8 pad_index, u32 client_id) { 170bool Client::DeviceConnected(std::size_t pad) const {
147 socket->Stop(); 171 // Use last timestamp to detect if the socket has stopped sending data
148 thread.join(); 172 const auto now = std::chrono::system_clock::now();
149 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;
150} 177}
151 178
152void Client::OnVersion(Response::Version data) { 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);
190}
191
192void Client::OnVersion([[maybe_unused]] Response::Version data) {
153 LOG_TRACE(Input, "Version packet received: {}", data.version); 193 LOG_TRACE(Input, "Version packet received: {}", data.version);
154} 194}
155 195
156void Client::OnPortInfo(Response::PortInfo data) { 196void Client::OnPortInfo([[maybe_unused]] Response::PortInfo data) {
157 LOG_TRACE(Input, "PortInfo packet received: {}", data.model); 197 LOG_TRACE(Input, "PortInfo packet received: {}", data.model);
158} 198}
159 199
160void 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;
161 LOG_TRACE(Input, "PadData packet received"); 203 LOG_TRACE(Input, "PadData packet received");
162 if (data.packet_counter <= packet_sequence) { 204 if (data.packet_counter == clients[client].packet_sequence) {
163 LOG_WARNING( 205 LOG_WARNING(
164 Input, 206 Input,
165 "PadData packet dropped because its stale info. Current count: {} Packet count: {}", 207 "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
166 packet_sequence, data.packet_counter); 208 clients[client].packet_sequence, data.packet_counter);
167 return; 209 return;
168 } 210 }
169 packet_sequence = data.packet_counter; 211 clients[client].active = data.info.is_pad_active;
170 // TODO: Check how the Switch handles motions and how the CemuhookUDP motion 212 clients[client].packet_sequence = data.packet_counter;
171 // directions correspond to the ones of the Switch 213 const auto now = std::chrono::system_clock::now();
172 Common::Vec3f accel = Common::MakeVec<float>(data.accel.x, data.accel.y, data.accel.z); 214 const auto time_difference =
173 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>(
174 { 216 now - clients[client].last_motion_update)
175 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);
176 227
177 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();
178 231
179 // 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
180 // 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.
@@ -183,41 +236,115 @@ void Client::OnPadData(Response::PadData data) {
183 float x = 0; 236 float x = 0;
184 float y = 0; 237 float y = 0;
185 238
186 if (is_active && status->touch_calibration) { 239 if (is_active && clients[client].status.touch_calibration) {
187 const u16 min_x = status->touch_calibration->min_x; 240 const u16 min_x = clients[client].status.touch_calibration->min_x;
188 const u16 max_x = status->touch_calibration->max_x; 241 const u16 max_x = clients[client].status.touch_calibration->max_x;
189 const u16 min_y = status->touch_calibration->min_y; 242 const u16 min_y = clients[client].status.touch_calibration->min_y;
190 const u16 max_y = status->touch_calibration->max_y; 243 const u16 max_y = clients[client].status.touch_calibration->max_y;
191 244
192 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) /
193 static_cast<float>(max_x - min_x); 247 static_cast<float>(max_x - min_x);
194 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) /
195 static_cast<float>(max_y - min_y); 250 static_cast<float>(max_y - min_y);
196 } 251 }
197 252
198 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 }
199 } 260 }
200} 261}
201 262
202void 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) {
203 SocketCallback callback{[this](Response::Version version) { OnVersion(version); }, 265 SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
204 [this](Response::PortInfo info) { OnPortInfo(info); }, 266 [this](Response::PortInfo info) { OnPortInfo(info); },
205 [this](Response::PadData data) { OnPadData(data); }}; 267 [this](Response::PadData data) { OnPadData(data); }};
206 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);
207 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);
208 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;
209} 317}
210 318
211void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id, 319DeviceStatus& Client::GetPadState(std::size_t pad) {
212 std::function<void()> success_callback, 320 return clients[pad].status;
213 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) {
214 std::thread([=] { 338 std::thread([=] {
215 Common::Event success_event; 339 Common::Event success_event;
216 SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {}, 340 SocketCallback callback{
217 [&](Response::PadData data) { success_event.Set(); }}; 341 .version = [](Response::Version) {},
342 .port_info = [](Response::PortInfo) {},
343 .pad_data = [&](Response::PadData) { success_event.Set(); },
344 };
218 Socket socket{host, port, pad_index, client_id, std::move(callback)}; 345 Socket socket{host, port, pad_index, client_id, std::move(callback)};
219 std::thread worker_thread{SocketLoop, &socket}; 346 std::thread worker_thread{SocketLoop, &socket};
220 bool result = success_event.WaitFor(std::chrono::seconds(8)); 347 const bool result = success_event.WaitFor(std::chrono::seconds(5));
221 socket.Stop(); 348 socket.Stop();
222 worker_thread.join(); 349 worker_thread.join();
223 if (result) { 350 if (result) {
@@ -225,16 +352,15 @@ void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 clie
225 } else { 352 } else {
226 failure_callback(); 353 failure_callback();
227 } 354 }
228 }) 355 }).detach();
229 .detach();
230} 356}
231 357
232CalibrationConfigurationJob::CalibrationConfigurationJob( 358CalibrationConfigurationJob::CalibrationConfigurationJob(
233 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,
234 std::function<void(Status)> status_callback, 360 std::function<void(Status)> status_callback,
235 std::function<void(u16, u16, u16, u16)> data_callback) { 361 std::function<void(u16, u16, u16, u16)> data_callback) {
236 362
237 std::thread([=] { 363 std::thread([=, this] {
238 constexpr u16 CALIBRATION_THRESHOLD = 100; 364 constexpr u16 CALIBRATION_THRESHOLD = 100;
239 365
240 u16 min_x{UINT16_MAX}; 366 u16 min_x{UINT16_MAX};
@@ -243,14 +369,14 @@ CalibrationConfigurationJob::CalibrationConfigurationJob(
243 u16 max_y{}; 369 u16 max_y{};
244 370
245 Status current_status{Status::Initialized}; 371 Status current_status{Status::Initialized};
246 SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {}, 372 SocketCallback callback{[](Response::Version) {}, [](Response::PortInfo) {},
247 [&](Response::PadData data) { 373 [&](Response::PadData data) {
248 if (current_status == Status::Initialized) { 374 if (current_status == Status::Initialized) {
249 // Receiving data means the communication is ready now 375 // Receiving data means the communication is ready now
250 current_status = Status::Ready; 376 current_status = Status::Ready;
251 status_callback(current_status); 377 status_callback(current_status);
252 } 378 }
253 if (!data.touch_1.is_active) { 379 if (data.touch_1.is_active == 0) {
254 return; 380 return;
255 } 381 }
256 LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x, 382 LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x,
@@ -280,8 +406,7 @@ CalibrationConfigurationJob::CalibrationConfigurationJob(
280 complete_event.Wait(); 406 complete_event.Wait();
281 socket.Stop(); 407 socket.Stop();
282 worker_thread.join(); 408 worker_thread.join();
283 }) 409 }).detach();
284 .detach();
285} 410}
286 411
287CalibrationConfigurationJob::~CalibrationConfigurationJob() { 412CalibrationConfigurationJob::~CalibrationConfigurationJob() {