udp_client.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <random>
  5. #include <boost/asio.hpp>
  6. #include "common/logging/log.h"
  7. #include "common/param_package.h"
  8. #include "common/settings.h"
  9. #include "input_common/drivers/udp_client.h"
  10. #include "input_common/helpers/udp_protocol.h"
  11. using boost::asio::ip::udp;
  12. namespace InputCommon::CemuhookUDP {
  13. struct SocketCallback {
  14. std::function<void(Response::Version)> version;
  15. std::function<void(Response::PortInfo)> port_info;
  16. std::function<void(Response::PadData)> pad_data;
  17. };
  18. class Socket {
  19. public:
  20. using clock = std::chrono::system_clock;
  21. explicit Socket(const std::string& host, u16 port, SocketCallback callback_)
  22. : callback(std::move(callback_)), timer(io_service),
  23. socket(io_service, udp::endpoint(udp::v4(), 0)), client_id(GenerateRandomClientId()) {
  24. boost::system::error_code ec{};
  25. auto ipv4 = boost::asio::ip::make_address_v4(host, ec);
  26. if (ec.value() != boost::system::errc::success) {
  27. LOG_ERROR(Input, "Invalid IPv4 address \"{}\" provided to socket", host);
  28. ipv4 = boost::asio::ip::address_v4{};
  29. }
  30. send_endpoint = {udp::endpoint(ipv4, port)};
  31. }
  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. u32 GenerateRandomClientId() const {
  51. std::random_device device;
  52. return device();
  53. }
  54. void HandleReceive(const boost::system::error_code&, std::size_t bytes_transferred) {
  55. if (auto type = Response::Validate(receive_buffer.data(), bytes_transferred)) {
  56. switch (*type) {
  57. case Type::Version: {
  58. Response::Version version;
  59. std::memcpy(&version, &receive_buffer[sizeof(Header)], sizeof(Response::Version));
  60. callback.version(std::move(version));
  61. break;
  62. }
  63. case Type::PortInfo: {
  64. Response::PortInfo port_info;
  65. std::memcpy(&port_info, &receive_buffer[sizeof(Header)],
  66. sizeof(Response::PortInfo));
  67. callback.port_info(std::move(port_info));
  68. break;
  69. }
  70. case Type::PadData: {
  71. Response::PadData pad_data;
  72. std::memcpy(&pad_data, &receive_buffer[sizeof(Header)], sizeof(Response::PadData));
  73. callback.pad_data(std::move(pad_data));
  74. break;
  75. }
  76. }
  77. }
  78. StartReceive();
  79. }
  80. void HandleSend(const boost::system::error_code&) {
  81. boost::system::error_code _ignored{};
  82. // Send a request for getting port info for the pad
  83. const Request::PortInfo port_info{4, {0, 1, 2, 3}};
  84. const auto port_message = Request::Create(port_info, client_id);
  85. std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE);
  86. socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint, {}, _ignored);
  87. // Send a request for getting pad data for the pad
  88. const Request::PadData pad_data{
  89. Request::PadData::Flags::AllPorts,
  90. 0,
  91. EMPTY_MAC_ADDRESS,
  92. };
  93. const auto pad_message = Request::Create(pad_data, client_id);
  94. std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE);
  95. socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint, {}, _ignored);
  96. StartSend(timer.expiry());
  97. }
  98. SocketCallback callback;
  99. boost::asio::io_service io_service;
  100. boost::asio::basic_waitable_timer<clock> timer;
  101. udp::socket socket;
  102. const u32 client_id;
  103. static constexpr std::size_t PORT_INFO_SIZE = sizeof(Message<Request::PortInfo>);
  104. static constexpr std::size_t PAD_DATA_SIZE = sizeof(Message<Request::PadData>);
  105. std::array<u8, PORT_INFO_SIZE> send_buffer1;
  106. std::array<u8, PAD_DATA_SIZE> send_buffer2;
  107. udp::endpoint send_endpoint;
  108. std::array<u8, MAX_PACKET_SIZE> receive_buffer;
  109. udp::endpoint receive_endpoint;
  110. };
  111. static void SocketLoop(Socket* socket) {
  112. socket->StartReceive();
  113. socket->StartSend(Socket::clock::now());
  114. socket->Loop();
  115. }
  116. UDPClient::UDPClient(const std::string& input_engine_) : InputEngine(input_engine_) {
  117. LOG_INFO(Input, "Udp Initialization started");
  118. ReloadSockets();
  119. }
  120. UDPClient::~UDPClient() {
  121. Reset();
  122. }
  123. UDPClient::ClientConnection::ClientConnection() = default;
  124. UDPClient::ClientConnection::~ClientConnection() = default;
  125. void UDPClient::ReloadSockets() {
  126. Reset();
  127. std::stringstream servers_ss(Settings::values.udp_input_servers.GetValue());
  128. std::string server_token;
  129. std::size_t client = 0;
  130. while (std::getline(servers_ss, server_token, ',')) {
  131. if (client == MAX_UDP_CLIENTS) {
  132. break;
  133. }
  134. std::stringstream server_ss(server_token);
  135. std::string token;
  136. std::getline(server_ss, token, ':');
  137. std::string udp_input_address = token;
  138. std::getline(server_ss, token, ':');
  139. char* temp;
  140. const u16 udp_input_port = static_cast<u16>(std::strtol(token.c_str(), &temp, 0));
  141. if (*temp != '\0') {
  142. LOG_ERROR(Input, "Port number is not valid {}", token);
  143. continue;
  144. }
  145. const std::size_t client_number = GetClientNumber(udp_input_address, udp_input_port);
  146. if (client_number != MAX_UDP_CLIENTS) {
  147. LOG_ERROR(Input, "Duplicated UDP servers found");
  148. continue;
  149. }
  150. StartCommunication(client++, udp_input_address, udp_input_port);
  151. }
  152. }
  153. std::size_t UDPClient::GetClientNumber(std::string_view host, u16 port) const {
  154. for (std::size_t client = 0; client < clients.size(); client++) {
  155. if (clients[client].active == -1) {
  156. continue;
  157. }
  158. if (clients[client].host == host && clients[client].port == port) {
  159. return client;
  160. }
  161. }
  162. return MAX_UDP_CLIENTS;
  163. }
  164. void UDPClient::OnVersion([[maybe_unused]] Response::Version data) {
  165. LOG_TRACE(Input, "Version packet received: {}", data.version);
  166. }
  167. void UDPClient::OnPortInfo([[maybe_unused]] Response::PortInfo data) {
  168. LOG_TRACE(Input, "PortInfo packet received: {}", data.model);
  169. }
  170. void UDPClient::OnPadData(Response::PadData data, std::size_t client) {
  171. const std::size_t pad_index = (client * PADS_PER_CLIENT) + data.info.id;
  172. if (pad_index >= pads.size()) {
  173. LOG_ERROR(Input, "Invalid pad id {}", data.info.id);
  174. return;
  175. }
  176. LOG_TRACE(Input, "PadData packet received");
  177. if (data.packet_counter == pads[pad_index].packet_sequence) {
  178. LOG_WARNING(
  179. Input,
  180. "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
  181. pads[pad_index].packet_sequence, data.packet_counter);
  182. pads[pad_index].connected = false;
  183. return;
  184. }
  185. clients[client].active = 1;
  186. pads[pad_index].connected = true;
  187. pads[pad_index].packet_sequence = data.packet_counter;
  188. const auto now = std::chrono::steady_clock::now();
  189. const auto time_difference = static_cast<u64>(
  190. std::chrono::duration_cast<std::chrono::microseconds>(now - pads[pad_index].last_update)
  191. .count());
  192. pads[pad_index].last_update = now;
  193. // Gyroscope values are not it the correct scale from better joy.
  194. // Dividing by 312 allows us to make one full turn = 1 turn
  195. // This must be a configurable valued called sensitivity
  196. const float gyro_scale = 1.0f / 312.0f;
  197. const BasicMotion motion{
  198. .gyro_x = data.gyro.pitch * gyro_scale,
  199. .gyro_y = data.gyro.roll * gyro_scale,
  200. .gyro_z = -data.gyro.yaw * gyro_scale,
  201. .accel_x = data.accel.x,
  202. .accel_y = -data.accel.z,
  203. .accel_z = data.accel.y,
  204. .delta_timestamp = time_difference,
  205. };
  206. const PadIdentifier identifier = GetPadIdentifier(pad_index);
  207. SetMotion(identifier, 0, motion);
  208. for (std::size_t id = 0; id < data.touch.size(); ++id) {
  209. const auto touch_pad = data.touch[id];
  210. const int touch_id = static_cast<int>(client * 2 + id);
  211. // TODO: Use custom calibration per device
  212. const Common::ParamPackage touch_param(Settings::values.touch_device.GetValue());
  213. const u16 min_x = static_cast<u16>(touch_param.Get("min_x", 100));
  214. const u16 min_y = static_cast<u16>(touch_param.Get("min_y", 50));
  215. const u16 max_x = static_cast<u16>(touch_param.Get("max_x", 1800));
  216. const u16 max_y = static_cast<u16>(touch_param.Get("max_y", 850));
  217. const f32 x =
  218. static_cast<f32>(std::clamp(static_cast<u16>(touch_pad.x), min_x, max_x) - min_x) /
  219. static_cast<f32>(max_x - min_x);
  220. const f32 y =
  221. static_cast<f32>(std::clamp(static_cast<u16>(touch_pad.y), min_y, max_y) - min_y) /
  222. static_cast<f32>(max_y - min_y);
  223. if (touch_pad.is_active) {
  224. SetAxis(identifier, touch_id * 2, x);
  225. SetAxis(identifier, touch_id * 2 + 1, y);
  226. SetButton(identifier, touch_id, true);
  227. continue;
  228. }
  229. SetButton(identifier, touch_id, false);
  230. }
  231. }
  232. void UDPClient::StartCommunication(std::size_t client, const std::string& host, u16 port) {
  233. SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
  234. [this](Response::PortInfo info) { OnPortInfo(info); },
  235. [this, client](Response::PadData data) { OnPadData(data, client); }};
  236. LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port);
  237. clients[client].host = host;
  238. clients[client].port = port;
  239. clients[client].active = 0;
  240. clients[client].socket = std::make_unique<Socket>(host, port, callback);
  241. clients[client].thread = std::thread{SocketLoop, clients[client].socket.get()};
  242. for (std::size_t index = 0; index < PADS_PER_CLIENT; ++index) {
  243. const PadIdentifier identifier = GetPadIdentifier(client * PADS_PER_CLIENT + index);
  244. PreSetController(identifier);
  245. }
  246. }
  247. const PadIdentifier UDPClient::GetPadIdentifier(std::size_t pad_index) const {
  248. const std::size_t client = pad_index / PADS_PER_CLIENT;
  249. return {
  250. .guid = Common::UUID{clients[client].host},
  251. .port = static_cast<std::size_t>(clients[client].port),
  252. .pad = pad_index,
  253. };
  254. }
  255. void UDPClient::Reset() {
  256. for (auto& client : clients) {
  257. if (client.thread.joinable()) {
  258. client.active = -1;
  259. client.socket->Stop();
  260. client.thread.join();
  261. }
  262. }
  263. }
  264. void TestCommunication(const std::string& host, u16 port,
  265. const std::function<void()>& success_callback,
  266. const std::function<void()>& failure_callback) {
  267. std::thread([=] {
  268. Common::Event success_event;
  269. SocketCallback callback{
  270. .version = [](Response::Version) {},
  271. .port_info = [](Response::PortInfo) {},
  272. .pad_data = [&](Response::PadData) { success_event.Set(); },
  273. };
  274. Socket socket{host, port, std::move(callback)};
  275. std::thread worker_thread{SocketLoop, &socket};
  276. const bool result =
  277. success_event.WaitUntil(std::chrono::steady_clock::now() + std::chrono::seconds(10));
  278. socket.Stop();
  279. worker_thread.join();
  280. if (result) {
  281. success_callback();
  282. } else {
  283. failure_callback();
  284. }
  285. }).detach();
  286. }
  287. CalibrationConfigurationJob::CalibrationConfigurationJob(
  288. const std::string& host, u16 port, std::function<void(Status)> status_callback,
  289. std::function<void(u16, u16, u16, u16)> data_callback) {
  290. std::thread([=, this] {
  291. Status current_status{Status::Initialized};
  292. SocketCallback callback{
  293. [](Response::Version) {}, [](Response::PortInfo) {},
  294. [&](Response::PadData data) {
  295. static constexpr u16 CALIBRATION_THRESHOLD = 100;
  296. static constexpr u16 MAX_VALUE = UINT16_MAX;
  297. if (current_status == Status::Initialized) {
  298. // Receiving data means the communication is ready now
  299. current_status = Status::Ready;
  300. status_callback(current_status);
  301. }
  302. const auto& touchpad_0 = data.touch[0];
  303. if (touchpad_0.is_active == 0) {
  304. return;
  305. }
  306. LOG_DEBUG(Input, "Current touch: {} {}", touchpad_0.x, touchpad_0.y);
  307. const u16 min_x = std::min(MAX_VALUE, static_cast<u16>(touchpad_0.x));
  308. const u16 min_y = std::min(MAX_VALUE, static_cast<u16>(touchpad_0.y));
  309. if (current_status == Status::Ready) {
  310. // First touch - min data (min_x/min_y)
  311. current_status = Status::Stage1Completed;
  312. status_callback(current_status);
  313. }
  314. if (touchpad_0.x - min_x > CALIBRATION_THRESHOLD &&
  315. touchpad_0.y - min_y > CALIBRATION_THRESHOLD) {
  316. // Set the current position as max value and finishes configuration
  317. const u16 max_x = touchpad_0.x;
  318. const u16 max_y = touchpad_0.y;
  319. current_status = Status::Completed;
  320. data_callback(min_x, min_y, max_x, max_y);
  321. status_callback(current_status);
  322. complete_event.Set();
  323. }
  324. }};
  325. Socket socket{host, port, std::move(callback)};
  326. std::thread worker_thread{SocketLoop, &socket};
  327. complete_event.Wait();
  328. socket.Stop();
  329. worker_thread.join();
  330. }).detach();
  331. }
  332. CalibrationConfigurationJob::~CalibrationConfigurationJob() {
  333. Stop();
  334. }
  335. void CalibrationConfigurationJob::Stop() {
  336. complete_event.Set();
  337. }
  338. } // namespace InputCommon::CemuhookUDP