client.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. // Copyright 2018 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <chrono>
  5. #include <cstring>
  6. #include <functional>
  7. #include <random>
  8. #include <thread>
  9. #include <boost/asio.hpp>
  10. #include "common/logging/log.h"
  11. #include "core/settings.h"
  12. #include "input_common/udp/client.h"
  13. #include "input_common/udp/protocol.h"
  14. using boost::asio::ip::udp;
  15. namespace InputCommon::CemuhookUDP {
  16. struct SocketCallback {
  17. std::function<void(Response::Version)> version;
  18. std::function<void(Response::PortInfo)> port_info;
  19. std::function<void(Response::PadData)> pad_data;
  20. };
  21. class Socket {
  22. public:
  23. using clock = std::chrono::system_clock;
  24. explicit Socket(const std::string& host, u16 port, std::size_t pad_index_,
  25. SocketCallback callback_)
  26. : callback(std::move(callback_)), timer(io_service),
  27. socket(io_service, udp::endpoint(udp::v4(), 0)), client_id(GenerateRandomClientId()),
  28. pad_index(pad_index_) {
  29. boost::system::error_code ec{};
  30. auto ipv4 = boost::asio::ip::make_address_v4(host, ec);
  31. if (ec.value() != boost::system::errc::success) {
  32. LOG_ERROR(Input, "Invalid IPv4 address \"{}\" provided to socket", host);
  33. ipv4 = boost::asio::ip::address_v4{};
  34. }
  35. send_endpoint = {udp::endpoint(ipv4, port)};
  36. }
  37. void Stop() {
  38. io_service.stop();
  39. }
  40. void Loop() {
  41. io_service.run();
  42. }
  43. void StartSend(const clock::time_point& from) {
  44. timer.expires_at(from + std::chrono::seconds(3));
  45. timer.async_wait([this](const boost::system::error_code& error) { HandleSend(error); });
  46. }
  47. void StartReceive() {
  48. socket.async_receive_from(
  49. boost::asio::buffer(receive_buffer), receive_endpoint,
  50. [this](const boost::system::error_code& error, std::size_t bytes_transferred) {
  51. HandleReceive(error, bytes_transferred);
  52. });
  53. }
  54. private:
  55. u32 GenerateRandomClientId() const {
  56. std::random_device device;
  57. return device();
  58. }
  59. void HandleReceive(const boost::system::error_code&, std::size_t bytes_transferred) {
  60. if (auto type = Response::Validate(receive_buffer.data(), bytes_transferred)) {
  61. switch (*type) {
  62. case Type::Version: {
  63. Response::Version version;
  64. std::memcpy(&version, &receive_buffer[sizeof(Header)], sizeof(Response::Version));
  65. callback.version(std::move(version));
  66. break;
  67. }
  68. case Type::PortInfo: {
  69. Response::PortInfo port_info;
  70. std::memcpy(&port_info, &receive_buffer[sizeof(Header)],
  71. sizeof(Response::PortInfo));
  72. callback.port_info(std::move(port_info));
  73. break;
  74. }
  75. case Type::PadData: {
  76. Response::PadData pad_data;
  77. std::memcpy(&pad_data, &receive_buffer[sizeof(Header)], sizeof(Response::PadData));
  78. callback.pad_data(std::move(pad_data));
  79. break;
  80. }
  81. }
  82. }
  83. StartReceive();
  84. }
  85. void HandleSend(const boost::system::error_code&) {
  86. boost::system::error_code _ignored{};
  87. // Send a request for getting port info for the pad
  88. const Request::PortInfo port_info{1, {static_cast<u8>(pad_index), 0, 0, 0}};
  89. const auto port_message = Request::Create(port_info, client_id);
  90. std::memcpy(&send_buffer1, &port_message, PORT_INFO_SIZE);
  91. socket.send_to(boost::asio::buffer(send_buffer1), send_endpoint, {}, _ignored);
  92. // Send a request for getting pad data for the pad
  93. const Request::PadData pad_data{
  94. Request::PadData::Flags::Id,
  95. static_cast<u8>(pad_index),
  96. EMPTY_MAC_ADDRESS,
  97. };
  98. const auto pad_message = Request::Create(pad_data, client_id);
  99. std::memcpy(send_buffer2.data(), &pad_message, PAD_DATA_SIZE);
  100. socket.send_to(boost::asio::buffer(send_buffer2), send_endpoint, {}, _ignored);
  101. StartSend(timer.expiry());
  102. }
  103. SocketCallback callback;
  104. boost::asio::io_service io_service;
  105. boost::asio::basic_waitable_timer<clock> timer;
  106. udp::socket socket;
  107. const u32 client_id;
  108. std::size_t pad_index{};
  109. static constexpr std::size_t PORT_INFO_SIZE = sizeof(Message<Request::PortInfo>);
  110. static constexpr std::size_t PAD_DATA_SIZE = sizeof(Message<Request::PadData>);
  111. std::array<u8, PORT_INFO_SIZE> send_buffer1;
  112. std::array<u8, PAD_DATA_SIZE> send_buffer2;
  113. udp::endpoint send_endpoint;
  114. std::array<u8, MAX_PACKET_SIZE> receive_buffer;
  115. udp::endpoint receive_endpoint;
  116. };
  117. static void SocketLoop(Socket* socket) {
  118. socket->StartReceive();
  119. socket->StartSend(Socket::clock::now());
  120. socket->Loop();
  121. }
  122. Client::Client() {
  123. LOG_INFO(Input, "Udp Initialization started");
  124. finger_id.fill(MAX_TOUCH_FINGERS);
  125. ReloadSockets();
  126. }
  127. Client::~Client() {
  128. Reset();
  129. }
  130. Client::ClientData::ClientData() = default;
  131. Client::ClientData::~ClientData() = default;
  132. std::vector<Common::ParamPackage> Client::GetInputDevices() const {
  133. std::vector<Common::ParamPackage> devices;
  134. for (std::size_t client = 0; client < clients.size(); client++) {
  135. if (!DeviceConnected(client)) {
  136. continue;
  137. }
  138. std::string name = fmt::format("UDP Controller {}", client);
  139. devices.emplace_back(Common::ParamPackage{
  140. {"class", "cemuhookudp"},
  141. {"display", std::move(name)},
  142. {"port", std::to_string(client)},
  143. });
  144. }
  145. return devices;
  146. }
  147. bool Client::DeviceConnected(std::size_t client) const {
  148. // Use last timestamp to detect if the socket has stopped sending data
  149. const auto now = std::chrono::steady_clock::now();
  150. const auto time_difference =
  151. static_cast<u64>(std::chrono::duration_cast<std::chrono::milliseconds>(
  152. now - clients[client].last_motion_update)
  153. .count());
  154. return time_difference < 1000 && clients[client].active == 1;
  155. }
  156. void Client::ReloadSockets() {
  157. Reset();
  158. std::stringstream servers_ss(Settings::values.udp_input_servers);
  159. std::string server_token;
  160. std::size_t client = 0;
  161. while (std::getline(servers_ss, server_token, ',')) {
  162. if (client == MAX_UDP_CLIENTS) {
  163. break;
  164. }
  165. std::stringstream server_ss(server_token);
  166. std::string token;
  167. std::getline(server_ss, token, ':');
  168. std::string udp_input_address = token;
  169. std::getline(server_ss, token, ':');
  170. char* temp;
  171. const u16 udp_input_port = static_cast<u16>(std::strtol(token.c_str(), &temp, 0));
  172. if (*temp != '\0') {
  173. LOG_ERROR(Input, "Port number is not valid {}", token);
  174. continue;
  175. }
  176. for (std::size_t pad = 0; pad < 4; ++pad) {
  177. const std::size_t client_number =
  178. GetClientNumber(udp_input_address, udp_input_port, pad);
  179. if (client_number != MAX_UDP_CLIENTS) {
  180. LOG_ERROR(Input, "Duplicated UDP servers found");
  181. continue;
  182. }
  183. StartCommunication(client++, udp_input_address, udp_input_port, pad);
  184. }
  185. }
  186. }
  187. std::size_t Client::GetClientNumber(std::string_view host, u16 port, std::size_t pad) const {
  188. for (std::size_t client = 0; client < clients.size(); client++) {
  189. if (clients[client].active == -1) {
  190. continue;
  191. }
  192. if (clients[client].host == host && clients[client].port == port &&
  193. clients[client].pad_index == pad) {
  194. return client;
  195. }
  196. }
  197. return MAX_UDP_CLIENTS;
  198. }
  199. void Client::OnVersion([[maybe_unused]] Response::Version data) {
  200. LOG_TRACE(Input, "Version packet received: {}", data.version);
  201. }
  202. void Client::OnPortInfo([[maybe_unused]] Response::PortInfo data) {
  203. LOG_TRACE(Input, "PortInfo packet received: {}", data.model);
  204. }
  205. void Client::OnPadData(Response::PadData data, std::size_t client) {
  206. // Accept packets only for the correct pad
  207. if (static_cast<u8>(clients[client].pad_index) != data.info.id) {
  208. return;
  209. }
  210. LOG_TRACE(Input, "PadData packet received");
  211. if (data.packet_counter == clients[client].packet_sequence) {
  212. LOG_WARNING(
  213. Input,
  214. "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
  215. clients[client].packet_sequence, data.packet_counter);
  216. return;
  217. }
  218. clients[client].active = static_cast<s8>(data.info.is_pad_active);
  219. clients[client].packet_sequence = data.packet_counter;
  220. const auto now = std::chrono::steady_clock::now();
  221. const auto time_difference =
  222. static_cast<u64>(std::chrono::duration_cast<std::chrono::microseconds>(
  223. now - clients[client].last_motion_update)
  224. .count());
  225. clients[client].last_motion_update = now;
  226. const Common::Vec3f raw_gyroscope = {data.gyro.pitch, data.gyro.roll, -data.gyro.yaw};
  227. clients[client].motion.SetAcceleration({data.accel.x, -data.accel.z, data.accel.y});
  228. // Gyroscope values are not it the correct scale from better joy.
  229. // Dividing by 312 allows us to make one full turn = 1 turn
  230. // This must be a configurable valued called sensitivity
  231. clients[client].motion.SetGyroscope(raw_gyroscope / 312.0f);
  232. clients[client].motion.UpdateRotation(time_difference);
  233. clients[client].motion.UpdateOrientation(time_difference);
  234. {
  235. std::lock_guard guard(clients[client].status.update_mutex);
  236. clients[client].status.motion_status = clients[client].motion.GetMotion();
  237. for (std::size_t id = 0; id < data.touch.size(); ++id) {
  238. UpdateTouchInput(data.touch[id], client, id);
  239. }
  240. if (configuring) {
  241. const Common::Vec3f gyroscope = clients[client].motion.GetGyroscope();
  242. const Common::Vec3f accelerometer = clients[client].motion.GetAcceleration();
  243. UpdateYuzuSettings(client, accelerometer, gyroscope);
  244. }
  245. }
  246. }
  247. void Client::StartCommunication(std::size_t client, const std::string& host, u16 port,
  248. std::size_t pad_index) {
  249. SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
  250. [this](Response::PortInfo info) { OnPortInfo(info); },
  251. [this, client](Response::PadData data) { OnPadData(data, client); }};
  252. LOG_INFO(Input, "Starting communication with UDP input server on {}:{}:{}", host, port,
  253. pad_index);
  254. clients[client].host = host;
  255. clients[client].port = port;
  256. clients[client].pad_index = pad_index;
  257. clients[client].active = 0;
  258. clients[client].socket = std::make_unique<Socket>(host, port, pad_index, callback);
  259. clients[client].thread = std::thread{SocketLoop, clients[client].socket.get()};
  260. // Set motion parameters
  261. // SetGyroThreshold value should be dependent on GyroscopeZeroDriftMode
  262. // Real HW values are unknown, 0.0001 is an approximate to Standard
  263. clients[client].motion.SetGyroThreshold(0.0001f);
  264. }
  265. void Client::Reset() {
  266. for (auto& client : clients) {
  267. if (client.thread.joinable()) {
  268. client.active = -1;
  269. client.socket->Stop();
  270. client.thread.join();
  271. }
  272. }
  273. }
  274. void Client::UpdateYuzuSettings(std::size_t client, const Common::Vec3<float>& acc,
  275. const Common::Vec3<float>& gyro) {
  276. if (gyro.Length() > 0.2f) {
  277. LOG_DEBUG(Input, "UDP Controller {}: gyro=({}, {}, {}), accel=({}, {}, {})", client,
  278. gyro[0], gyro[1], gyro[2], acc[0], acc[1], acc[2]);
  279. }
  280. UDPPadStatus pad{
  281. .host = clients[client].host,
  282. .port = clients[client].port,
  283. .pad_index = clients[client].pad_index,
  284. };
  285. for (std::size_t i = 0; i < 3; ++i) {
  286. if (gyro[i] > 5.0f || gyro[i] < -5.0f) {
  287. pad.motion = static_cast<PadMotion>(i);
  288. pad.motion_value = gyro[i];
  289. pad_queue.Push(pad);
  290. }
  291. if (acc[i] > 1.75f || acc[i] < -1.75f) {
  292. pad.motion = static_cast<PadMotion>(i + 3);
  293. pad.motion_value = acc[i];
  294. pad_queue.Push(pad);
  295. }
  296. }
  297. }
  298. std::optional<std::size_t> Client::GetUnusedFingerID() const {
  299. std::size_t first_free_id = 0;
  300. while (first_free_id < MAX_TOUCH_FINGERS) {
  301. if (!std::get<2>(touch_status[first_free_id])) {
  302. return first_free_id;
  303. } else {
  304. first_free_id++;
  305. }
  306. }
  307. return std::nullopt;
  308. }
  309. void Client::UpdateTouchInput(Response::TouchPad& touch_pad, std::size_t client, std::size_t id) {
  310. // TODO: Use custom calibration per device
  311. const Common::ParamPackage touch_param(Settings::values.touch_device);
  312. const u16 min_x = static_cast<u16>(touch_param.Get("min_x", 100));
  313. const u16 min_y = static_cast<u16>(touch_param.Get("min_y", 50));
  314. const u16 max_x = static_cast<u16>(touch_param.Get("max_x", 1800));
  315. const u16 max_y = static_cast<u16>(touch_param.Get("max_y", 850));
  316. const std::size_t touch_id = client * 2 + id;
  317. if (touch_pad.is_active) {
  318. if (finger_id[touch_id] == MAX_TOUCH_FINGERS) {
  319. const auto first_free_id = GetUnusedFingerID();
  320. if (!first_free_id) {
  321. // Invalid finger id skip to next input
  322. return;
  323. }
  324. finger_id[touch_id] = *first_free_id;
  325. }
  326. auto& [x, y, pressed] = touch_status[finger_id[touch_id]];
  327. x = static_cast<float>(std::clamp(static_cast<u16>(touch_pad.x), min_x, max_x) - min_x) /
  328. static_cast<float>(max_x - min_x);
  329. y = static_cast<float>(std::clamp(static_cast<u16>(touch_pad.y), min_y, max_y) - min_y) /
  330. static_cast<float>(max_y - min_y);
  331. pressed = true;
  332. return;
  333. }
  334. if (finger_id[touch_id] != MAX_TOUCH_FINGERS) {
  335. touch_status[finger_id[touch_id]] = {};
  336. finger_id[touch_id] = MAX_TOUCH_FINGERS;
  337. }
  338. }
  339. void Client::BeginConfiguration() {
  340. pad_queue.Clear();
  341. configuring = true;
  342. }
  343. void Client::EndConfiguration() {
  344. pad_queue.Clear();
  345. configuring = false;
  346. }
  347. DeviceStatus& Client::GetPadState(const std::string& host, u16 port, std::size_t pad) {
  348. const std::size_t client_number = GetClientNumber(host, port, pad);
  349. if (client_number == MAX_UDP_CLIENTS) {
  350. return clients[0].status;
  351. }
  352. return clients[client_number].status;
  353. }
  354. const DeviceStatus& Client::GetPadState(const std::string& host, u16 port, std::size_t pad) const {
  355. const std::size_t client_number = GetClientNumber(host, port, pad);
  356. if (client_number == MAX_UDP_CLIENTS) {
  357. return clients[0].status;
  358. }
  359. return clients[client_number].status;
  360. }
  361. Input::TouchStatus& Client::GetTouchState() {
  362. return touch_status;
  363. }
  364. const Input::TouchStatus& Client::GetTouchState() const {
  365. return touch_status;
  366. }
  367. Common::SPSCQueue<UDPPadStatus>& Client::GetPadQueue() {
  368. return pad_queue;
  369. }
  370. const Common::SPSCQueue<UDPPadStatus>& Client::GetPadQueue() const {
  371. return pad_queue;
  372. }
  373. void TestCommunication(const std::string& host, u16 port, std::size_t pad_index,
  374. const std::function<void()>& success_callback,
  375. const std::function<void()>& failure_callback) {
  376. std::thread([=] {
  377. Common::Event success_event;
  378. SocketCallback callback{
  379. .version = [](Response::Version) {},
  380. .port_info = [](Response::PortInfo) {},
  381. .pad_data = [&](Response::PadData) { success_event.Set(); },
  382. };
  383. Socket socket{host, port, pad_index, std::move(callback)};
  384. std::thread worker_thread{SocketLoop, &socket};
  385. const bool result = success_event.WaitFor(std::chrono::seconds(5));
  386. socket.Stop();
  387. worker_thread.join();
  388. if (result) {
  389. success_callback();
  390. } else {
  391. failure_callback();
  392. }
  393. }).detach();
  394. }
  395. CalibrationConfigurationJob::CalibrationConfigurationJob(
  396. const std::string& host, u16 port, std::size_t pad_index,
  397. std::function<void(Status)> status_callback,
  398. std::function<void(u16, u16, u16, u16)> data_callback) {
  399. std::thread([=, this] {
  400. constexpr u16 CALIBRATION_THRESHOLD = 100;
  401. u16 min_x{UINT16_MAX};
  402. u16 min_y{UINT16_MAX};
  403. u16 max_x{};
  404. u16 max_y{};
  405. Status current_status{Status::Initialized};
  406. SocketCallback callback{[](Response::Version) {}, [](Response::PortInfo) {},
  407. [&](Response::PadData data) {
  408. if (current_status == Status::Initialized) {
  409. // Receiving data means the communication is ready now
  410. current_status = Status::Ready;
  411. status_callback(current_status);
  412. }
  413. if (data.touch[0].is_active == 0) {
  414. return;
  415. }
  416. LOG_DEBUG(Input, "Current touch: {} {}", data.touch[0].x,
  417. data.touch[0].y);
  418. min_x = std::min(min_x, static_cast<u16>(data.touch[0].x));
  419. min_y = std::min(min_y, static_cast<u16>(data.touch[0].y));
  420. if (current_status == Status::Ready) {
  421. // First touch - min data (min_x/min_y)
  422. current_status = Status::Stage1Completed;
  423. status_callback(current_status);
  424. }
  425. if (data.touch[0].x - min_x > CALIBRATION_THRESHOLD &&
  426. data.touch[0].y - min_y > CALIBRATION_THRESHOLD) {
  427. // Set the current position as max value and finishes
  428. // configuration
  429. max_x = data.touch[0].x;
  430. max_y = data.touch[0].y;
  431. current_status = Status::Completed;
  432. data_callback(min_x, min_y, max_x, max_y);
  433. status_callback(current_status);
  434. complete_event.Set();
  435. }
  436. }};
  437. Socket socket{host, port, pad_index, std::move(callback)};
  438. std::thread worker_thread{SocketLoop, &socket};
  439. complete_event.Wait();
  440. socket.Stop();
  441. worker_thread.join();
  442. }).detach();
  443. }
  444. CalibrationConfigurationJob::~CalibrationConfigurationJob() {
  445. Stop();
  446. }
  447. void CalibrationConfigurationJob::Stop() {
  448. complete_event.Set();
  449. }
  450. } // namespace InputCommon::CemuhookUDP