client.cpp 16 KB

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