client.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <array>
  6. #include <chrono>
  7. #include <cstring>
  8. #include <functional>
  9. #include <thread>
  10. #include <boost/asio.hpp>
  11. #include <boost/bind.hpp>
  12. #include "common/logging/log.h"
  13. #include "input_common/udp/client.h"
  14. #include "input_common/udp/protocol.h"
  15. using boost::asio::ip::address_v4;
  16. using boost::asio::ip::udp;
  17. namespace InputCommon::CemuhookUDP {
  18. struct SocketCallback {
  19. std::function<void(Response::Version)> version;
  20. std::function<void(Response::PortInfo)> port_info;
  21. std::function<void(Response::PadData)> pad_data;
  22. };
  23. class Socket {
  24. public:
  25. using clock = std::chrono::system_clock;
  26. explicit Socket(const std::string& host, u16 port, u8 pad_index, u32 client_id,
  27. SocketCallback callback)
  28. : client_id(client_id), timer(io_service),
  29. send_endpoint(udp::endpoint(address_v4::from_string(host), port)),
  30. socket(io_service, udp::endpoint(udp::v4(), 0)), pad_index(pad_index),
  31. callback(std::move(callback)) {}
  32. void Stop() {
  33. io_service.stop();
  34. }
  35. void Loop() {
  36. io_service.run();
  37. }
  38. void StartSend(const clock::time_point& from) {
  39. timer.expires_at(from + std::chrono::seconds(3));
  40. timer.async_wait([this](const boost::system::error_code& error) { HandleSend(error); });
  41. }
  42. void StartReceive() {
  43. socket.async_receive_from(
  44. boost::asio::buffer(receive_buffer), receive_endpoint,
  45. [this](const boost::system::error_code& error, std::size_t bytes_transferred) {
  46. HandleReceive(error, bytes_transferred);
  47. });
  48. }
  49. private:
  50. void HandleReceive(const boost::system::error_code& error, std::size_t bytes_transferred) {
  51. if (auto type = Response::Validate(receive_buffer.data(), bytes_transferred)) {
  52. switch (*type) {
  53. case Type::Version: {
  54. Response::Version version;
  55. std::memcpy(&version, &receive_buffer[sizeof(Header)], sizeof(Response::Version));
  56. callback.version(std::move(version));
  57. break;
  58. }
  59. case Type::PortInfo: {
  60. Response::PortInfo port_info;
  61. std::memcpy(&port_info, &receive_buffer[sizeof(Header)],
  62. sizeof(Response::PortInfo));
  63. callback.port_info(std::move(port_info));
  64. break;
  65. }
  66. case Type::PadData: {
  67. Response::PadData pad_data;
  68. std::memcpy(&pad_data, &receive_buffer[sizeof(Header)], sizeof(Response::PadData));
  69. callback.pad_data(std::move(pad_data));
  70. break;
  71. }
  72. }
  73. }
  74. StartReceive();
  75. }
  76. void HandleSend(const boost::system::error_code& error) {
  77. // Send a request for getting port info for the pad
  78. Request::PortInfo port_info{1, {pad_index, 0, 0, 0}};
  79. auto port_message = Request::Create(port_info, client_id);
  80. std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE);
  81. std::size_t len = socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint);
  82. // Send a request for getting pad data for the pad
  83. Request::PadData pad_data{Request::PadData::Flags::Id, pad_index, EMPTY_MAC_ADDRESS};
  84. auto pad_message = Request::Create(pad_data, client_id);
  85. std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE);
  86. std::size_t len2 = socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint);
  87. StartSend(timer.expiry());
  88. }
  89. SocketCallback callback;
  90. boost::asio::io_service io_service;
  91. boost::asio::basic_waitable_timer<clock> timer;
  92. udp::socket socket;
  93. u32 client_id;
  94. u8 pad_index;
  95. static constexpr std::size_t PORT_INFO_SIZE = sizeof(Message<Request::PortInfo>);
  96. static constexpr std::size_t PAD_DATA_SIZE = sizeof(Message<Request::PadData>);
  97. std::array<u8, PORT_INFO_SIZE> send_buffer1;
  98. std::array<u8, PAD_DATA_SIZE> send_buffer2;
  99. udp::endpoint send_endpoint;
  100. std::array<u8, MAX_PACKET_SIZE> receive_buffer;
  101. udp::endpoint receive_endpoint;
  102. };
  103. static void SocketLoop(Socket* socket) {
  104. socket->StartReceive();
  105. socket->StartSend(Socket::clock::now());
  106. socket->Loop();
  107. }
  108. Client::Client(std::shared_ptr<DeviceStatus> status, const std::string& host, u16 port,
  109. u8 pad_index, u32 client_id)
  110. : status(status) {
  111. StartCommunication(host, port, pad_index, client_id);
  112. }
  113. Client::~Client() {
  114. socket->Stop();
  115. thread.join();
  116. }
  117. void Client::ReloadSocket(const std::string& host, u16 port, u8 pad_index, u32 client_id) {
  118. socket->Stop();
  119. thread.join();
  120. StartCommunication(host, port, pad_index, client_id);
  121. }
  122. void Client::OnVersion(Response::Version data) {
  123. LOG_TRACE(Input, "Version packet received: {}", data.version);
  124. }
  125. void Client::OnPortInfo(Response::PortInfo data) {
  126. LOG_TRACE(Input, "PortInfo packet received: {}", data.model);
  127. }
  128. void Client::OnPadData(Response::PadData data) {
  129. LOG_TRACE(Input, "PadData packet received");
  130. if (data.packet_counter <= packet_sequence) {
  131. LOG_WARNING(
  132. Input,
  133. "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
  134. packet_sequence, data.packet_counter);
  135. return;
  136. }
  137. packet_sequence = data.packet_counter;
  138. // TODO: Check how the Switch handles motions and how the CemuhookUDP motion
  139. // directions correspond to the ones of the Switch
  140. Common::Vec3f accel = Common::MakeVec<float>(data.accel.x, data.accel.y, data.accel.z);
  141. Common::Vec3f gyro = Common::MakeVec<float>(data.gyro.pitch, data.gyro.yaw, data.gyro.roll);
  142. {
  143. std::lock_guard guard(status->update_mutex);
  144. status->motion_status = {accel, gyro};
  145. // TODO: add a setting for "click" touch. Click touch refers to a device that differentiates
  146. // between a simple "tap" and a hard press that causes the touch screen to click.
  147. bool is_active = data.touch_1.is_active != 0;
  148. float x = 0;
  149. float y = 0;
  150. if (is_active && status->touch_calibration) {
  151. u16 min_x = status->touch_calibration->min_x;
  152. u16 max_x = status->touch_calibration->max_x;
  153. u16 min_y = status->touch_calibration->min_y;
  154. u16 max_y = status->touch_calibration->max_y;
  155. x = (std::clamp(static_cast<u16>(data.touch_1.x), min_x, max_x) - min_x) /
  156. static_cast<float>(max_x - min_x);
  157. y = (std::clamp(static_cast<u16>(data.touch_1.y), min_y, max_y) - min_y) /
  158. static_cast<float>(max_y - min_y);
  159. }
  160. status->touch_status = {x, y, is_active};
  161. }
  162. }
  163. void Client::StartCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id) {
  164. SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
  165. [this](Response::PortInfo info) { OnPortInfo(info); },
  166. [this](Response::PadData data) { OnPadData(data); }};
  167. LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port);
  168. socket = std::make_unique<Socket>(host, port, pad_index, client_id, callback);
  169. thread = std::thread{SocketLoop, this->socket.get()};
  170. }
  171. void TestCommunication(const std::string& host, u16 port, u8 pad_index, u32 client_id,
  172. std::function<void()> success_callback,
  173. std::function<void()> failure_callback) {
  174. std::thread([=] {
  175. Common::Event success_event;
  176. SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {},
  177. [&](Response::PadData data) { success_event.Set(); }};
  178. Socket socket{host, port, pad_index, client_id, callback};
  179. std::thread worker_thread{SocketLoop, &socket};
  180. bool result = success_event.WaitFor(std::chrono::seconds(8));
  181. socket.Stop();
  182. worker_thread.join();
  183. if (result)
  184. success_callback();
  185. else
  186. failure_callback();
  187. })
  188. .detach();
  189. }
  190. CalibrationConfigurationJob::CalibrationConfigurationJob(
  191. const std::string& host, u16 port, u8 pad_index, u32 client_id,
  192. std::function<void(Status)> status_callback,
  193. std::function<void(u16, u16, u16, u16)> data_callback) {
  194. std::thread([=] {
  195. constexpr u16 CALIBRATION_THRESHOLD = 100;
  196. u16 min_x{UINT16_MAX}, min_y{UINT16_MAX};
  197. u16 max_x, max_y;
  198. Status current_status{Status::Initialized};
  199. SocketCallback callback{[](Response::Version version) {}, [](Response::PortInfo info) {},
  200. [&](Response::PadData data) {
  201. if (current_status == Status::Initialized) {
  202. // Receiving data means the communication is ready now
  203. current_status = Status::Ready;
  204. status_callback(current_status);
  205. }
  206. if (!data.touch_1.is_active)
  207. return;
  208. LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x,
  209. data.touch_1.y);
  210. min_x = std::min(min_x, static_cast<u16>(data.touch_1.x));
  211. min_y = std::min(min_y, static_cast<u16>(data.touch_1.y));
  212. if (current_status == Status::Ready) {
  213. // First touch - min data (min_x/min_y)
  214. current_status = Status::Stage1Completed;
  215. status_callback(current_status);
  216. }
  217. if (data.touch_1.x - min_x > CALIBRATION_THRESHOLD &&
  218. data.touch_1.y - min_y > CALIBRATION_THRESHOLD) {
  219. // Set the current position as max value and finishes
  220. // configuration
  221. max_x = data.touch_1.x;
  222. max_y = data.touch_1.y;
  223. current_status = Status::Completed;
  224. data_callback(min_x, min_y, max_x, max_y);
  225. status_callback(current_status);
  226. complete_event.Set();
  227. }
  228. }};
  229. Socket socket{host, port, pad_index, client_id, callback};
  230. std::thread worker_thread{SocketLoop, &socket};
  231. complete_event.Wait();
  232. socket.Stop();
  233. worker_thread.join();
  234. })
  235. .detach();
  236. }
  237. CalibrationConfigurationJob::~CalibrationConfigurationJob() {
  238. Stop();
  239. }
  240. void CalibrationConfigurationJob::Stop() {
  241. complete_event.Set();
  242. }
  243. } // namespace InputCommon::CemuhookUDP