client.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. for (std::size_t client = 0; client < clients.size(); client++) {
  120. const auto pad = client % 4;
  121. StartCommunication(client, Settings::values.udp_input_address,
  122. Settings::values.udp_input_port, pad, 24872);
  123. // Set motion parameters
  124. // SetGyroThreshold value should be dependent on GyroscopeZeroDriftMode
  125. // Real HW values are unknown, 0.0001 is an approximate to Standard
  126. clients[client].motion.SetGyroThreshold(0.0001f);
  127. }
  128. }
  129. Client::~Client() {
  130. Reset();
  131. }
  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 pad) const {
  148. // Use last timestamp to detect if the socket has stopped sending data
  149. const auto now = std::chrono::system_clock::now();
  150. const auto time_difference = static_cast<u64>(
  151. std::chrono::duration_cast<std::chrono::milliseconds>(now - clients[pad].last_motion_update)
  152. .count());
  153. return time_difference < 1000 && clients[pad].active == 1;
  154. }
  155. void Client::ReloadUDPClient() {
  156. for (std::size_t client = 0; client < clients.size(); client++) {
  157. ReloadSocket(Settings::values.udp_input_address, Settings::values.udp_input_port, client);
  158. }
  159. }
  160. void Client::ReloadSocket(const std::string& host, u16 port, std::size_t pad_index, u32 client_id) {
  161. // client number must be determined from host / port and pad index
  162. const std::size_t client = pad_index;
  163. clients[client].socket->Stop();
  164. clients[client].thread.join();
  165. StartCommunication(client, host, port, pad_index, client_id);
  166. }
  167. void Client::OnVersion([[maybe_unused]] Response::Version data) {
  168. LOG_TRACE(Input, "Version packet received: {}", data.version);
  169. }
  170. void Client::OnPortInfo([[maybe_unused]] Response::PortInfo data) {
  171. LOG_TRACE(Input, "PortInfo packet received: {}", data.model);
  172. }
  173. void Client::OnPadData(Response::PadData data) {
  174. // Client number must be determined from host / port and pad index
  175. const std::size_t client = data.info.id;
  176. LOG_TRACE(Input, "PadData packet received");
  177. if (data.packet_counter == clients[client].packet_sequence) {
  178. LOG_WARNING(
  179. Input,
  180. "PadData packet dropped because its stale info. Current count: {} Packet count: {}",
  181. clients[client].packet_sequence, data.packet_counter);
  182. return;
  183. }
  184. clients[client].active = data.info.is_pad_active;
  185. clients[client].packet_sequence = data.packet_counter;
  186. const auto now = std::chrono::system_clock::now();
  187. const auto time_difference =
  188. static_cast<u64>(std::chrono::duration_cast<std::chrono::microseconds>(
  189. now - clients[client].last_motion_update)
  190. .count());
  191. clients[client].last_motion_update = now;
  192. const Common::Vec3f raw_gyroscope = {data.gyro.pitch, data.gyro.roll, -data.gyro.yaw};
  193. clients[client].motion.SetAcceleration({data.accel.x, -data.accel.z, data.accel.y});
  194. // Gyroscope values are not it the correct scale from better joy.
  195. // Dividing by 312 allows us to make one full turn = 1 turn
  196. // This must be a configurable valued called sensitivity
  197. clients[client].motion.SetGyroscope(raw_gyroscope / 312.0f);
  198. clients[client].motion.UpdateRotation(time_difference);
  199. clients[client].motion.UpdateOrientation(time_difference);
  200. {
  201. std::lock_guard guard(clients[client].status.update_mutex);
  202. clients[client].status.motion_status = clients[client].motion.GetMotion();
  203. // TODO: add a setting for "click" touch. Click touch refers to a device that differentiates
  204. // between a simple "tap" and a hard press that causes the touch screen to click.
  205. const bool is_active = data.touch_1.is_active != 0;
  206. float x = 0;
  207. float y = 0;
  208. if (is_active && clients[client].status.touch_calibration) {
  209. const u16 min_x = clients[client].status.touch_calibration->min_x;
  210. const u16 max_x = clients[client].status.touch_calibration->max_x;
  211. const u16 min_y = clients[client].status.touch_calibration->min_y;
  212. const u16 max_y = clients[client].status.touch_calibration->max_y;
  213. x = static_cast<float>(std::clamp(static_cast<u16>(data.touch_1.x), min_x, max_x) -
  214. min_x) /
  215. static_cast<float>(max_x - min_x);
  216. y = static_cast<float>(std::clamp(static_cast<u16>(data.touch_1.y), min_y, max_y) -
  217. min_y) /
  218. static_cast<float>(max_y - min_y);
  219. }
  220. clients[client].status.touch_status = {x, y, is_active};
  221. if (configuring) {
  222. const Common::Vec3f gyroscope = clients[client].motion.GetGyroscope();
  223. const Common::Vec3f accelerometer = clients[client].motion.GetAcceleration();
  224. UpdateYuzuSettings(client, accelerometer, gyroscope, is_active);
  225. }
  226. }
  227. }
  228. void Client::StartCommunication(std::size_t client, const std::string& host, u16 port,
  229. std::size_t pad_index, u32 client_id) {
  230. SocketCallback callback{[this](Response::Version version) { OnVersion(version); },
  231. [this](Response::PortInfo info) { OnPortInfo(info); },
  232. [this](Response::PadData data) { OnPadData(data); }};
  233. LOG_INFO(Input, "Starting communication with UDP input server on {}:{}", host, port);
  234. clients[client].socket = std::make_unique<Socket>(host, port, pad_index, client_id, callback);
  235. clients[client].thread = std::thread{SocketLoop, clients[client].socket.get()};
  236. }
  237. void Client::Reset() {
  238. for (auto& client : clients) {
  239. client.socket->Stop();
  240. client.thread.join();
  241. }
  242. }
  243. void Client::UpdateYuzuSettings(std::size_t client, const Common::Vec3<float>& acc,
  244. const Common::Vec3<float>& gyro, bool touch) {
  245. if (gyro.Length() > 0.2f) {
  246. LOG_DEBUG(Input, "UDP Controller {}: gyro=({}, {}, {}), accel=({}, {}, {}), touch={}",
  247. client, gyro[0], gyro[1], gyro[2], acc[0], acc[1], acc[2], touch);
  248. }
  249. UDPPadStatus pad;
  250. if (touch) {
  251. pad.touch = PadTouch::Click;
  252. pad_queue[client].Push(pad);
  253. }
  254. for (size_t i = 0; i < 3; ++i) {
  255. if (gyro[i] > 5.0f || gyro[i] < -5.0f) {
  256. pad.motion = static_cast<PadMotion>(i);
  257. pad.motion_value = gyro[i];
  258. pad_queue[client].Push(pad);
  259. }
  260. if (acc[i] > 1.75f || acc[i] < -1.75f) {
  261. pad.motion = static_cast<PadMotion>(i + 3);
  262. pad.motion_value = acc[i];
  263. pad_queue[client].Push(pad);
  264. }
  265. }
  266. }
  267. void Client::BeginConfiguration() {
  268. for (auto& pq : pad_queue) {
  269. pq.Clear();
  270. }
  271. configuring = true;
  272. }
  273. void Client::EndConfiguration() {
  274. for (auto& pq : pad_queue) {
  275. pq.Clear();
  276. }
  277. configuring = false;
  278. }
  279. DeviceStatus& Client::GetPadState(std::size_t pad) {
  280. return clients[pad].status;
  281. }
  282. const DeviceStatus& Client::GetPadState(std::size_t pad) const {
  283. return clients[pad].status;
  284. }
  285. std::array<Common::SPSCQueue<UDPPadStatus>, 4>& Client::GetPadQueue() {
  286. return pad_queue;
  287. }
  288. const std::array<Common::SPSCQueue<UDPPadStatus>, 4>& Client::GetPadQueue() const {
  289. return pad_queue;
  290. }
  291. void TestCommunication(const std::string& host, u16 port, std::size_t pad_index, u32 client_id,
  292. const std::function<void()>& success_callback,
  293. const std::function<void()>& failure_callback) {
  294. std::thread([=] {
  295. Common::Event success_event;
  296. SocketCallback callback{
  297. .version = [](Response::Version) {},
  298. .port_info = [](Response::PortInfo) {},
  299. .pad_data = [&](Response::PadData) { success_event.Set(); },
  300. };
  301. Socket socket{host, port, pad_index, client_id, std::move(callback)};
  302. std::thread worker_thread{SocketLoop, &socket};
  303. const bool result = success_event.WaitFor(std::chrono::seconds(5));
  304. socket.Stop();
  305. worker_thread.join();
  306. if (result) {
  307. success_callback();
  308. } else {
  309. failure_callback();
  310. }
  311. }).detach();
  312. }
  313. CalibrationConfigurationJob::CalibrationConfigurationJob(
  314. const std::string& host, u16 port, std::size_t pad_index, u32 client_id,
  315. std::function<void(Status)> status_callback,
  316. std::function<void(u16, u16, u16, u16)> data_callback) {
  317. std::thread([=, this] {
  318. constexpr u16 CALIBRATION_THRESHOLD = 100;
  319. u16 min_x{UINT16_MAX};
  320. u16 min_y{UINT16_MAX};
  321. u16 max_x{};
  322. u16 max_y{};
  323. Status current_status{Status::Initialized};
  324. SocketCallback callback{[](Response::Version) {}, [](Response::PortInfo) {},
  325. [&](Response::PadData data) {
  326. if (current_status == Status::Initialized) {
  327. // Receiving data means the communication is ready now
  328. current_status = Status::Ready;
  329. status_callback(current_status);
  330. }
  331. if (data.touch_1.is_active == 0) {
  332. return;
  333. }
  334. LOG_DEBUG(Input, "Current touch: {} {}", data.touch_1.x,
  335. data.touch_1.y);
  336. min_x = std::min(min_x, static_cast<u16>(data.touch_1.x));
  337. min_y = std::min(min_y, static_cast<u16>(data.touch_1.y));
  338. if (current_status == Status::Ready) {
  339. // First touch - min data (min_x/min_y)
  340. current_status = Status::Stage1Completed;
  341. status_callback(current_status);
  342. }
  343. if (data.touch_1.x - min_x > CALIBRATION_THRESHOLD &&
  344. data.touch_1.y - min_y > CALIBRATION_THRESHOLD) {
  345. // Set the current position as max value and finishes
  346. // configuration
  347. max_x = data.touch_1.x;
  348. max_y = data.touch_1.y;
  349. current_status = Status::Completed;
  350. data_callback(min_x, min_y, max_x, max_y);
  351. status_callback(current_status);
  352. complete_event.Set();
  353. }
  354. }};
  355. Socket socket{host, port, pad_index, client_id, std::move(callback)};
  356. std::thread worker_thread{SocketLoop, &socket};
  357. complete_event.Wait();
  358. socket.Stop();
  359. worker_thread.join();
  360. }).detach();
  361. }
  362. CalibrationConfigurationJob::~CalibrationConfigurationJob() {
  363. Stop();
  364. }
  365. void CalibrationConfigurationJob::Stop() {
  366. complete_event.Set();
  367. }
  368. } // namespace InputCommon::CemuhookUDP