client.cpp 12 KB

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