client.cpp 19 KB

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