joycon_driver.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. // SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "common/logging/log.h"
  4. #include "common/swap.h"
  5. #include "common/thread.h"
  6. #include "input_common/helpers/joycon_driver.h"
  7. #include "input_common/helpers/joycon_protocol/calibration.h"
  8. #include "input_common/helpers/joycon_protocol/generic_functions.h"
  9. #include "input_common/helpers/joycon_protocol/irs.h"
  10. #include "input_common/helpers/joycon_protocol/nfc.h"
  11. #include "input_common/helpers/joycon_protocol/poller.h"
  12. #include "input_common/helpers/joycon_protocol/ringcon.h"
  13. #include "input_common/helpers/joycon_protocol/rumble.h"
  14. namespace InputCommon::Joycon {
  15. JoyconDriver::JoyconDriver(std::size_t port_) : port{port_} {
  16. hidapi_handle = std::make_shared<JoyconHandle>();
  17. }
  18. JoyconDriver::~JoyconDriver() {
  19. Stop();
  20. }
  21. void JoyconDriver::Stop() {
  22. is_connected = false;
  23. input_thread = {};
  24. }
  25. DriverResult JoyconDriver::RequestDeviceAccess(SDL_hid_device_info* device_info) {
  26. std::scoped_lock lock{mutex};
  27. handle_device_type = ControllerType::None;
  28. GetDeviceType(device_info, handle_device_type);
  29. if (handle_device_type == ControllerType::None) {
  30. return DriverResult::UnsupportedControllerType;
  31. }
  32. hidapi_handle->handle =
  33. SDL_hid_open(device_info->vendor_id, device_info->product_id, device_info->serial_number);
  34. std::memcpy(&handle_serial_number, device_info->serial_number, 15);
  35. if (!hidapi_handle->handle) {
  36. LOG_ERROR(Input, "Yuzu can't gain access to this device: ID {:04X}:{:04X}.",
  37. device_info->vendor_id, device_info->product_id);
  38. return DriverResult::HandleInUse;
  39. }
  40. SDL_hid_set_nonblocking(hidapi_handle->handle, 1);
  41. return DriverResult::Success;
  42. }
  43. DriverResult JoyconDriver::InitializeDevice() {
  44. if (!hidapi_handle->handle) {
  45. return DriverResult::InvalidHandle;
  46. }
  47. std::scoped_lock lock{mutex};
  48. disable_input_thread = true;
  49. // Reset Counters
  50. error_counter = 0;
  51. hidapi_handle->packet_counter = 0;
  52. // Reset external device status
  53. starlink_connected = false;
  54. ring_connected = false;
  55. amiibo_detected = false;
  56. // Set HW default configuration
  57. vibration_enabled = true;
  58. motion_enabled = true;
  59. hidbus_enabled = false;
  60. nfc_enabled = false;
  61. passive_enabled = false;
  62. irs_enabled = false;
  63. gyro_sensitivity = Joycon::GyroSensitivity::DPS2000;
  64. gyro_performance = Joycon::GyroPerformance::HZ833;
  65. accelerometer_sensitivity = Joycon::AccelerometerSensitivity::G8;
  66. accelerometer_performance = Joycon::AccelerometerPerformance::HZ100;
  67. // Initialize HW Protocols
  68. calibration_protocol = std::make_unique<CalibrationProtocol>(hidapi_handle);
  69. generic_protocol = std::make_unique<GenericProtocol>(hidapi_handle);
  70. irs_protocol = std::make_unique<IrsProtocol>(hidapi_handle);
  71. nfc_protocol = std::make_unique<NfcProtocol>(hidapi_handle);
  72. ring_protocol = std::make_unique<RingConProtocol>(hidapi_handle);
  73. rumble_protocol = std::make_unique<RumbleProtocol>(hidapi_handle);
  74. // Get fixed joycon info
  75. generic_protocol->GetVersionNumber(version);
  76. generic_protocol->SetLowPowerMode(false);
  77. generic_protocol->GetColor(color);
  78. if (handle_device_type == ControllerType::Pro) {
  79. // Some 3rd party controllers aren't pro controllers
  80. generic_protocol->GetControllerType(device_type);
  81. } else {
  82. device_type = handle_device_type;
  83. }
  84. generic_protocol->GetSerialNumber(serial_number);
  85. supported_features = GetSupportedFeatures();
  86. // Get Calibration data
  87. calibration_protocol->GetLeftJoyStickCalibration(left_stick_calibration);
  88. calibration_protocol->GetRightJoyStickCalibration(right_stick_calibration);
  89. calibration_protocol->GetImuCalibration(motion_calibration);
  90. // Set led status
  91. generic_protocol->SetLedBlinkPattern(static_cast<u8>(1 + port));
  92. // Apply HW configuration
  93. SetPollingMode();
  94. // Initialize joycon poller
  95. joycon_poller = std::make_unique<JoyconPoller>(device_type, left_stick_calibration,
  96. right_stick_calibration, motion_calibration);
  97. // Start pooling for data
  98. is_connected = true;
  99. if (!input_thread_running) {
  100. input_thread =
  101. std::jthread([this](std::stop_token stop_token) { InputThread(stop_token); });
  102. }
  103. disable_input_thread = false;
  104. return DriverResult::Success;
  105. }
  106. void JoyconDriver::InputThread(std::stop_token stop_token) {
  107. LOG_INFO(Input, "Joycon Adapter input thread started");
  108. Common::SetCurrentThreadName("JoyconInput");
  109. input_thread_running = true;
  110. // Max update rate is 5ms, ensure we are always able to read a bit faster
  111. constexpr static int ThreadDelay = 2;
  112. std::vector<u8> buffer(MaxBufferSize);
  113. while (!stop_token.stop_requested()) {
  114. int status = 0;
  115. if (!IsInputThreadValid()) {
  116. input_thread.request_stop();
  117. continue;
  118. }
  119. // By disabling the input thread we can ensure custom commands will succeed as no package is
  120. // skipped
  121. if (!disable_input_thread) {
  122. status = SDL_hid_read_timeout(hidapi_handle->handle, buffer.data(), buffer.size(),
  123. ThreadDelay);
  124. } else {
  125. std::this_thread::sleep_for(std::chrono::milliseconds(ThreadDelay));
  126. }
  127. if (IsPayloadCorrect(status, buffer)) {
  128. OnNewData(buffer);
  129. }
  130. std::this_thread::yield();
  131. }
  132. is_connected = false;
  133. input_thread_running = false;
  134. LOG_INFO(Input, "Joycon Adapter input thread stopped");
  135. }
  136. void JoyconDriver::OnNewData(std::span<u8> buffer) {
  137. const auto report_mode = static_cast<ReportMode>(buffer[0]);
  138. // Packages can be a litte bit inconsistent. Average the delta time to provide a smoother motion
  139. // experience
  140. switch (report_mode) {
  141. case ReportMode::STANDARD_FULL_60HZ:
  142. case ReportMode::NFC_IR_MODE_60HZ:
  143. case ReportMode::SIMPLE_HID_MODE: {
  144. const auto now = std::chrono::steady_clock::now();
  145. const auto new_delta_time = static_cast<u64>(
  146. std::chrono::duration_cast<std::chrono::microseconds>(now - last_update).count());
  147. delta_time = ((delta_time * 8) + (new_delta_time * 2)) / 10;
  148. last_update = now;
  149. joycon_poller->UpdateColor(color);
  150. break;
  151. }
  152. default:
  153. break;
  154. }
  155. const MotionStatus motion_status{
  156. .is_enabled = motion_enabled,
  157. .delta_time = delta_time,
  158. .gyro_sensitivity = gyro_sensitivity,
  159. .accelerometer_sensitivity = accelerometer_sensitivity,
  160. };
  161. // TODO: Remove this when calibration is properly loaded and not calculated
  162. if (ring_connected && report_mode == ReportMode::STANDARD_FULL_60HZ) {
  163. InputReportActive data{};
  164. memcpy(&data, buffer.data(), sizeof(InputReportActive));
  165. calibration_protocol->GetRingCalibration(ring_calibration, data.ring_input);
  166. }
  167. const RingStatus ring_status{
  168. .is_enabled = ring_connected,
  169. .default_value = ring_calibration.default_value,
  170. .max_value = ring_calibration.max_value,
  171. .min_value = ring_calibration.min_value,
  172. };
  173. if (irs_protocol->IsEnabled()) {
  174. irs_protocol->RequestImage(buffer);
  175. joycon_poller->UpdateCamera(irs_protocol->GetImage(), irs_protocol->GetIrsFormat());
  176. }
  177. if (nfc_protocol->IsEnabled()) {
  178. if (amiibo_detected) {
  179. if (!nfc_protocol->HasAmiibo()) {
  180. joycon_poller->UpdateAmiibo({});
  181. amiibo_detected = false;
  182. return;
  183. }
  184. }
  185. if (!amiibo_detected) {
  186. std::vector<u8> data(0x21C);
  187. const auto result = nfc_protocol->ScanAmiibo(data);
  188. if (result == DriverResult::Success) {
  189. joycon_poller->UpdateAmiibo(data);
  190. amiibo_detected = true;
  191. }
  192. }
  193. }
  194. switch (report_mode) {
  195. case ReportMode::STANDARD_FULL_60HZ:
  196. joycon_poller->ReadActiveMode(buffer, motion_status, ring_status);
  197. break;
  198. case ReportMode::NFC_IR_MODE_60HZ:
  199. joycon_poller->ReadNfcIRMode(buffer, motion_status);
  200. break;
  201. case ReportMode::SIMPLE_HID_MODE:
  202. joycon_poller->ReadPassiveMode(buffer);
  203. break;
  204. case ReportMode::SUBCMD_REPLY:
  205. LOG_DEBUG(Input, "Unhandled command reply");
  206. break;
  207. default:
  208. LOG_ERROR(Input, "Report mode not Implemented {}", report_mode);
  209. break;
  210. }
  211. }
  212. DriverResult JoyconDriver::SetPollingMode() {
  213. disable_input_thread = true;
  214. rumble_protocol->EnableRumble(vibration_enabled && supported_features.vibration);
  215. if (motion_enabled && supported_features.motion) {
  216. generic_protocol->EnableImu(true);
  217. generic_protocol->SetImuConfig(gyro_sensitivity, gyro_performance,
  218. accelerometer_sensitivity, accelerometer_performance);
  219. } else {
  220. generic_protocol->EnableImu(false);
  221. }
  222. if (irs_protocol->IsEnabled()) {
  223. irs_protocol->DisableIrs();
  224. }
  225. if (nfc_protocol->IsEnabled()) {
  226. amiibo_detected = false;
  227. nfc_protocol->DisableNfc();
  228. }
  229. if (ring_protocol->IsEnabled()) {
  230. ring_connected = false;
  231. ring_protocol->DisableRingCon();
  232. }
  233. if (irs_enabled && supported_features.irs) {
  234. auto result = irs_protocol->EnableIrs();
  235. if (result == DriverResult::Success) {
  236. disable_input_thread = false;
  237. return result;
  238. }
  239. irs_protocol->DisableIrs();
  240. LOG_ERROR(Input, "Error enabling IRS");
  241. }
  242. if (nfc_enabled && supported_features.nfc) {
  243. auto result = nfc_protocol->EnableNfc();
  244. if (result == DriverResult::Success) {
  245. result = nfc_protocol->StartNFCPollingMode();
  246. }
  247. if (result == DriverResult::Success) {
  248. disable_input_thread = false;
  249. return result;
  250. }
  251. nfc_protocol->DisableNfc();
  252. LOG_ERROR(Input, "Error enabling NFC");
  253. }
  254. if (hidbus_enabled && supported_features.hidbus) {
  255. auto result = ring_protocol->EnableRingCon();
  256. if (result == DriverResult::Success) {
  257. result = ring_protocol->StartRingconPolling();
  258. }
  259. if (result == DriverResult::Success) {
  260. ring_connected = true;
  261. disable_input_thread = false;
  262. return result;
  263. }
  264. ring_connected = false;
  265. ring_protocol->DisableRingCon();
  266. LOG_ERROR(Input, "Error enabling Ringcon");
  267. }
  268. if (passive_enabled && supported_features.passive) {
  269. const auto result = generic_protocol->EnablePassiveMode();
  270. if (result == DriverResult::Success) {
  271. disable_input_thread = false;
  272. return result;
  273. }
  274. LOG_ERROR(Input, "Error enabling passive mode");
  275. }
  276. // Default Mode
  277. const auto result = generic_protocol->EnableActiveMode();
  278. if (result != DriverResult::Success) {
  279. LOG_ERROR(Input, "Error enabling active mode");
  280. }
  281. // Switch calls this function after enabling active mode
  282. generic_protocol->TriggersElapsed();
  283. disable_input_thread = false;
  284. return result;
  285. }
  286. JoyconDriver::SupportedFeatures JoyconDriver::GetSupportedFeatures() {
  287. SupportedFeatures features{
  288. .passive = true,
  289. .motion = true,
  290. .vibration = true,
  291. };
  292. if (device_type == ControllerType::Right) {
  293. features.nfc = true;
  294. features.irs = true;
  295. features.hidbus = true;
  296. }
  297. if (device_type == ControllerType::Pro) {
  298. features.nfc = true;
  299. }
  300. return features;
  301. }
  302. bool JoyconDriver::IsInputThreadValid() const {
  303. if (!is_connected.load()) {
  304. return false;
  305. }
  306. if (hidapi_handle->handle == nullptr) {
  307. return false;
  308. }
  309. // Controller is not responding. Terminate connection
  310. if (error_counter > MaxErrorCount) {
  311. return false;
  312. }
  313. return true;
  314. }
  315. bool JoyconDriver::IsPayloadCorrect(int status, std::span<const u8> buffer) {
  316. if (status <= -1) {
  317. error_counter++;
  318. return false;
  319. }
  320. // There's no new data
  321. if (status == 0) {
  322. return false;
  323. }
  324. // No reply ever starts with zero
  325. if (buffer[0] == 0x00) {
  326. error_counter++;
  327. return false;
  328. }
  329. error_counter = 0;
  330. return true;
  331. }
  332. DriverResult JoyconDriver::SetVibration(const VibrationValue& vibration) {
  333. std::scoped_lock lock{mutex};
  334. if (disable_input_thread) {
  335. return DriverResult::HandleInUse;
  336. }
  337. return rumble_protocol->SendVibration(vibration);
  338. }
  339. DriverResult JoyconDriver::SetLedConfig(u8 led_pattern) {
  340. std::scoped_lock lock{mutex};
  341. if (disable_input_thread) {
  342. return DriverResult::HandleInUse;
  343. }
  344. return generic_protocol->SetLedPattern(led_pattern);
  345. }
  346. DriverResult JoyconDriver::SetIrsConfig(IrsMode mode_, IrsResolution format_) {
  347. std::scoped_lock lock{mutex};
  348. if (disable_input_thread) {
  349. return DriverResult::HandleInUse;
  350. }
  351. disable_input_thread = true;
  352. const auto result = irs_protocol->SetIrsConfig(mode_, format_);
  353. disable_input_thread = false;
  354. return result;
  355. }
  356. DriverResult JoyconDriver::SetPasiveMode() {
  357. std::scoped_lock lock{mutex};
  358. motion_enabled = false;
  359. hidbus_enabled = false;
  360. nfc_enabled = false;
  361. passive_enabled = true;
  362. irs_enabled = false;
  363. return SetPollingMode();
  364. }
  365. DriverResult JoyconDriver::SetActiveMode() {
  366. if (is_ring_disabled_by_irs) {
  367. is_ring_disabled_by_irs = false;
  368. SetActiveMode();
  369. return SetRingConMode();
  370. }
  371. std::scoped_lock lock{mutex};
  372. motion_enabled = true;
  373. hidbus_enabled = false;
  374. nfc_enabled = false;
  375. passive_enabled = false;
  376. irs_enabled = false;
  377. return SetPollingMode();
  378. }
  379. DriverResult JoyconDriver::SetIrMode() {
  380. std::scoped_lock lock{mutex};
  381. if (!supported_features.irs) {
  382. return DriverResult::NotSupported;
  383. }
  384. if (ring_connected) {
  385. is_ring_disabled_by_irs = true;
  386. }
  387. motion_enabled = false;
  388. hidbus_enabled = false;
  389. nfc_enabled = false;
  390. passive_enabled = false;
  391. irs_enabled = true;
  392. return SetPollingMode();
  393. }
  394. DriverResult JoyconDriver::SetNfcMode() {
  395. std::scoped_lock lock{mutex};
  396. if (!supported_features.nfc) {
  397. return DriverResult::NotSupported;
  398. }
  399. motion_enabled = true;
  400. hidbus_enabled = false;
  401. nfc_enabled = true;
  402. passive_enabled = false;
  403. irs_enabled = false;
  404. return SetPollingMode();
  405. }
  406. DriverResult JoyconDriver::SetRingConMode() {
  407. std::scoped_lock lock{mutex};
  408. if (!supported_features.hidbus) {
  409. return DriverResult::NotSupported;
  410. }
  411. motion_enabled = true;
  412. hidbus_enabled = true;
  413. nfc_enabled = false;
  414. passive_enabled = false;
  415. irs_enabled = false;
  416. const auto result = SetPollingMode();
  417. if (!ring_connected) {
  418. return DriverResult::NoDeviceDetected;
  419. }
  420. return result;
  421. }
  422. bool JoyconDriver::IsConnected() const {
  423. std::scoped_lock lock{mutex};
  424. return is_connected.load();
  425. }
  426. bool JoyconDriver::IsVibrationEnabled() const {
  427. std::scoped_lock lock{mutex};
  428. return vibration_enabled;
  429. }
  430. FirmwareVersion JoyconDriver::GetDeviceVersion() const {
  431. std::scoped_lock lock{mutex};
  432. return version;
  433. }
  434. Color JoyconDriver::GetDeviceColor() const {
  435. std::scoped_lock lock{mutex};
  436. return color;
  437. }
  438. std::size_t JoyconDriver::GetDevicePort() const {
  439. std::scoped_lock lock{mutex};
  440. return port;
  441. }
  442. ControllerType JoyconDriver::GetDeviceType() const {
  443. std::scoped_lock lock{mutex};
  444. return device_type;
  445. }
  446. ControllerType JoyconDriver::GetHandleDeviceType() const {
  447. std::scoped_lock lock{mutex};
  448. return handle_device_type;
  449. }
  450. SerialNumber JoyconDriver::GetSerialNumber() const {
  451. std::scoped_lock lock{mutex};
  452. return serial_number;
  453. }
  454. SerialNumber JoyconDriver::GetHandleSerialNumber() const {
  455. std::scoped_lock lock{mutex};
  456. return handle_serial_number;
  457. }
  458. void JoyconDriver::SetCallbacks(const JoyconCallbacks& callbacks) {
  459. joycon_poller->SetCallbacks(callbacks);
  460. }
  461. DriverResult JoyconDriver::GetDeviceType(SDL_hid_device_info* device_info,
  462. ControllerType& controller_type) {
  463. static constexpr std::array<std::pair<u32, ControllerType>, 6> supported_devices{
  464. std::pair<u32, ControllerType>{0x2006, ControllerType::Left},
  465. {0x2007, ControllerType::Right},
  466. {0x2009, ControllerType::Pro},
  467. };
  468. constexpr static u16 nintendo_vendor_id = 0x057e;
  469. controller_type = ControllerType::None;
  470. if (device_info->vendor_id != nintendo_vendor_id) {
  471. return DriverResult::UnsupportedControllerType;
  472. }
  473. for (const auto& [product_id, type] : supported_devices) {
  474. if (device_info->product_id == static_cast<u16>(product_id)) {
  475. controller_type = type;
  476. return Joycon::DriverResult::Success;
  477. }
  478. }
  479. return Joycon::DriverResult::UnsupportedControllerType;
  480. }
  481. DriverResult JoyconDriver::GetSerialNumber(SDL_hid_device_info* device_info,
  482. SerialNumber& serial_number) {
  483. if (device_info->serial_number == nullptr) {
  484. return DriverResult::Unknown;
  485. }
  486. std::memcpy(&serial_number, device_info->serial_number, 15);
  487. return Joycon::DriverResult::Success;
  488. }
  489. } // namespace InputCommon::Joycon