udp_client.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. }
  209. void UDPClient::StartCommunication(std::size_t client, const std::string& host, u16 port) {
  210. SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
  211. [this](Response::PortInfo info) { OnPortInfo(info); },
  212. [this, client](Response::PadData data) { OnPadData(data, client); }};
  213. LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port);
  214. clients[client].host = host;
  215. clients[client].port = port;
  216. clients[client].active = 0;
  217. clients[client].socket = std::make_unique<Socket>(host, port, callback);
  218. clients[client].thread = std::thread{SocketLoop, clients[client].socket.get()};
  219. for (std::size_t index = 0; index < PADS_PER_CLIENT; ++index) {
  220. const PadIdentifier identifier = GetPadIdentifier(client * PADS_PER_CLIENT + index);
  221. PreSetController(identifier);
  222. }
  223. }
  224. const PadIdentifier UDPClient::GetPadIdentifier(std::size_t pad_index) const {
  225. const std::size_t client = pad_index / PADS_PER_CLIENT;
  226. return {
  227. .guid = Common::UUID{clients[client].host},
  228. .port = static_cast<std::size_t>(clients[client].port),
  229. .pad = pad_index,
  230. };
  231. }
  232. void UDPClient::Reset() {
  233. for (auto& client : clients) {
  234. if (client.thread.joinable()) {
  235. client.active = -1;
  236. client.socket->Stop();
  237. client.thread.join();
  238. }
  239. }
  240. }
  241. void TestCommunication(const std::string& host, u16 port,
  242. const std::function<void()>& success_callback,
  243. const std::function<void()>& failure_callback) {
  244. std::thread([=] {
  245. Common::Event success_event;
  246. SocketCallback callback{
  247. .version = [](Response::Version) {},
  248. .port_info = [](Response::PortInfo) {},
  249. .pad_data = [&](Response::PadData) { success_event.Set(); },
  250. };
  251. Socket socket{host, port, std::move(callback)};
  252. std::thread worker_thread{SocketLoop, &socket};
  253. const bool result =
  254. success_event.WaitUntil(std::chrono::steady_clock::now() + std::chrono::seconds(10));
  255. socket.Stop();
  256. worker_thread.join();
  257. if (result) {
  258. success_callback();
  259. } else {
  260. failure_callback();
  261. }
  262. }).detach();
  263. }
  264. CalibrationConfigurationJob::CalibrationConfigurationJob(
  265. const std::string& host, u16 port, std::function<void(Status)> status_callback,
  266. std::function<void(u16, u16, u16, u16)> data_callback) {
  267. std::thread([=, this] {
  268. Status current_status{Status::Initialized};
  269. SocketCallback callback{
  270. [](Response::Version) {}, [](Response::PortInfo) {},
  271. [&](Response::PadData data) {
  272. static constexpr u16 CALIBRATION_THRESHOLD = 100;
  273. static constexpr u16 MAX_VALUE = UINT16_MAX;
  274. if (current_status == Status::Initialized) {
  275. // Receiving data means the communication is ready now
  276. current_status = Status::Ready;
  277. status_callback(current_status);
  278. }
  279. const auto& touchpad_0 = data.touch[0];
  280. if (touchpad_0.is_active == 0) {
  281. return;
  282. }
  283. LOG_DEBUG(Input, "Current touch: {} {}", touchpad_0.x, touchpad_0.y);
  284. const u16 min_x = std::min(MAX_VALUE, static_cast<u16>(touchpad_0.x));
  285. const u16 min_y = std::min(MAX_VALUE, static_cast<u16>(touchpad_0.y));
  286. if (current_status == Status::Ready) {
  287. // First touch - min data (min_x/min_y)
  288. current_status = Status::Stage1Completed;
  289. status_callback(current_status);
  290. }
  291. if (touchpad_0.x - min_x > CALIBRATION_THRESHOLD &&
  292. touchpad_0.y - min_y > CALIBRATION_THRESHOLD) {
  293. // Set the current position as max value and finishes configuration
  294. const u16 max_x = touchpad_0.x;
  295. const u16 max_y = touchpad_0.y;
  296. current_status = Status::Completed;
  297. data_callback(min_x, min_y, max_x, max_y);
  298. status_callback(current_status);
  299. complete_event.Set();
  300. }
  301. }};
  302. Socket socket{host, port, std::move(callback)};
  303. std::thread worker_thread{SocketLoop, &socket};
  304. complete_event.Wait();
  305. socket.Stop();
  306. worker_thread.join();
  307. }).detach();
  308. }
  309. CalibrationConfigurationJob::~CalibrationConfigurationJob() {
  310. Stop();
  311. }
  312. void CalibrationConfigurationJob::Stop() {
  313. complete_event.Set();
  314. }
  315. } // namespace InputCommon::CemuhookUDP