SDL_hidapi_switch.c 123 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. /* This driver supports the Nintendo Switch Pro controller.
  19. Code and logic contributed by Valve Corporation under the SDL zlib license.
  20. */
  21. #include "SDL_internal.h"
  22. #ifdef SDL_JOYSTICK_HIDAPI
  23. #include "../../SDL_hints_c.h"
  24. #include "../SDL_sysjoystick.h"
  25. #include "SDL_hidapijoystick_c.h"
  26. #include "SDL_hidapi_rumble.h"
  27. #include "SDL_hidapi_nintendo.h"
  28. #ifdef SDL_JOYSTICK_HIDAPI_SWITCH
  29. // Define this if you want to log all packets from the controller
  30. // #define DEBUG_SWITCH_PROTOCOL
  31. // Define this to get log output for rumble logic
  32. // #define DEBUG_RUMBLE
  33. /* The initialization sequence doesn't appear to work correctly on Windows unless
  34. the reads and writes are on the same thread.
  35. ... and now I can't reproduce this, so I'm leaving it in, but disabled for now.
  36. */
  37. // #define SWITCH_SYNCHRONOUS_WRITES
  38. /* How often you can write rumble commands to the controller.
  39. If you send commands more frequently than this, you can turn off the controller
  40. in Bluetooth mode, or the motors can miss the command in USB mode.
  41. */
  42. #define RUMBLE_WRITE_FREQUENCY_MS 30
  43. // How often you have to refresh a long duration rumble to keep the motors running
  44. #define RUMBLE_REFRESH_FREQUENCY_MS 50
  45. #define SWITCH_GYRO_SCALE 14.2842f
  46. #define SWITCH_ACCEL_SCALE 4096.f
  47. #define SWITCH_GYRO_SCALE_MULT 936.0f
  48. #define SWITCH_ACCEL_SCALE_MULT 4.0f
  49. enum
  50. {
  51. SDL_GAMEPAD_BUTTON_SWITCH_SHARE = 11,
  52. SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1,
  53. SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1,
  54. SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2,
  55. SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2,
  56. SDL_GAMEPAD_NUM_SWITCH_BUTTONS,
  57. };
  58. typedef enum
  59. {
  60. k_eSwitchInputReportIDs_SubcommandReply = 0x21,
  61. k_eSwitchInputReportIDs_FullControllerState = 0x30,
  62. k_eSwitchInputReportIDs_FullControllerAndMcuState = 0x31,
  63. k_eSwitchInputReportIDs_SimpleControllerState = 0x3F,
  64. k_eSwitchInputReportIDs_CommandAck = 0x81,
  65. } ESwitchInputReportIDs;
  66. typedef enum
  67. {
  68. k_eSwitchOutputReportIDs_RumbleAndSubcommand = 0x01,
  69. k_eSwitchOutputReportIDs_Rumble = 0x10,
  70. k_eSwitchOutputReportIDs_Proprietary = 0x80,
  71. } ESwitchOutputReportIDs;
  72. typedef enum
  73. {
  74. k_eSwitchSubcommandIDs_BluetoothManualPair = 0x01,
  75. k_eSwitchSubcommandIDs_RequestDeviceInfo = 0x02,
  76. k_eSwitchSubcommandIDs_SetInputReportMode = 0x03,
  77. k_eSwitchSubcommandIDs_SetHCIState = 0x06,
  78. k_eSwitchSubcommandIDs_SPIFlashRead = 0x10,
  79. k_eSwitchSubcommandIDs_SetPlayerLights = 0x30,
  80. k_eSwitchSubcommandIDs_SetHomeLight = 0x38,
  81. k_eSwitchSubcommandIDs_EnableIMU = 0x40,
  82. k_eSwitchSubcommandIDs_SetIMUSensitivity = 0x41,
  83. k_eSwitchSubcommandIDs_EnableVibration = 0x48,
  84. } ESwitchSubcommandIDs;
  85. typedef enum
  86. {
  87. k_eSwitchProprietaryCommandIDs_Status = 0x01,
  88. k_eSwitchProprietaryCommandIDs_Handshake = 0x02,
  89. k_eSwitchProprietaryCommandIDs_HighSpeed = 0x03,
  90. k_eSwitchProprietaryCommandIDs_ForceUSB = 0x04,
  91. k_eSwitchProprietaryCommandIDs_ClearUSB = 0x05,
  92. k_eSwitchProprietaryCommandIDs_ResetMCU = 0x06,
  93. } ESwitchProprietaryCommandIDs;
  94. #define k_unSwitchOutputPacketDataLength 49
  95. #define k_unSwitchMaxOutputPacketLength 64
  96. #define k_unSwitchBluetoothPacketLength k_unSwitchOutputPacketDataLength
  97. #define k_unSwitchUSBPacketLength k_unSwitchMaxOutputPacketLength
  98. #define k_unSPIStickFactoryCalibrationStartOffset 0x603D
  99. #define k_unSPIStickFactoryCalibrationEndOffset 0x604E
  100. #define k_unSPIStickFactoryCalibrationLength (k_unSPIStickFactoryCalibrationEndOffset - k_unSPIStickFactoryCalibrationStartOffset + 1)
  101. #define k_unSPIStickUserCalibrationStartOffset 0x8010
  102. #define k_unSPIStickUserCalibrationEndOffset 0x8025
  103. #define k_unSPIStickUserCalibrationLength (k_unSPIStickUserCalibrationEndOffset - k_unSPIStickUserCalibrationStartOffset + 1)
  104. #define k_unSPIIMUScaleStartOffset 0x6020
  105. #define k_unSPIIMUScaleEndOffset 0x6037
  106. #define k_unSPIIMUScaleLength (k_unSPIIMUScaleEndOffset - k_unSPIIMUScaleStartOffset + 1)
  107. #define k_unSPIIMUUserScaleStartOffset 0x8026
  108. #define k_unSPIIMUUserScaleEndOffset 0x8039
  109. #define k_unSPIIMUUserScaleLength (k_unSPIIMUUserScaleEndOffset - k_unSPIIMUUserScaleStartOffset + 1)
  110. #pragma pack(1)
  111. typedef struct
  112. {
  113. Uint8 rgucButtons[2];
  114. Uint8 ucStickHat;
  115. Uint8 rgucJoystickLeft[2];
  116. Uint8 rgucJoystickRight[2];
  117. } SwitchInputOnlyControllerStatePacket_t;
  118. typedef struct
  119. {
  120. Uint8 rgucButtons[2];
  121. Uint8 ucStickHat;
  122. Sint16 sJoystickLeft[2];
  123. Sint16 sJoystickRight[2];
  124. } SwitchSimpleStatePacket_t;
  125. typedef struct
  126. {
  127. Uint8 ucCounter;
  128. Uint8 ucBatteryAndConnection;
  129. Uint8 rgucButtons[3];
  130. Uint8 rgucJoystickLeft[3];
  131. Uint8 rgucJoystickRight[3];
  132. Uint8 ucVibrationCode;
  133. } SwitchControllerStatePacket_t;
  134. typedef struct
  135. {
  136. SwitchControllerStatePacket_t controllerState;
  137. struct
  138. {
  139. Sint16 sAccelX;
  140. Sint16 sAccelY;
  141. Sint16 sAccelZ;
  142. Sint16 sGyroX;
  143. Sint16 sGyroY;
  144. Sint16 sGyroZ;
  145. } imuState[3];
  146. } SwitchStatePacket_t;
  147. typedef struct
  148. {
  149. Uint32 unAddress;
  150. Uint8 ucLength;
  151. } SwitchSPIOpData_t;
  152. typedef struct
  153. {
  154. SwitchControllerStatePacket_t m_controllerState;
  155. Uint8 ucSubcommandAck;
  156. Uint8 ucSubcommandID;
  157. #define k_unSubcommandDataBytes 35
  158. union
  159. {
  160. Uint8 rgucSubcommandData[k_unSubcommandDataBytes];
  161. struct
  162. {
  163. SwitchSPIOpData_t opData;
  164. Uint8 rgucReadData[k_unSubcommandDataBytes - sizeof(SwitchSPIOpData_t)];
  165. } spiReadData;
  166. struct
  167. {
  168. Uint8 rgucFirmwareVersion[2];
  169. Uint8 ucDeviceType;
  170. Uint8 ucFiller1;
  171. Uint8 rgucMACAddress[6];
  172. Uint8 ucFiller2;
  173. Uint8 ucColorLocation;
  174. } deviceInfo;
  175. struct
  176. {
  177. SwitchSPIOpData_t opData;
  178. Uint8 rgucLeftCalibration[9];
  179. Uint8 rgucRightCalibration[9];
  180. } stickFactoryCalibration;
  181. struct
  182. {
  183. SwitchSPIOpData_t opData;
  184. Uint8 rgucLeftMagic[2];
  185. Uint8 rgucLeftCalibration[9];
  186. Uint8 rgucRightMagic[2];
  187. Uint8 rgucRightCalibration[9];
  188. } stickUserCalibration;
  189. };
  190. } SwitchSubcommandInputPacket_t;
  191. typedef struct
  192. {
  193. Uint8 ucPacketType;
  194. Uint8 ucCommandID;
  195. Uint8 ucFiller;
  196. Uint8 ucDeviceType;
  197. Uint8 rgucMACAddress[6];
  198. } SwitchProprietaryStatusPacket_t;
  199. typedef struct
  200. {
  201. Uint8 rgucData[4];
  202. } SwitchRumbleData_t;
  203. typedef struct
  204. {
  205. Uint8 ucPacketType;
  206. Uint8 ucPacketNumber;
  207. SwitchRumbleData_t rumbleData[2];
  208. } SwitchCommonOutputPacket_t;
  209. typedef struct
  210. {
  211. SwitchCommonOutputPacket_t commonData;
  212. Uint8 ucSubcommandID;
  213. Uint8 rgucSubcommandData[k_unSwitchOutputPacketDataLength - sizeof(SwitchCommonOutputPacket_t) - 1];
  214. } SwitchSubcommandOutputPacket_t;
  215. typedef struct
  216. {
  217. Uint8 ucPacketType;
  218. Uint8 ucProprietaryID;
  219. Uint8 rgucProprietaryData[k_unSwitchOutputPacketDataLength - 1 - 1];
  220. } SwitchProprietaryOutputPacket_t;
  221. #pragma pack()
  222. /* Enhanced report hint mode:
  223. * "0": enhanced features are never used
  224. * "1": enhanced features are always used
  225. * "auto": enhanced features are advertised to the application, but SDL doesn't touch the controller state unless the application explicitly requests it.
  226. */
  227. typedef enum
  228. {
  229. SWITCH_ENHANCED_REPORT_HINT_OFF,
  230. SWITCH_ENHANCED_REPORT_HINT_ON,
  231. SWITCH_ENHANCED_REPORT_HINT_AUTO
  232. } HIDAPI_Switch_EnhancedReportHint;
  233. typedef struct
  234. {
  235. SDL_HIDAPI_Device *device;
  236. SDL_Joystick *joystick;
  237. bool m_bInputOnly;
  238. bool m_bUseButtonLabels;
  239. bool m_bPlayerLights;
  240. int m_nPlayerIndex;
  241. bool m_bSyncWrite;
  242. int m_nMaxWriteAttempts;
  243. ESwitchDeviceInfoControllerType m_eControllerType;
  244. Uint8 m_nInitialInputMode;
  245. Uint8 m_nCurrentInputMode;
  246. Uint8 m_rgucMACAddress[6];
  247. Uint8 m_nCommandNumber;
  248. HIDAPI_Switch_EnhancedReportHint m_eEnhancedReportHint;
  249. bool m_bEnhancedMode;
  250. bool m_bEnhancedModeAvailable;
  251. SwitchCommonOutputPacket_t m_RumblePacket;
  252. Uint8 m_rgucReadBuffer[k_unSwitchMaxOutputPacketLength];
  253. bool m_bRumbleActive;
  254. Uint64 m_ulRumbleSent;
  255. bool m_bRumblePending;
  256. bool m_bRumbleZeroPending;
  257. Uint32 m_unRumblePending;
  258. bool m_bSensorsSupported;
  259. bool m_bReportSensors;
  260. bool m_bHasSensorData;
  261. Uint64 m_ulLastInput;
  262. Uint64 m_ulLastIMUReset;
  263. Uint64 m_ulIMUSampleTimestampNS;
  264. Uint32 m_unIMUSamples;
  265. Uint64 m_ulIMUUpdateIntervalNS;
  266. Uint64 m_ulTimestampNS;
  267. bool m_bVerticalMode;
  268. SwitchInputOnlyControllerStatePacket_t m_lastInputOnlyState;
  269. SwitchSimpleStatePacket_t m_lastSimpleState;
  270. SwitchStatePacket_t m_lastFullState;
  271. struct StickCalibrationData
  272. {
  273. struct
  274. {
  275. Sint16 sCenter;
  276. Sint16 sMin;
  277. Sint16 sMax;
  278. } axis[2];
  279. } m_StickCalData[2];
  280. struct StickExtents
  281. {
  282. struct
  283. {
  284. Sint16 sMin;
  285. Sint16 sMax;
  286. } axis[2];
  287. } m_StickExtents[2], m_SimpleStickExtents[2];
  288. struct IMUScaleData
  289. {
  290. float fAccelScaleX;
  291. float fAccelScaleY;
  292. float fAccelScaleZ;
  293. float fGyroScaleX;
  294. float fGyroScaleY;
  295. float fGyroScaleZ;
  296. } m_IMUScaleData;
  297. } SDL_DriverSwitch_Context;
  298. static int ReadInput(SDL_DriverSwitch_Context *ctx)
  299. {
  300. int result;
  301. // Make sure we don't try to read at the same time a write is happening
  302. if (SDL_GetAtomicInt(&ctx->device->rumble_pending) > 0) {
  303. return 0;
  304. }
  305. result = SDL_hid_read_timeout(ctx->device->dev, ctx->m_rgucReadBuffer, sizeof(ctx->m_rgucReadBuffer), 0);
  306. // See if we can guess the initial input mode
  307. if (result > 0 && !ctx->m_bInputOnly && !ctx->m_nInitialInputMode) {
  308. switch (ctx->m_rgucReadBuffer[0]) {
  309. case k_eSwitchInputReportIDs_FullControllerState:
  310. case k_eSwitchInputReportIDs_FullControllerAndMcuState:
  311. case k_eSwitchInputReportIDs_SimpleControllerState:
  312. ctx->m_nInitialInputMode = ctx->m_rgucReadBuffer[0];
  313. break;
  314. default:
  315. break;
  316. }
  317. }
  318. return result;
  319. }
  320. static int WriteOutput(SDL_DriverSwitch_Context *ctx, const Uint8 *data, int size)
  321. {
  322. #ifdef SWITCH_SYNCHRONOUS_WRITES
  323. return SDL_hid_write(ctx->device->dev, data, size);
  324. #else
  325. // Use the rumble thread for general asynchronous writes
  326. if (!SDL_HIDAPI_LockRumble()) {
  327. return -1;
  328. }
  329. return SDL_HIDAPI_SendRumbleAndUnlock(ctx->device, data, size);
  330. #endif // SWITCH_SYNCHRONOUS_WRITES
  331. }
  332. static SwitchSubcommandInputPacket_t *ReadSubcommandReply(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs expectedID)
  333. {
  334. // Average response time for messages is ~30ms
  335. Uint64 endTicks = SDL_GetTicks() + 100;
  336. int nRead = 0;
  337. while ((nRead = ReadInput(ctx)) != -1) {
  338. if (nRead > 0) {
  339. if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_SubcommandReply) {
  340. SwitchSubcommandInputPacket_t *reply = (SwitchSubcommandInputPacket_t *)&ctx->m_rgucReadBuffer[1];
  341. if (reply->ucSubcommandID == expectedID && (reply->ucSubcommandAck & 0x80)) {
  342. return reply;
  343. }
  344. }
  345. } else {
  346. SDL_Delay(1);
  347. }
  348. if (SDL_GetTicks() >= endTicks) {
  349. break;
  350. }
  351. }
  352. return NULL;
  353. }
  354. static bool ReadProprietaryReply(SDL_DriverSwitch_Context *ctx, ESwitchProprietaryCommandIDs expectedID)
  355. {
  356. // Average response time for messages is ~30ms
  357. Uint64 endTicks = SDL_GetTicks() + 100;
  358. int nRead = 0;
  359. while ((nRead = ReadInput(ctx)) != -1) {
  360. if (nRead > 0) {
  361. if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_CommandAck && ctx->m_rgucReadBuffer[1] == expectedID) {
  362. return true;
  363. }
  364. } else {
  365. SDL_Delay(1);
  366. }
  367. if (SDL_GetTicks() >= endTicks) {
  368. break;
  369. }
  370. }
  371. return false;
  372. }
  373. static void ConstructSubcommand(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs ucCommandID, const Uint8 *pBuf, Uint8 ucLen, SwitchSubcommandOutputPacket_t *outPacket)
  374. {
  375. SDL_memset(outPacket, 0, sizeof(*outPacket));
  376. outPacket->commonData.ucPacketType = k_eSwitchOutputReportIDs_RumbleAndSubcommand;
  377. outPacket->commonData.ucPacketNumber = ctx->m_nCommandNumber;
  378. SDL_memcpy(outPacket->commonData.rumbleData, ctx->m_RumblePacket.rumbleData, sizeof(ctx->m_RumblePacket.rumbleData));
  379. outPacket->ucSubcommandID = ucCommandID;
  380. if (pBuf) {
  381. SDL_memcpy(outPacket->rgucSubcommandData, pBuf, ucLen);
  382. }
  383. ctx->m_nCommandNumber = (ctx->m_nCommandNumber + 1) & 0xF;
  384. }
  385. static bool WritePacket(SDL_DriverSwitch_Context *ctx, void *pBuf, Uint8 ucLen)
  386. {
  387. Uint8 rgucBuf[k_unSwitchMaxOutputPacketLength];
  388. const size_t unWriteSize = ctx->device->is_bluetooth ? k_unSwitchBluetoothPacketLength : k_unSwitchUSBPacketLength;
  389. if (ucLen > k_unSwitchOutputPacketDataLength) {
  390. return false;
  391. }
  392. if (ucLen < unWriteSize) {
  393. SDL_memcpy(rgucBuf, pBuf, ucLen);
  394. SDL_memset(rgucBuf + ucLen, 0, unWriteSize - ucLen);
  395. pBuf = rgucBuf;
  396. ucLen = (Uint8)unWriteSize;
  397. }
  398. if (ctx->m_bSyncWrite) {
  399. return SDL_hid_write(ctx->device->dev, (Uint8 *)pBuf, ucLen) >= 0;
  400. } else {
  401. return WriteOutput(ctx, (Uint8 *)pBuf, ucLen) >= 0;
  402. }
  403. }
  404. static bool WriteSubcommand(SDL_DriverSwitch_Context *ctx, ESwitchSubcommandIDs ucCommandID, const Uint8 *pBuf, Uint8 ucLen, SwitchSubcommandInputPacket_t **ppReply)
  405. {
  406. SwitchSubcommandInputPacket_t *reply = NULL;
  407. int nTries;
  408. for (nTries = 1; !reply && nTries <= ctx->m_nMaxWriteAttempts; ++nTries) {
  409. SwitchSubcommandOutputPacket_t commandPacket;
  410. ConstructSubcommand(ctx, ucCommandID, pBuf, ucLen, &commandPacket);
  411. if (!WritePacket(ctx, &commandPacket, sizeof(commandPacket))) {
  412. continue;
  413. }
  414. reply = ReadSubcommandReply(ctx, ucCommandID);
  415. }
  416. if (ppReply) {
  417. *ppReply = reply;
  418. }
  419. return reply != NULL;
  420. }
  421. static bool WriteProprietary(SDL_DriverSwitch_Context *ctx, ESwitchProprietaryCommandIDs ucCommand, Uint8 *pBuf, Uint8 ucLen, bool waitForReply)
  422. {
  423. int nTries;
  424. for (nTries = 1; nTries <= ctx->m_nMaxWriteAttempts; ++nTries) {
  425. SwitchProprietaryOutputPacket_t packet;
  426. if ((!pBuf && ucLen > 0) || ucLen > sizeof(packet.rgucProprietaryData)) {
  427. return false;
  428. }
  429. SDL_zero(packet);
  430. packet.ucPacketType = k_eSwitchOutputReportIDs_Proprietary;
  431. packet.ucProprietaryID = ucCommand;
  432. if (pBuf) {
  433. SDL_memcpy(packet.rgucProprietaryData, pBuf, ucLen);
  434. }
  435. if (!WritePacket(ctx, &packet, sizeof(packet))) {
  436. continue;
  437. }
  438. if (!waitForReply || ReadProprietaryReply(ctx, ucCommand)) {
  439. // SDL_Log("Succeeded%s after %d tries", ctx->m_bSyncWrite ? " (sync)" : "", nTries);
  440. return true;
  441. }
  442. }
  443. // SDL_Log("Failed%s after %d tries", ctx->m_bSyncWrite ? " (sync)" : "", nTries);
  444. return false;
  445. }
  446. static Uint8 EncodeRumbleHighAmplitude(Uint16 amplitude)
  447. {
  448. /* More information about these values can be found here:
  449. * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
  450. */
  451. Uint16 hfa[101][2] = { { 0, 0x0 }, { 514, 0x2 }, { 775, 0x4 }, { 921, 0x6 }, { 1096, 0x8 }, { 1303, 0x0a }, { 1550, 0x0c }, { 1843, 0x0e }, { 2192, 0x10 }, { 2606, 0x12 }, { 3100, 0x14 }, { 3686, 0x16 }, { 4383, 0x18 }, { 5213, 0x1a }, { 6199, 0x1c }, { 7372, 0x1e }, { 7698, 0x20 }, { 8039, 0x22 }, { 8395, 0x24 }, { 8767, 0x26 }, { 9155, 0x28 }, { 9560, 0x2a }, { 9984, 0x2c }, { 10426, 0x2e }, { 10887, 0x30 }, { 11369, 0x32 }, { 11873, 0x34 }, { 12398, 0x36 }, { 12947, 0x38 }, { 13520, 0x3a }, { 14119, 0x3c }, { 14744, 0x3e }, { 15067, 0x40 }, { 15397, 0x42 }, { 15734, 0x44 }, { 16079, 0x46 }, { 16431, 0x48 }, { 16790, 0x4a }, { 17158, 0x4c }, { 17534, 0x4e }, { 17918, 0x50 }, { 18310, 0x52 }, { 18711, 0x54 }, { 19121, 0x56 }, { 19540, 0x58 }, { 19967, 0x5a }, { 20405, 0x5c }, { 20851, 0x5e }, { 21308, 0x60 }, { 21775, 0x62 }, { 22251, 0x64 }, { 22739, 0x66 }, { 23236, 0x68 }, { 23745, 0x6a }, { 24265, 0x6c }, { 24797, 0x6e }, { 25340, 0x70 }, { 25894, 0x72 }, { 26462, 0x74 }, { 27041, 0x76 }, { 27633, 0x78 }, { 28238, 0x7a }, { 28856, 0x7c }, { 29488, 0x7e }, { 30134, 0x80 }, { 30794, 0x82 }, { 31468, 0x84 }, { 32157, 0x86 }, { 32861, 0x88 }, { 33581, 0x8a }, { 34316, 0x8c }, { 35068, 0x8e }, { 35836, 0x90 }, { 36620, 0x92 }, { 37422, 0x94 }, { 38242, 0x96 }, { 39079, 0x98 }, { 39935, 0x9a }, { 40809, 0x9c }, { 41703, 0x9e }, { 42616, 0xa0 }, { 43549, 0xa2 }, { 44503, 0xa4 }, { 45477, 0xa6 }, { 46473, 0xa8 }, { 47491, 0xaa }, { 48531, 0xac }, { 49593, 0xae }, { 50679, 0xb0 }, { 51789, 0xb2 }, { 52923, 0xb4 }, { 54082, 0xb6 }, { 55266, 0xb8 }, { 56476, 0xba }, { 57713, 0xbc }, { 58977, 0xbe }, { 60268, 0xc0 }, { 61588, 0xc2 }, { 62936, 0xc4 }, { 64315, 0xc6 }, { 65535, 0xc8 } };
  452. int index = 0;
  453. for (; index < 101; index++) {
  454. if (amplitude <= hfa[index][0]) {
  455. return (Uint8)hfa[index][1];
  456. }
  457. }
  458. return (Uint8)hfa[100][1];
  459. }
  460. static Uint16 EncodeRumbleLowAmplitude(Uint16 amplitude)
  461. {
  462. /* More information about these values can be found here:
  463. * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
  464. */
  465. Uint16 lfa[101][2] = { { 0, 0x0040 }, { 514, 0x8040 }, { 775, 0x0041 }, { 921, 0x8041 }, { 1096, 0x0042 }, { 1303, 0x8042 }, { 1550, 0x0043 }, { 1843, 0x8043 }, { 2192, 0x0044 }, { 2606, 0x8044 }, { 3100, 0x0045 }, { 3686, 0x8045 }, { 4383, 0x0046 }, { 5213, 0x8046 }, { 6199, 0x0047 }, { 7372, 0x8047 }, { 7698, 0x0048 }, { 8039, 0x8048 }, { 8395, 0x0049 }, { 8767, 0x8049 }, { 9155, 0x004a }, { 9560, 0x804a }, { 9984, 0x004b }, { 10426, 0x804b }, { 10887, 0x004c }, { 11369, 0x804c }, { 11873, 0x004d }, { 12398, 0x804d }, { 12947, 0x004e }, { 13520, 0x804e }, { 14119, 0x004f }, { 14744, 0x804f }, { 15067, 0x0050 }, { 15397, 0x8050 }, { 15734, 0x0051 }, { 16079, 0x8051 }, { 16431, 0x0052 }, { 16790, 0x8052 }, { 17158, 0x0053 }, { 17534, 0x8053 }, { 17918, 0x0054 }, { 18310, 0x8054 }, { 18711, 0x0055 }, { 19121, 0x8055 }, { 19540, 0x0056 }, { 19967, 0x8056 }, { 20405, 0x0057 }, { 20851, 0x8057 }, { 21308, 0x0058 }, { 21775, 0x8058 }, { 22251, 0x0059 }, { 22739, 0x8059 }, { 23236, 0x005a }, { 23745, 0x805a }, { 24265, 0x005b }, { 24797, 0x805b }, { 25340, 0x005c }, { 25894, 0x805c }, { 26462, 0x005d }, { 27041, 0x805d }, { 27633, 0x005e }, { 28238, 0x805e }, { 28856, 0x005f }, { 29488, 0x805f }, { 30134, 0x0060 }, { 30794, 0x8060 }, { 31468, 0x0061 }, { 32157, 0x8061 }, { 32861, 0x0062 }, { 33581, 0x8062 }, { 34316, 0x0063 }, { 35068, 0x8063 }, { 35836, 0x0064 }, { 36620, 0x8064 }, { 37422, 0x0065 }, { 38242, 0x8065 }, { 39079, 0x0066 }, { 39935, 0x8066 }, { 40809, 0x0067 }, { 41703, 0x8067 }, { 42616, 0x0068 }, { 43549, 0x8068 }, { 44503, 0x0069 }, { 45477, 0x8069 }, { 46473, 0x006a }, { 47491, 0x806a }, { 48531, 0x006b }, { 49593, 0x806b }, { 50679, 0x006c }, { 51789, 0x806c }, { 52923, 0x006d }, { 54082, 0x806d }, { 55266, 0x006e }, { 56476, 0x806e }, { 57713, 0x006f }, { 58977, 0x806f }, { 60268, 0x0070 }, { 61588, 0x8070 }, { 62936, 0x0071 }, { 64315, 0x8071 }, { 65535, 0x0072 } };
  466. int index = 0;
  467. for (; index < 101; index++) {
  468. if (amplitude <= lfa[index][0]) {
  469. return lfa[index][1];
  470. }
  471. }
  472. return lfa[100][1];
  473. }
  474. static void SetNeutralRumble(SwitchRumbleData_t *pRumble)
  475. {
  476. pRumble->rgucData[0] = 0x00;
  477. pRumble->rgucData[1] = 0x01;
  478. pRumble->rgucData[2] = 0x40;
  479. pRumble->rgucData[3] = 0x40;
  480. }
  481. static void EncodeRumble(SwitchRumbleData_t *pRumble, Uint16 usHighFreq, Uint8 ucHighFreqAmp, Uint8 ucLowFreq, Uint16 usLowFreqAmp)
  482. {
  483. if (ucHighFreqAmp > 0 || usLowFreqAmp > 0) {
  484. // High-band frequency and low-band amplitude are actually nine-bits each so they
  485. // take a bit from the high-band amplitude and low-band frequency bytes respectively
  486. pRumble->rgucData[0] = usHighFreq & 0xFF;
  487. pRumble->rgucData[1] = ucHighFreqAmp | ((usHighFreq >> 8) & 0x01);
  488. pRumble->rgucData[2] = ucLowFreq | ((usLowFreqAmp >> 8) & 0x80);
  489. pRumble->rgucData[3] = usLowFreqAmp & 0xFF;
  490. #ifdef DEBUG_RUMBLE
  491. SDL_Log("Freq: %.2X %.2X %.2X, Amp: %.2X %.2X %.2X",
  492. usHighFreq & 0xFF, ((usHighFreq >> 8) & 0x01), ucLowFreq,
  493. ucHighFreqAmp, ((usLowFreqAmp >> 8) & 0x80), usLowFreqAmp & 0xFF);
  494. #endif
  495. } else {
  496. SetNeutralRumble(pRumble);
  497. }
  498. }
  499. static bool WriteRumble(SDL_DriverSwitch_Context *ctx)
  500. {
  501. /* Write into m_RumblePacket rather than a temporary buffer to allow the current rumble state
  502. * to be retained for subsequent rumble or subcommand packets sent to the controller
  503. */
  504. ctx->m_RumblePacket.ucPacketType = k_eSwitchOutputReportIDs_Rumble;
  505. ctx->m_RumblePacket.ucPacketNumber = ctx->m_nCommandNumber;
  506. ctx->m_nCommandNumber = (ctx->m_nCommandNumber + 1) & 0xF;
  507. // Refresh the rumble state periodically
  508. ctx->m_ulRumbleSent = SDL_GetTicks();
  509. return WritePacket(ctx, (Uint8 *)&ctx->m_RumblePacket, sizeof(ctx->m_RumblePacket));
  510. }
  511. static ESwitchDeviceInfoControllerType CalculateControllerType(SDL_DriverSwitch_Context *ctx, ESwitchDeviceInfoControllerType eControllerType)
  512. {
  513. SDL_HIDAPI_Device *device = ctx->device;
  514. // The N64 controller reports as a Pro controller over USB
  515. if (eControllerType == k_eSwitchDeviceInfoControllerType_ProController &&
  516. device->product_id == USB_PRODUCT_NINTENDO_N64_CONTROLLER) {
  517. eControllerType = k_eSwitchDeviceInfoControllerType_N64;
  518. }
  519. if (eControllerType == k_eSwitchDeviceInfoControllerType_Unknown) {
  520. // This might be a Joy-Con that's missing from a charging grip slot
  521. if (device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) {
  522. if (device->interface_number == 1) {
  523. eControllerType = k_eSwitchDeviceInfoControllerType_JoyConLeft;
  524. } else {
  525. eControllerType = k_eSwitchDeviceInfoControllerType_JoyConRight;
  526. }
  527. }
  528. }
  529. return eControllerType;
  530. }
  531. static bool BReadDeviceInfo(SDL_DriverSwitch_Context *ctx)
  532. {
  533. SwitchSubcommandInputPacket_t *reply = NULL;
  534. if (ctx->device->is_bluetooth) {
  535. if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_RequestDeviceInfo, NULL, 0, &reply)) {
  536. // Byte 2: Controller ID (1=LJC, 2=RJC, 3=Pro)
  537. ctx->m_eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)reply->deviceInfo.ucDeviceType);
  538. // Bytes 4-9: MAC address (big-endian)
  539. SDL_memcpy(ctx->m_rgucMACAddress, reply->deviceInfo.rgucMACAddress, sizeof(ctx->m_rgucMACAddress));
  540. return true;
  541. }
  542. } else {
  543. if (WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Status, NULL, 0, true)) {
  544. SwitchProprietaryStatusPacket_t *status = (SwitchProprietaryStatusPacket_t *)&ctx->m_rgucReadBuffer[0];
  545. size_t i;
  546. ctx->m_eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)status->ucDeviceType);
  547. for (i = 0; i < sizeof(ctx->m_rgucMACAddress); ++i) {
  548. ctx->m_rgucMACAddress[i] = status->rgucMACAddress[sizeof(ctx->m_rgucMACAddress) - i - 1];
  549. }
  550. return true;
  551. }
  552. }
  553. return false;
  554. }
  555. static bool BTrySetupUSB(SDL_DriverSwitch_Context *ctx)
  556. {
  557. /* We have to send a connection handshake to the controller when communicating over USB
  558. * before we're able to send it other commands. Luckily this command is not supported
  559. * over Bluetooth, so we can use the controller's lack of response as a way to
  560. * determine if the connection is over USB or Bluetooth
  561. */
  562. if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Handshake, NULL, 0, true)) {
  563. return false;
  564. }
  565. if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_HighSpeed, NULL, 0, true)) {
  566. // The 8BitDo M30 and SF30 Pro don't respond to this command, but otherwise work correctly
  567. // return false;
  568. }
  569. if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Handshake, NULL, 0, true)) {
  570. // This fails on the right Joy-Con when plugged into the charging grip
  571. // return false;
  572. }
  573. if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, false)) {
  574. return false;
  575. }
  576. return true;
  577. }
  578. static bool SetVibrationEnabled(SDL_DriverSwitch_Context *ctx, Uint8 enabled)
  579. {
  580. return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_EnableVibration, &enabled, sizeof(enabled), NULL);
  581. }
  582. static bool SetInputMode(SDL_DriverSwitch_Context *ctx, Uint8 input_mode)
  583. {
  584. #ifdef FORCE_SIMPLE_REPORTS
  585. input_mode = k_eSwitchInputReportIDs_SimpleControllerState;
  586. #endif
  587. #ifdef FORCE_FULL_REPORTS
  588. input_mode = k_eSwitchInputReportIDs_FullControllerState;
  589. #endif
  590. if (input_mode == ctx->m_nCurrentInputMode) {
  591. return true;
  592. } else {
  593. ctx->m_nCurrentInputMode = input_mode;
  594. return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetInputReportMode, &input_mode, sizeof(input_mode), NULL);
  595. }
  596. }
  597. static bool SetHomeLED(SDL_DriverSwitch_Context *ctx, Uint8 brightness)
  598. {
  599. Uint8 ucLedIntensity = 0;
  600. Uint8 rgucBuffer[4];
  601. if (brightness > 0) {
  602. if (brightness < 65) {
  603. ucLedIntensity = (brightness + 5) / 10;
  604. } else {
  605. ucLedIntensity = (Uint8)SDL_ceilf(0xF * SDL_powf((float)brightness / 100.f, 2.13f));
  606. }
  607. }
  608. rgucBuffer[0] = (0x0 << 4) | 0x1; // 0 mini cycles (besides first), cycle duration 8ms
  609. rgucBuffer[1] = ((ucLedIntensity & 0xF) << 4) | 0x0; // LED start intensity (0x0-0xF), 0 cycles (LED stays on at start intensity after first cycle)
  610. rgucBuffer[2] = ((ucLedIntensity & 0xF) << 4) | 0x0; // First cycle LED intensity, 0x0 intensity for second cycle
  611. rgucBuffer[3] = (0x0 << 4) | 0x0; // 8ms fade transition to first cycle, 8ms first cycle LED duration
  612. return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetHomeLight, rgucBuffer, sizeof(rgucBuffer), NULL);
  613. }
  614. static void SDLCALL SDL_HomeLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  615. {
  616. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata;
  617. if (hint && *hint) {
  618. int value;
  619. if (SDL_strchr(hint, '.') != NULL) {
  620. value = (int)(100.0f * SDL_atof(hint));
  621. if (value > 255) {
  622. value = 255;
  623. }
  624. } else if (SDL_GetStringBoolean(hint, true)) {
  625. value = 100;
  626. } else {
  627. value = 0;
  628. }
  629. SetHomeLED(ctx, (Uint8)value);
  630. }
  631. }
  632. static void UpdateSlotLED(SDL_DriverSwitch_Context *ctx)
  633. {
  634. if (!ctx->m_bInputOnly) {
  635. Uint8 led_data = 0;
  636. if (ctx->m_bPlayerLights && ctx->m_nPlayerIndex >= 0) {
  637. led_data = (1 << (ctx->m_nPlayerIndex % 4));
  638. }
  639. WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SetPlayerLights, &led_data, sizeof(led_data), NULL);
  640. }
  641. }
  642. static void SDLCALL SDL_PlayerLEDHintChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  643. {
  644. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata;
  645. bool bPlayerLights = SDL_GetStringBoolean(hint, true);
  646. if (bPlayerLights != ctx->m_bPlayerLights) {
  647. ctx->m_bPlayerLights = bPlayerLights;
  648. UpdateSlotLED(ctx);
  649. HIDAPI_UpdateDeviceProperties(ctx->device);
  650. }
  651. }
  652. static void GetInitialInputMode(SDL_DriverSwitch_Context *ctx)
  653. {
  654. if (!ctx->m_nInitialInputMode) {
  655. // This will set the initial input mode if it can
  656. ReadInput(ctx);
  657. }
  658. }
  659. static Uint8 GetDefaultInputMode(SDL_DriverSwitch_Context *ctx)
  660. {
  661. Uint8 input_mode;
  662. // Determine the desired input mode
  663. if (ctx->m_nInitialInputMode) {
  664. input_mode = ctx->m_nInitialInputMode;
  665. } else {
  666. if (ctx->device->is_bluetooth) {
  667. input_mode = k_eSwitchInputReportIDs_SimpleControllerState;
  668. } else {
  669. input_mode = k_eSwitchInputReportIDs_FullControllerState;
  670. }
  671. }
  672. switch (ctx->m_eEnhancedReportHint) {
  673. case SWITCH_ENHANCED_REPORT_HINT_OFF:
  674. input_mode = k_eSwitchInputReportIDs_SimpleControllerState;
  675. break;
  676. case SWITCH_ENHANCED_REPORT_HINT_ON:
  677. if (input_mode == k_eSwitchInputReportIDs_SimpleControllerState) {
  678. input_mode = k_eSwitchInputReportIDs_FullControllerState;
  679. }
  680. break;
  681. case SWITCH_ENHANCED_REPORT_HINT_AUTO:
  682. /* Joy-Con controllers switch their thumbsticks into D-pad mode in simple mode,
  683. * so let's enable full controller state for them.
  684. */
  685. if (ctx->device->vendor_id == USB_VENDOR_NINTENDO &&
  686. (ctx->device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT ||
  687. ctx->device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT)) {
  688. input_mode = k_eSwitchInputReportIDs_FullControllerState;
  689. }
  690. break;
  691. }
  692. // Wired controllers break if they are put into simple controller state
  693. if (input_mode == k_eSwitchInputReportIDs_SimpleControllerState &&
  694. !ctx->device->is_bluetooth) {
  695. input_mode = k_eSwitchInputReportIDs_FullControllerState;
  696. }
  697. return input_mode;
  698. }
  699. static Uint8 GetSensorInputMode(SDL_DriverSwitch_Context *ctx)
  700. {
  701. Uint8 input_mode;
  702. // Determine the desired input mode
  703. if (!ctx->m_nInitialInputMode ||
  704. ctx->m_nInitialInputMode == k_eSwitchInputReportIDs_SimpleControllerState) {
  705. input_mode = k_eSwitchInputReportIDs_FullControllerState;
  706. } else {
  707. input_mode = ctx->m_nInitialInputMode;
  708. }
  709. return input_mode;
  710. }
  711. static void UpdateInputMode(SDL_DriverSwitch_Context *ctx)
  712. {
  713. Uint8 input_mode;
  714. if (ctx->m_bReportSensors) {
  715. input_mode = GetSensorInputMode(ctx);
  716. } else {
  717. input_mode = GetDefaultInputMode(ctx);
  718. }
  719. SetInputMode(ctx, input_mode);
  720. }
  721. static void SetEnhancedModeAvailable(SDL_DriverSwitch_Context *ctx)
  722. {
  723. if (ctx->m_bEnhancedModeAvailable) {
  724. return;
  725. }
  726. ctx->m_bEnhancedModeAvailable = true;
  727. if (ctx->m_bSensorsSupported) {
  728. // Use the right sensor in the combined Joy-Con pair
  729. if (!ctx->device->parent ||
  730. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  731. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO, 200.0f);
  732. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL, 200.0f);
  733. }
  734. if (ctx->device->parent &&
  735. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) {
  736. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO_L, 200.0f);
  737. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL_L, 200.0f);
  738. }
  739. if (ctx->device->parent &&
  740. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  741. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_GYRO_R, 200.0f);
  742. SDL_PrivateJoystickAddSensor(ctx->joystick, SDL_SENSOR_ACCEL_R, 200.0f);
  743. }
  744. }
  745. }
  746. static void SetEnhancedReportHint(SDL_DriverSwitch_Context *ctx, HIDAPI_Switch_EnhancedReportHint eEnhancedReportHint)
  747. {
  748. ctx->m_eEnhancedReportHint = eEnhancedReportHint;
  749. switch (eEnhancedReportHint) {
  750. case SWITCH_ENHANCED_REPORT_HINT_OFF:
  751. ctx->m_bEnhancedMode = false;
  752. break;
  753. case SWITCH_ENHANCED_REPORT_HINT_ON:
  754. SetEnhancedModeAvailable(ctx);
  755. ctx->m_bEnhancedMode = true;
  756. break;
  757. case SWITCH_ENHANCED_REPORT_HINT_AUTO:
  758. SetEnhancedModeAvailable(ctx);
  759. break;
  760. }
  761. UpdateInputMode(ctx);
  762. }
  763. static void UpdateEnhancedModeOnEnhancedReport(SDL_DriverSwitch_Context *ctx)
  764. {
  765. if (ctx->m_eEnhancedReportHint == SWITCH_ENHANCED_REPORT_HINT_AUTO) {
  766. SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_ON);
  767. }
  768. }
  769. static void UpdateEnhancedModeOnApplicationUsage(SDL_DriverSwitch_Context *ctx)
  770. {
  771. if (ctx->m_eEnhancedReportHint == SWITCH_ENHANCED_REPORT_HINT_AUTO) {
  772. SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_ON);
  773. }
  774. }
  775. static void SDLCALL SDL_EnhancedReportsChanged(void *userdata, const char *name, const char *oldValue, const char *hint)
  776. {
  777. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)userdata;
  778. if (hint && SDL_strcasecmp(hint, "auto") == 0) {
  779. SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_AUTO);
  780. } else if (SDL_GetStringBoolean(hint, true)) {
  781. SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_ON);
  782. } else {
  783. SetEnhancedReportHint(ctx, SWITCH_ENHANCED_REPORT_HINT_OFF);
  784. }
  785. }
  786. static bool SetIMUEnabled(SDL_DriverSwitch_Context *ctx, bool enabled)
  787. {
  788. Uint8 imu_data = enabled ? 1 : 0;
  789. return WriteSubcommand(ctx, k_eSwitchSubcommandIDs_EnableIMU, &imu_data, sizeof(imu_data), NULL);
  790. }
  791. static bool LoadStickCalibration(SDL_DriverSwitch_Context *ctx)
  792. {
  793. Uint8 *pLeftStickCal = NULL;
  794. Uint8 *pRightStickCal = NULL;
  795. size_t stick, axis;
  796. SwitchSubcommandInputPacket_t *user_reply = NULL;
  797. SwitchSubcommandInputPacket_t *factory_reply = NULL;
  798. SwitchSPIOpData_t readUserParams;
  799. SwitchSPIOpData_t readFactoryParams;
  800. Uint8 userParamsReadSuccessCount = 0;
  801. // Read User Calibration Info
  802. readUserParams.unAddress = k_unSPIStickUserCalibrationStartOffset;
  803. readUserParams.ucLength = k_unSPIStickUserCalibrationLength;
  804. // This isn't readable on all controllers, so ignore failure
  805. WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readUserParams, sizeof(readUserParams), &user_reply);
  806. // Read Factory Calibration Info
  807. readFactoryParams.unAddress = k_unSPIStickFactoryCalibrationStartOffset;
  808. readFactoryParams.ucLength = k_unSPIStickFactoryCalibrationLength;
  809. // Automatically select the user calibration if magic bytes are set
  810. if (user_reply && user_reply->stickUserCalibration.rgucLeftMagic[0] == 0xB2 && user_reply->stickUserCalibration.rgucLeftMagic[1] == 0xA1) {
  811. userParamsReadSuccessCount += 1;
  812. pLeftStickCal = user_reply->stickUserCalibration.rgucLeftCalibration;
  813. }
  814. if (user_reply && user_reply->stickUserCalibration.rgucRightMagic[0] == 0xB2 && user_reply->stickUserCalibration.rgucRightMagic[1] == 0xA1) {
  815. userParamsReadSuccessCount += 1;
  816. pRightStickCal = user_reply->stickUserCalibration.rgucRightCalibration;
  817. }
  818. // Only read the factory calibration info if we failed to receive the correct magic bytes
  819. if (userParamsReadSuccessCount < 2) {
  820. // Read Factory Calibration Info
  821. readFactoryParams.unAddress = k_unSPIStickFactoryCalibrationStartOffset;
  822. readFactoryParams.ucLength = k_unSPIStickFactoryCalibrationLength;
  823. const int MAX_ATTEMPTS = 3;
  824. for (int attempt = 0;; ++attempt) {
  825. if (!WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readFactoryParams, sizeof(readFactoryParams), &factory_reply)) {
  826. return false;
  827. }
  828. if (factory_reply->stickFactoryCalibration.opData.unAddress == k_unSPIStickFactoryCalibrationStartOffset) {
  829. // We successfully read the calibration data
  830. pLeftStickCal = factory_reply->stickFactoryCalibration.rgucLeftCalibration;
  831. pRightStickCal = factory_reply->stickFactoryCalibration.rgucRightCalibration;
  832. break;
  833. }
  834. if (attempt == MAX_ATTEMPTS) {
  835. return false;
  836. }
  837. }
  838. }
  839. // If we still don't have calibration data, return false
  840. if (pLeftStickCal == NULL || pRightStickCal == NULL)
  841. {
  842. return false;
  843. }
  844. /* Stick calibration values are 12-bits each and are packed by bit
  845. * For whatever reason the fields are in a different order for each stick
  846. * Left: X-Max, Y-Max, X-Center, Y-Center, X-Min, Y-Min
  847. * Right: X-Center, Y-Center, X-Min, Y-Min, X-Max, Y-Max
  848. */
  849. // Left stick
  850. ctx->m_StickCalData[0].axis[0].sMax = ((pLeftStickCal[1] << 8) & 0xF00) | pLeftStickCal[0]; // X Axis max above center
  851. ctx->m_StickCalData[0].axis[1].sMax = (pLeftStickCal[2] << 4) | (pLeftStickCal[1] >> 4); // Y Axis max above center
  852. ctx->m_StickCalData[0].axis[0].sCenter = ((pLeftStickCal[4] << 8) & 0xF00) | pLeftStickCal[3]; // X Axis center
  853. ctx->m_StickCalData[0].axis[1].sCenter = (pLeftStickCal[5] << 4) | (pLeftStickCal[4] >> 4); // Y Axis center
  854. ctx->m_StickCalData[0].axis[0].sMin = ((pLeftStickCal[7] << 8) & 0xF00) | pLeftStickCal[6]; // X Axis min below center
  855. ctx->m_StickCalData[0].axis[1].sMin = (pLeftStickCal[8] << 4) | (pLeftStickCal[7] >> 4); // Y Axis min below center
  856. // Right stick
  857. ctx->m_StickCalData[1].axis[0].sCenter = ((pRightStickCal[1] << 8) & 0xF00) | pRightStickCal[0]; // X Axis center
  858. ctx->m_StickCalData[1].axis[1].sCenter = (pRightStickCal[2] << 4) | (pRightStickCal[1] >> 4); // Y Axis center
  859. ctx->m_StickCalData[1].axis[0].sMin = ((pRightStickCal[4] << 8) & 0xF00) | pRightStickCal[3]; // X Axis min below center
  860. ctx->m_StickCalData[1].axis[1].sMin = (pRightStickCal[5] << 4) | (pRightStickCal[4] >> 4); // Y Axis min below center
  861. ctx->m_StickCalData[1].axis[0].sMax = ((pRightStickCal[7] << 8) & 0xF00) | pRightStickCal[6]; // X Axis max above center
  862. ctx->m_StickCalData[1].axis[1].sMax = (pRightStickCal[8] << 4) | (pRightStickCal[7] >> 4); // Y Axis max above center
  863. // Filter out any values that were uninitialized (0xFFF) in the SPI read
  864. for (stick = 0; stick < 2; ++stick) {
  865. for (axis = 0; axis < 2; ++axis) {
  866. if (ctx->m_StickCalData[stick].axis[axis].sCenter == 0xFFF) {
  867. ctx->m_StickCalData[stick].axis[axis].sCenter = 2048;
  868. }
  869. if (ctx->m_StickCalData[stick].axis[axis].sMax == 0xFFF) {
  870. ctx->m_StickCalData[stick].axis[axis].sMax = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sCenter * 0.7f);
  871. }
  872. if (ctx->m_StickCalData[stick].axis[axis].sMin == 0xFFF) {
  873. ctx->m_StickCalData[stick].axis[axis].sMin = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sCenter * 0.7f);
  874. }
  875. }
  876. }
  877. for (stick = 0; stick < 2; ++stick) {
  878. for (axis = 0; axis < 2; ++axis) {
  879. ctx->m_StickExtents[stick].axis[axis].sMin = -(Sint16)(ctx->m_StickCalData[stick].axis[axis].sMin * 0.7f);
  880. ctx->m_StickExtents[stick].axis[axis].sMax = (Sint16)(ctx->m_StickCalData[stick].axis[axis].sMax * 0.7f);
  881. }
  882. }
  883. for (stick = 0; stick < 2; ++stick) {
  884. for (axis = 0; axis < 2; ++axis) {
  885. ctx->m_SimpleStickExtents[stick].axis[axis].sMin = (Sint16)(SDL_MIN_SINT16 * 0.5f);
  886. ctx->m_SimpleStickExtents[stick].axis[axis].sMax = (Sint16)(SDL_MAX_SINT16 * 0.5f);
  887. }
  888. }
  889. return true;
  890. }
  891. static bool LoadIMUCalibration(SDL_DriverSwitch_Context *ctx)
  892. {
  893. SwitchSubcommandInputPacket_t *reply = NULL;
  894. // Read Calibration Info
  895. SwitchSPIOpData_t readParams;
  896. readParams.unAddress = k_unSPIIMUScaleStartOffset;
  897. readParams.ucLength = k_unSPIIMUScaleLength;
  898. if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readParams, sizeof(readParams), &reply)) {
  899. Uint8 *pIMUScale;
  900. Sint16 sAccelRawX, sAccelRawY, sAccelRawZ, sGyroRawX, sGyroRawY, sGyroRawZ;
  901. Sint16 sAccelSensCoeffX, sAccelSensCoeffY, sAccelSensCoeffZ;
  902. Sint16 sGyroSensCoeffX, sGyroSensCoeffY, sGyroSensCoeffZ;
  903. // IMU scale gives us multipliers for converting raw values to real world values
  904. pIMUScale = reply->spiReadData.rgucReadData;
  905. sAccelRawX = (pIMUScale[1] << 8) | pIMUScale[0];
  906. sAccelRawY = (pIMUScale[3] << 8) | pIMUScale[2];
  907. sAccelRawZ = (pIMUScale[5] << 8) | pIMUScale[4];
  908. sAccelSensCoeffX = (pIMUScale[7] << 8) | pIMUScale[6];
  909. sAccelSensCoeffY = (pIMUScale[9] << 8) | pIMUScale[8];
  910. sAccelSensCoeffZ = (pIMUScale[11] << 8) | pIMUScale[10];
  911. sGyroRawX = (pIMUScale[13] << 8) | pIMUScale[12];
  912. sGyroRawY = (pIMUScale[15] << 8) | pIMUScale[14];
  913. sGyroRawZ = (pIMUScale[17] << 8) | pIMUScale[16];
  914. sGyroSensCoeffX = (pIMUScale[19] << 8) | pIMUScale[18];
  915. sGyroSensCoeffY = (pIMUScale[21] << 8) | pIMUScale[20];
  916. sGyroSensCoeffZ = (pIMUScale[23] << 8) | pIMUScale[22];
  917. // Check for user calibration data. If it's present and set, it'll override the factory settings
  918. readParams.unAddress = k_unSPIIMUUserScaleStartOffset;
  919. readParams.ucLength = k_unSPIIMUUserScaleLength;
  920. if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_SPIFlashRead, (uint8_t *)&readParams, sizeof(readParams), &reply) && (pIMUScale[0] | pIMUScale[1] << 8) == 0xA1B2) {
  921. pIMUScale = reply->spiReadData.rgucReadData;
  922. sAccelRawX = (pIMUScale[3] << 8) | pIMUScale[2];
  923. sAccelRawY = (pIMUScale[5] << 8) | pIMUScale[4];
  924. sAccelRawZ = (pIMUScale[7] << 8) | pIMUScale[6];
  925. sGyroRawX = (pIMUScale[15] << 8) | pIMUScale[14];
  926. sGyroRawY = (pIMUScale[17] << 8) | pIMUScale[16];
  927. sGyroRawZ = (pIMUScale[19] << 8) | pIMUScale[18];
  928. }
  929. // Accelerometer scale
  930. ctx->m_IMUScaleData.fAccelScaleX = SWITCH_ACCEL_SCALE_MULT / ((float)sAccelSensCoeffX - (float)sAccelRawX) * SDL_STANDARD_GRAVITY;
  931. ctx->m_IMUScaleData.fAccelScaleY = SWITCH_ACCEL_SCALE_MULT / ((float)sAccelSensCoeffY - (float)sAccelRawY) * SDL_STANDARD_GRAVITY;
  932. ctx->m_IMUScaleData.fAccelScaleZ = SWITCH_ACCEL_SCALE_MULT / ((float)sAccelSensCoeffZ - (float)sAccelRawZ) * SDL_STANDARD_GRAVITY;
  933. // Gyro scale
  934. ctx->m_IMUScaleData.fGyroScaleX = SWITCH_GYRO_SCALE_MULT / ((float)sGyroSensCoeffX - (float)sGyroRawX) * SDL_PI_F / 180.0f;
  935. ctx->m_IMUScaleData.fGyroScaleY = SWITCH_GYRO_SCALE_MULT / ((float)sGyroSensCoeffY - (float)sGyroRawY) * SDL_PI_F / 180.0f;
  936. ctx->m_IMUScaleData.fGyroScaleZ = SWITCH_GYRO_SCALE_MULT / ((float)sGyroSensCoeffZ - (float)sGyroRawZ) * SDL_PI_F / 180.0f;
  937. } else {
  938. // Use default values
  939. const float accelScale = SDL_STANDARD_GRAVITY / SWITCH_ACCEL_SCALE;
  940. const float gyroScale = SDL_PI_F / 180.0f / SWITCH_GYRO_SCALE;
  941. ctx->m_IMUScaleData.fAccelScaleX = accelScale;
  942. ctx->m_IMUScaleData.fAccelScaleY = accelScale;
  943. ctx->m_IMUScaleData.fAccelScaleZ = accelScale;
  944. ctx->m_IMUScaleData.fGyroScaleX = gyroScale;
  945. ctx->m_IMUScaleData.fGyroScaleY = gyroScale;
  946. ctx->m_IMUScaleData.fGyroScaleZ = gyroScale;
  947. }
  948. return true;
  949. }
  950. static Sint16 ApplyStickCalibration(SDL_DriverSwitch_Context *ctx, int nStick, int nAxis, Sint16 sRawValue)
  951. {
  952. sRawValue -= ctx->m_StickCalData[nStick].axis[nAxis].sCenter;
  953. if (sRawValue >= 0) {
  954. if (sRawValue > ctx->m_StickExtents[nStick].axis[nAxis].sMax) {
  955. ctx->m_StickExtents[nStick].axis[nAxis].sMax = sRawValue;
  956. }
  957. return (Sint16)HIDAPI_RemapVal(sRawValue, 0, ctx->m_StickExtents[nStick].axis[nAxis].sMax, 0, SDL_MAX_SINT16);
  958. } else {
  959. if (sRawValue < ctx->m_StickExtents[nStick].axis[nAxis].sMin) {
  960. ctx->m_StickExtents[nStick].axis[nAxis].sMin = sRawValue;
  961. }
  962. return (Sint16)HIDAPI_RemapVal(sRawValue, ctx->m_StickExtents[nStick].axis[nAxis].sMin, 0, SDL_MIN_SINT16, 0);
  963. }
  964. }
  965. static Sint16 ApplySimpleStickCalibration(SDL_DriverSwitch_Context *ctx, int nStick, int nAxis, Sint16 sRawValue)
  966. {
  967. // 0x8000 is the neutral value for all joystick axes
  968. const Uint16 usJoystickCenter = 0x8000;
  969. sRawValue -= usJoystickCenter;
  970. if (sRawValue >= 0) {
  971. if (sRawValue > ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMax) {
  972. ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMax = sRawValue;
  973. }
  974. return (Sint16)HIDAPI_RemapVal(sRawValue, 0, ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMax, 0, SDL_MAX_SINT16);
  975. } else {
  976. if (sRawValue < ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMin) {
  977. ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMin = sRawValue;
  978. }
  979. return (Sint16)HIDAPI_RemapVal(sRawValue, ctx->m_SimpleStickExtents[nStick].axis[nAxis].sMin, 0, SDL_MIN_SINT16, 0);
  980. }
  981. }
  982. static Uint8 RemapButton(SDL_DriverSwitch_Context *ctx, Uint8 button)
  983. {
  984. if (ctx->m_bUseButtonLabels) {
  985. // Use button labels instead of positions, e.g. Nintendo Online Classic controllers
  986. switch (button) {
  987. case SDL_GAMEPAD_BUTTON_SOUTH:
  988. return SDL_GAMEPAD_BUTTON_EAST;
  989. case SDL_GAMEPAD_BUTTON_EAST:
  990. return SDL_GAMEPAD_BUTTON_SOUTH;
  991. case SDL_GAMEPAD_BUTTON_WEST:
  992. return SDL_GAMEPAD_BUTTON_NORTH;
  993. case SDL_GAMEPAD_BUTTON_NORTH:
  994. return SDL_GAMEPAD_BUTTON_WEST;
  995. default:
  996. break;
  997. }
  998. }
  999. return button;
  1000. }
  1001. static int GetMaxWriteAttempts(SDL_HIDAPI_Device *device)
  1002. {
  1003. if (device->vendor_id == USB_VENDOR_NINTENDO &&
  1004. device->product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) {
  1005. // This device is a little slow and we know we're always on USB
  1006. return 20;
  1007. } else {
  1008. return 5;
  1009. }
  1010. }
  1011. static ESwitchDeviceInfoControllerType ReadJoyConControllerType(SDL_HIDAPI_Device *device)
  1012. {
  1013. ESwitchDeviceInfoControllerType eControllerType = k_eSwitchDeviceInfoControllerType_Unknown;
  1014. const int MAX_ATTEMPTS = 1; // Don't try too long, in case this is a zombie Bluetooth controller
  1015. int attempts = 0;
  1016. // Create enough of a context to read the controller type from the device
  1017. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)SDL_calloc(1, sizeof(*ctx));
  1018. if (ctx) {
  1019. ctx->device = device;
  1020. ctx->m_bSyncWrite = true;
  1021. ctx->m_nMaxWriteAttempts = GetMaxWriteAttempts(device);
  1022. for ( ; ; ) {
  1023. ++attempts;
  1024. if (device->is_bluetooth) {
  1025. SwitchSubcommandInputPacket_t *reply = NULL;
  1026. if (WriteSubcommand(ctx, k_eSwitchSubcommandIDs_RequestDeviceInfo, NULL, 0, &reply)) {
  1027. eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)reply->deviceInfo.ucDeviceType);
  1028. }
  1029. } else {
  1030. if (WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_Status, NULL, 0, true)) {
  1031. SwitchProprietaryStatusPacket_t *status = (SwitchProprietaryStatusPacket_t *)&ctx->m_rgucReadBuffer[0];
  1032. eControllerType = CalculateControllerType(ctx, (ESwitchDeviceInfoControllerType)status->ucDeviceType);
  1033. }
  1034. }
  1035. if (eControllerType == k_eSwitchDeviceInfoControllerType_Unknown && attempts < MAX_ATTEMPTS) {
  1036. // Wait a bit and try again
  1037. SDL_Delay(100);
  1038. continue;
  1039. }
  1040. break;
  1041. }
  1042. SDL_free(ctx);
  1043. }
  1044. return eControllerType;
  1045. }
  1046. static bool HasHomeLED(SDL_DriverSwitch_Context *ctx)
  1047. {
  1048. Uint16 vendor_id = ctx->device->vendor_id;
  1049. Uint16 product_id = ctx->device->product_id;
  1050. // The Power A Nintendo Switch Pro controllers don't have a Home LED
  1051. if (vendor_id == 0 && product_id == 0) {
  1052. return false;
  1053. }
  1054. // HORI Wireless Switch Pad
  1055. if (vendor_id == 0x0f0d && product_id == 0x00f6) {
  1056. return false;
  1057. }
  1058. // Third party controllers don't have a home LED and will shut off if we try to set it
  1059. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_Unknown ||
  1060. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_LicProController) {
  1061. return false;
  1062. }
  1063. // The Nintendo Online classic controllers don't have a Home LED
  1064. if (vendor_id == USB_VENDOR_NINTENDO &&
  1065. ctx->m_eControllerType > k_eSwitchDeviceInfoControllerType_ProController) {
  1066. return false;
  1067. }
  1068. return true;
  1069. }
  1070. static bool AlwaysUsesLabels(Uint16 vendor_id, Uint16 product_id, ESwitchDeviceInfoControllerType eControllerType)
  1071. {
  1072. // Some controllers don't have a diamond button configuration, so should always use labels
  1073. if (SDL_IsJoystickGameCube(vendor_id, product_id)) {
  1074. return true;
  1075. }
  1076. switch (eControllerType) {
  1077. case k_eSwitchDeviceInfoControllerType_HVCLeft:
  1078. case k_eSwitchDeviceInfoControllerType_HVCRight:
  1079. case k_eSwitchDeviceInfoControllerType_NESLeft:
  1080. case k_eSwitchDeviceInfoControllerType_NESRight:
  1081. case k_eSwitchDeviceInfoControllerType_N64:
  1082. case k_eSwitchDeviceInfoControllerType_SEGA_Genesis:
  1083. return true;
  1084. default:
  1085. return false;
  1086. }
  1087. }
  1088. static void HIDAPI_DriverNintendoClassic_RegisterHints(SDL_HintCallback callback, void *userdata)
  1089. {
  1090. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, callback, userdata);
  1091. }
  1092. static void HIDAPI_DriverNintendoClassic_UnregisterHints(SDL_HintCallback callback, void *userdata)
  1093. {
  1094. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, callback, userdata);
  1095. }
  1096. static bool HIDAPI_DriverNintendoClassic_IsEnabled(void)
  1097. {
  1098. return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT));
  1099. }
  1100. static bool HIDAPI_DriverNintendoClassic_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  1101. {
  1102. if (vendor_id == USB_VENDOR_NINTENDO) {
  1103. if (product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT) {
  1104. if (SDL_strncmp(name, "NES Controller", 14) == 0 ||
  1105. SDL_strncmp(name, "HVC Controller", 14) == 0) {
  1106. return true;
  1107. }
  1108. }
  1109. if (product_id == USB_PRODUCT_NINTENDO_N64_CONTROLLER) {
  1110. return true;
  1111. }
  1112. if (product_id == USB_PRODUCT_NINTENDO_SEGA_GENESIS_CONTROLLER) {
  1113. return true;
  1114. }
  1115. if (product_id == USB_PRODUCT_NINTENDO_SNES_CONTROLLER) {
  1116. return true;
  1117. }
  1118. }
  1119. return false;
  1120. }
  1121. static void HIDAPI_DriverJoyCons_RegisterHints(SDL_HintCallback callback, void *userdata)
  1122. {
  1123. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, callback, userdata);
  1124. }
  1125. static void HIDAPI_DriverJoyCons_UnregisterHints(SDL_HintCallback callback, void *userdata)
  1126. {
  1127. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, callback, userdata);
  1128. }
  1129. static bool HIDAPI_DriverJoyCons_IsEnabled(void)
  1130. {
  1131. return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT));
  1132. }
  1133. static bool HIDAPI_DriverJoyCons_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  1134. {
  1135. if (vendor_id == USB_VENDOR_NINTENDO) {
  1136. if (product_id == USB_PRODUCT_NINTENDO_SWITCH_PRO && device && device->dev) {
  1137. // This might be a Kinvoca Joy-Con that reports VID/PID as a Switch Pro controller
  1138. ESwitchDeviceInfoControllerType eControllerType = ReadJoyConControllerType(device);
  1139. if (eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft ||
  1140. eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  1141. return true;
  1142. }
  1143. }
  1144. if (product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT ||
  1145. product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT ||
  1146. product_id == USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) {
  1147. return true;
  1148. }
  1149. }
  1150. return false;
  1151. }
  1152. static void HIDAPI_DriverSwitch_RegisterHints(SDL_HintCallback callback, void *userdata)
  1153. {
  1154. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, callback, userdata);
  1155. }
  1156. static void HIDAPI_DriverSwitch_UnregisterHints(SDL_HintCallback callback, void *userdata)
  1157. {
  1158. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, callback, userdata);
  1159. }
  1160. static bool HIDAPI_DriverSwitch_IsEnabled(void)
  1161. {
  1162. return SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_SWITCH, SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI, SDL_HIDAPI_DEFAULT));
  1163. }
  1164. static bool HIDAPI_DriverSwitch_IsSupportedDevice(SDL_HIDAPI_Device *device, const char *name, SDL_GamepadType type, Uint16 vendor_id, Uint16 product_id, Uint16 version, int interface_number, int interface_class, int interface_subclass, int interface_protocol)
  1165. {
  1166. /* The HORI Wireless Switch Pad enumerates as a HID device when connected via USB
  1167. with the same VID/PID as when connected over Bluetooth but doesn't actually
  1168. support communication over USB. The most reliable way to block this without allowing the
  1169. controller to continually attempt to reconnect is to filter it out by manufacturer/product string.
  1170. Note that the controller does have a different product string when connected over Bluetooth.
  1171. */
  1172. if (SDL_strcmp(name, "HORI Wireless Switch Pad") == 0) {
  1173. return false;
  1174. }
  1175. // If it's handled by another driver, it's not handled here
  1176. if (HIDAPI_DriverNintendoClassic_IsSupportedDevice(device, name, type, vendor_id, product_id, version, interface_number, interface_class, interface_subclass, interface_protocol) ||
  1177. HIDAPI_DriverJoyCons_IsSupportedDevice(device, name, type, vendor_id, product_id, version, interface_number, interface_class, interface_subclass, interface_protocol)) {
  1178. return false;
  1179. }
  1180. return (type == SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO);
  1181. }
  1182. static void UpdateDeviceIdentity(SDL_HIDAPI_Device *device)
  1183. {
  1184. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1185. if (ctx->m_bInputOnly) {
  1186. if (SDL_IsJoystickGameCube(device->vendor_id, device->product_id)) {
  1187. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1188. }
  1189. } else {
  1190. char serial[18];
  1191. switch (ctx->m_eControllerType) {
  1192. case k_eSwitchDeviceInfoControllerType_JoyConLeft:
  1193. HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (L)");
  1194. HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT);
  1195. device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT;
  1196. break;
  1197. case k_eSwitchDeviceInfoControllerType_JoyConRight:
  1198. HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (R)");
  1199. HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT);
  1200. device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT;
  1201. break;
  1202. case k_eSwitchDeviceInfoControllerType_ProController:
  1203. case k_eSwitchDeviceInfoControllerType_LicProController:
  1204. HIDAPI_SetDeviceName(device, "Nintendo Switch Pro Controller");
  1205. HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SWITCH_PRO);
  1206. device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO;
  1207. break;
  1208. case k_eSwitchDeviceInfoControllerType_HVCLeft:
  1209. HIDAPI_SetDeviceName(device, "Nintendo HVC Controller (1)");
  1210. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1211. break;
  1212. case k_eSwitchDeviceInfoControllerType_HVCRight:
  1213. HIDAPI_SetDeviceName(device, "Nintendo HVC Controller (2)");
  1214. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1215. break;
  1216. case k_eSwitchDeviceInfoControllerType_NESLeft:
  1217. HIDAPI_SetDeviceName(device, "Nintendo NES Controller (L)");
  1218. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1219. break;
  1220. case k_eSwitchDeviceInfoControllerType_NESRight:
  1221. HIDAPI_SetDeviceName(device, "Nintendo NES Controller (R)");
  1222. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1223. break;
  1224. case k_eSwitchDeviceInfoControllerType_SNES:
  1225. HIDAPI_SetDeviceName(device, "Nintendo SNES Controller");
  1226. HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SNES_CONTROLLER);
  1227. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1228. break;
  1229. case k_eSwitchDeviceInfoControllerType_N64:
  1230. HIDAPI_SetDeviceName(device, "Nintendo N64 Controller");
  1231. HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_N64_CONTROLLER);
  1232. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1233. break;
  1234. case k_eSwitchDeviceInfoControllerType_SEGA_Genesis:
  1235. HIDAPI_SetDeviceName(device, "Nintendo SEGA Genesis Controller");
  1236. HIDAPI_SetDeviceProduct(device, USB_VENDOR_NINTENDO, USB_PRODUCT_NINTENDO_SEGA_GENESIS_CONTROLLER);
  1237. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1238. break;
  1239. case k_eSwitchDeviceInfoControllerType_Unknown:
  1240. // We couldn't read the device info for this controller, might not be fully compliant
  1241. if (device->vendor_id == USB_VENDOR_NINTENDO) {
  1242. switch (device->product_id) {
  1243. case USB_PRODUCT_NINTENDO_SWITCH_JOYCON_LEFT:
  1244. ctx->m_eControllerType = k_eSwitchDeviceInfoControllerType_JoyConLeft;
  1245. HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (L)");
  1246. device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_LEFT;
  1247. break;
  1248. case USB_PRODUCT_NINTENDO_SWITCH_JOYCON_RIGHT:
  1249. ctx->m_eControllerType = k_eSwitchDeviceInfoControllerType_JoyConRight;
  1250. HIDAPI_SetDeviceName(device, "Nintendo Switch Joy-Con (R)");
  1251. device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_JOYCON_RIGHT;
  1252. break;
  1253. case USB_PRODUCT_NINTENDO_SWITCH_PRO:
  1254. ctx->m_eControllerType = k_eSwitchDeviceInfoControllerType_ProController;
  1255. HIDAPI_SetDeviceName(device, "Nintendo Switch Pro Controller");
  1256. device->type = SDL_GAMEPAD_TYPE_NINTENDO_SWITCH_PRO;
  1257. break;
  1258. default:
  1259. break;
  1260. }
  1261. }
  1262. return;
  1263. default:
  1264. device->type = SDL_GAMEPAD_TYPE_STANDARD;
  1265. break;
  1266. }
  1267. device->guid.data[15] = ctx->m_eControllerType;
  1268. (void)SDL_snprintf(serial, sizeof(serial), "%.2x-%.2x-%.2x-%.2x-%.2x-%.2x",
  1269. ctx->m_rgucMACAddress[0],
  1270. ctx->m_rgucMACAddress[1],
  1271. ctx->m_rgucMACAddress[2],
  1272. ctx->m_rgucMACAddress[3],
  1273. ctx->m_rgucMACAddress[4],
  1274. ctx->m_rgucMACAddress[5]);
  1275. HIDAPI_SetDeviceSerial(device, serial);
  1276. }
  1277. }
  1278. static bool HIDAPI_DriverSwitch_InitDevice(SDL_HIDAPI_Device *device)
  1279. {
  1280. SDL_DriverSwitch_Context *ctx;
  1281. ctx = (SDL_DriverSwitch_Context *)SDL_calloc(1, sizeof(*ctx));
  1282. if (!ctx) {
  1283. return false;
  1284. }
  1285. ctx->device = device;
  1286. device->context = ctx;
  1287. ctx->m_nMaxWriteAttempts = GetMaxWriteAttempts(device);
  1288. ctx->m_bSyncWrite = true;
  1289. // Find out whether or not we can send output reports
  1290. ctx->m_bInputOnly = SDL_IsJoystickNintendoSwitchProInputOnly(device->vendor_id, device->product_id);
  1291. if (!ctx->m_bInputOnly) {
  1292. // Initialize rumble data, important for reading device info on the MOBAPAD M073
  1293. SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]);
  1294. SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]);
  1295. BReadDeviceInfo(ctx);
  1296. }
  1297. UpdateDeviceIdentity(device);
  1298. // Prefer the USB device over the Bluetooth device
  1299. if (device->is_bluetooth) {
  1300. if (HIDAPI_HasConnectedUSBDevice(device->serial)) {
  1301. return true;
  1302. }
  1303. } else {
  1304. HIDAPI_DisconnectBluetoothDevice(device->serial);
  1305. }
  1306. return HIDAPI_JoystickConnected(device, NULL);
  1307. }
  1308. static int HIDAPI_DriverSwitch_GetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id)
  1309. {
  1310. return -1;
  1311. }
  1312. static void HIDAPI_DriverSwitch_SetDevicePlayerIndex(SDL_HIDAPI_Device *device, SDL_JoystickID instance_id, int player_index)
  1313. {
  1314. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1315. if (!ctx->joystick) {
  1316. return;
  1317. }
  1318. ctx->m_nPlayerIndex = player_index;
  1319. UpdateSlotLED(ctx);
  1320. }
  1321. static bool HIDAPI_DriverSwitch_OpenJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  1322. {
  1323. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1324. SDL_AssertJoysticksLocked();
  1325. ctx->joystick = joystick;
  1326. ctx->m_bSyncWrite = true;
  1327. if (!ctx->m_bInputOnly) {
  1328. #ifdef SDL_PLATFORM_MACOS
  1329. // Wait for the OS to finish its handshake with the controller
  1330. SDL_Delay(250);
  1331. #endif
  1332. GetInitialInputMode(ctx);
  1333. ctx->m_nCurrentInputMode = ctx->m_nInitialInputMode;
  1334. // Initialize rumble data
  1335. SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]);
  1336. SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]);
  1337. if (!device->is_bluetooth) {
  1338. if (!BTrySetupUSB(ctx)) {
  1339. SDL_SetError("Couldn't setup USB mode");
  1340. return false;
  1341. }
  1342. }
  1343. if (!LoadStickCalibration(ctx)) {
  1344. SDL_SetError("Couldn't load stick calibration");
  1345. return false;
  1346. }
  1347. if (ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_HVCLeft &&
  1348. ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_HVCRight &&
  1349. ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_NESLeft &&
  1350. ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_NESRight &&
  1351. ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_SNES &&
  1352. ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_N64 &&
  1353. ctx->m_eControllerType != k_eSwitchDeviceInfoControllerType_SEGA_Genesis) {
  1354. if (LoadIMUCalibration(ctx)) {
  1355. ctx->m_bSensorsSupported = true;
  1356. }
  1357. }
  1358. // Enable vibration
  1359. SetVibrationEnabled(ctx, 1);
  1360. // Set desired input mode
  1361. SDL_AddHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS,
  1362. SDL_EnhancedReportsChanged, ctx);
  1363. // Start sending USB reports
  1364. if (!device->is_bluetooth) {
  1365. // ForceUSB doesn't generate an ACK, so don't wait for a reply
  1366. if (!WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, false)) {
  1367. SDL_SetError("Couldn't start USB reports");
  1368. return false;
  1369. }
  1370. }
  1371. // Set the LED state
  1372. if (HasHomeLED(ctx)) {
  1373. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft ||
  1374. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  1375. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED,
  1376. SDL_HomeLEDHintChanged, ctx);
  1377. } else {
  1378. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED,
  1379. SDL_HomeLEDHintChanged, ctx);
  1380. }
  1381. }
  1382. }
  1383. if (AlwaysUsesLabels(device->vendor_id, device->product_id, ctx->m_eControllerType)) {
  1384. ctx->m_bUseButtonLabels = true;
  1385. }
  1386. // Initialize player index (needed for setting LEDs)
  1387. ctx->m_nPlayerIndex = SDL_GetJoystickPlayerIndex(joystick);
  1388. ctx->m_bPlayerLights = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED, true);
  1389. UpdateSlotLED(ctx);
  1390. SDL_AddHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED,
  1391. SDL_PlayerLEDHintChanged, ctx);
  1392. // Initialize the joystick capabilities
  1393. joystick->nbuttons = SDL_GAMEPAD_NUM_SWITCH_BUTTONS;
  1394. joystick->naxes = SDL_GAMEPAD_AXIS_COUNT;
  1395. joystick->nhats = 1;
  1396. // Set up for input
  1397. ctx->m_bSyncWrite = false;
  1398. ctx->m_ulLastIMUReset = ctx->m_ulLastInput = SDL_GetTicks();
  1399. ctx->m_ulIMUUpdateIntervalNS = SDL_MS_TO_NS(5); // Start off at 5 ms update rate
  1400. // Set up for vertical mode
  1401. ctx->m_bVerticalMode = SDL_GetHintBoolean(SDL_HINT_JOYSTICK_HIDAPI_VERTICAL_JOY_CONS, false);
  1402. return true;
  1403. }
  1404. static bool HIDAPI_DriverSwitch_ActuallyRumbleJoystick(SDL_DriverSwitch_Context *ctx, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  1405. {
  1406. /* Experimentally determined rumble values. These will only matter on some controllers as tested ones
  1407. * seem to disregard these and just use any non-zero rumble values as a binary flag for constant rumble
  1408. *
  1409. * More information about these values can be found here:
  1410. * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
  1411. */
  1412. const Uint16 k_usHighFreq = 0x0074;
  1413. const Uint8 k_ucHighFreqAmp = EncodeRumbleHighAmplitude(high_frequency_rumble);
  1414. const Uint8 k_ucLowFreq = 0x3D;
  1415. const Uint16 k_usLowFreqAmp = EncodeRumbleLowAmplitude(low_frequency_rumble);
  1416. if (low_frequency_rumble || high_frequency_rumble) {
  1417. EncodeRumble(&ctx->m_RumblePacket.rumbleData[0], k_usHighFreq, k_ucHighFreqAmp, k_ucLowFreq, k_usLowFreqAmp);
  1418. EncodeRumble(&ctx->m_RumblePacket.rumbleData[1], k_usHighFreq, k_ucHighFreqAmp, k_ucLowFreq, k_usLowFreqAmp);
  1419. } else {
  1420. SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[0]);
  1421. SetNeutralRumble(&ctx->m_RumblePacket.rumbleData[1]);
  1422. }
  1423. ctx->m_bRumbleActive = (low_frequency_rumble || high_frequency_rumble);
  1424. if (!WriteRumble(ctx)) {
  1425. return SDL_SetError("Couldn't send rumble packet");
  1426. }
  1427. return true;
  1428. }
  1429. static bool HIDAPI_DriverSwitch_SendPendingRumble(SDL_DriverSwitch_Context *ctx)
  1430. {
  1431. if (SDL_GetTicks() < (ctx->m_ulRumbleSent + RUMBLE_WRITE_FREQUENCY_MS)) {
  1432. return true;
  1433. }
  1434. if (ctx->m_bRumblePending) {
  1435. Uint16 low_frequency_rumble = (Uint16)(ctx->m_unRumblePending >> 16);
  1436. Uint16 high_frequency_rumble = (Uint16)ctx->m_unRumblePending;
  1437. #ifdef DEBUG_RUMBLE
  1438. SDL_Log("Sent pending rumble %d/%d, %d ms after previous rumble", low_frequency_rumble, high_frequency_rumble, SDL_GetTicks() - ctx->m_ulRumbleSent);
  1439. #endif
  1440. ctx->m_bRumblePending = false;
  1441. ctx->m_unRumblePending = 0;
  1442. return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, low_frequency_rumble, high_frequency_rumble);
  1443. }
  1444. if (ctx->m_bRumbleZeroPending) {
  1445. ctx->m_bRumbleZeroPending = false;
  1446. #ifdef DEBUG_RUMBLE
  1447. SDL_Log("Sent pending zero rumble, %d ms after previous rumble", SDL_GetTicks() - ctx->m_ulRumbleSent);
  1448. #endif
  1449. return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, 0, 0);
  1450. }
  1451. return true;
  1452. }
  1453. static bool HIDAPI_DriverSwitch_RumbleJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 low_frequency_rumble, Uint16 high_frequency_rumble)
  1454. {
  1455. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1456. if (ctx->m_bInputOnly) {
  1457. return SDL_Unsupported();
  1458. }
  1459. if (device->parent) {
  1460. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) {
  1461. // Just handle low frequency rumble
  1462. high_frequency_rumble = 0;
  1463. } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  1464. // Just handle high frequency rumble
  1465. low_frequency_rumble = 0;
  1466. }
  1467. }
  1468. if (ctx->m_bRumblePending) {
  1469. if (!HIDAPI_DriverSwitch_SendPendingRumble(ctx)) {
  1470. return false;
  1471. }
  1472. }
  1473. if (SDL_GetTicks() < (ctx->m_ulRumbleSent + RUMBLE_WRITE_FREQUENCY_MS)) {
  1474. if (low_frequency_rumble || high_frequency_rumble) {
  1475. Uint32 unRumblePending = ((Uint32)low_frequency_rumble << 16) | high_frequency_rumble;
  1476. // Keep the highest rumble intensity in the given interval
  1477. if (unRumblePending > ctx->m_unRumblePending) {
  1478. ctx->m_unRumblePending = unRumblePending;
  1479. }
  1480. ctx->m_bRumblePending = true;
  1481. ctx->m_bRumbleZeroPending = false;
  1482. } else {
  1483. // When rumble is complete, turn it off
  1484. ctx->m_bRumbleZeroPending = true;
  1485. }
  1486. return true;
  1487. }
  1488. #ifdef DEBUG_RUMBLE
  1489. SDL_Log("Sent rumble %d/%d", low_frequency_rumble, high_frequency_rumble);
  1490. #endif
  1491. return HIDAPI_DriverSwitch_ActuallyRumbleJoystick(ctx, low_frequency_rumble, high_frequency_rumble);
  1492. }
  1493. static bool HIDAPI_DriverSwitch_RumbleJoystickTriggers(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint16 left_rumble, Uint16 right_rumble)
  1494. {
  1495. return SDL_Unsupported();
  1496. }
  1497. static Uint32 HIDAPI_DriverSwitch_GetJoystickCapabilities(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  1498. {
  1499. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1500. Uint32 result = 0;
  1501. if (ctx->m_bPlayerLights && !ctx->m_bInputOnly) {
  1502. result |= SDL_JOYSTICK_CAP_PLAYER_LED;
  1503. }
  1504. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_ProController && !ctx->m_bInputOnly) {
  1505. // Doesn't have an RGB LED, so don't return SDL_JOYSTICK_CAP_RGB_LED here
  1506. result |= SDL_JOYSTICK_CAP_RUMBLE;
  1507. } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft ||
  1508. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  1509. result |= SDL_JOYSTICK_CAP_RUMBLE;
  1510. }
  1511. return result;
  1512. }
  1513. static bool HIDAPI_DriverSwitch_SetJoystickLED(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, Uint8 red, Uint8 green, Uint8 blue)
  1514. {
  1515. return SDL_Unsupported();
  1516. }
  1517. static bool HIDAPI_DriverSwitch_SendJoystickEffect(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, const void *data, int size)
  1518. {
  1519. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1520. if (size == sizeof(SwitchCommonOutputPacket_t)) {
  1521. const SwitchCommonOutputPacket_t *packet = (SwitchCommonOutputPacket_t *)data;
  1522. if (packet->ucPacketType != k_eSwitchOutputReportIDs_Rumble) {
  1523. return SDL_SetError("Unknown Nintendo Switch Pro effect type");
  1524. }
  1525. SDL_copyp(&ctx->m_RumblePacket.rumbleData[0], &packet->rumbleData[0]);
  1526. SDL_copyp(&ctx->m_RumblePacket.rumbleData[1], &packet->rumbleData[1]);
  1527. if (!WriteRumble(ctx)) {
  1528. return false;
  1529. }
  1530. // This overwrites any internal rumble
  1531. ctx->m_bRumblePending = false;
  1532. ctx->m_bRumbleZeroPending = false;
  1533. return true;
  1534. } else if (size >= 2 && size <= 256) {
  1535. const Uint8 *payload = (const Uint8 *)data;
  1536. ESwitchSubcommandIDs cmd = (ESwitchSubcommandIDs)payload[0];
  1537. if (cmd == k_eSwitchSubcommandIDs_SetInputReportMode && !device->is_bluetooth) {
  1538. // Going into simple mode over USB disables input reports, so don't do that
  1539. return true;
  1540. }
  1541. if (cmd == k_eSwitchSubcommandIDs_SetHomeLight && !HasHomeLED(ctx)) {
  1542. // Setting the home LED when it's not supported can cause the controller to reset
  1543. return true;
  1544. }
  1545. if (!WriteSubcommand(ctx, cmd, &payload[1], (Uint8)(size - 1), NULL)) {
  1546. return false;
  1547. }
  1548. return true;
  1549. }
  1550. return SDL_Unsupported();
  1551. }
  1552. static bool HIDAPI_DriverSwitch_SetJoystickSensorsEnabled(SDL_HIDAPI_Device *device, SDL_Joystick *joystick, bool enabled)
  1553. {
  1554. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  1555. UpdateEnhancedModeOnApplicationUsage(ctx);
  1556. if (!ctx->m_bSensorsSupported || (enabled && !ctx->m_bEnhancedMode)) {
  1557. return SDL_Unsupported();
  1558. }
  1559. ctx->m_bReportSensors = enabled;
  1560. ctx->m_unIMUSamples = 0;
  1561. ctx->m_ulIMUSampleTimestampNS = SDL_GetTicksNS();
  1562. UpdateInputMode(ctx);
  1563. SetIMUEnabled(ctx, enabled);
  1564. return true;
  1565. }
  1566. static void HandleInputOnlyControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchInputOnlyControllerStatePacket_t *packet)
  1567. {
  1568. Sint16 axis;
  1569. Uint64 timestamp = SDL_GetTicksNS();
  1570. if (packet->rgucButtons[0] != ctx->m_lastInputOnlyState.rgucButtons[0]) {
  1571. Uint8 data = packet->rgucButtons[0];
  1572. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x02) != 0));
  1573. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x04) != 0));
  1574. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x01) != 0));
  1575. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0));
  1576. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0));
  1577. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0));
  1578. }
  1579. if (packet->rgucButtons[1] != ctx->m_lastInputOnlyState.rgucButtons[1]) {
  1580. Uint8 data = packet->rgucButtons[1];
  1581. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0));
  1582. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  1583. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0));
  1584. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x08) != 0));
  1585. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  1586. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0));
  1587. }
  1588. if (packet->ucStickHat != ctx->m_lastInputOnlyState.ucStickHat) {
  1589. Uint8 hat;
  1590. switch (packet->ucStickHat) {
  1591. case 0:
  1592. hat = SDL_HAT_UP;
  1593. break;
  1594. case 1:
  1595. hat = SDL_HAT_RIGHTUP;
  1596. break;
  1597. case 2:
  1598. hat = SDL_HAT_RIGHT;
  1599. break;
  1600. case 3:
  1601. hat = SDL_HAT_RIGHTDOWN;
  1602. break;
  1603. case 4:
  1604. hat = SDL_HAT_DOWN;
  1605. break;
  1606. case 5:
  1607. hat = SDL_HAT_LEFTDOWN;
  1608. break;
  1609. case 6:
  1610. hat = SDL_HAT_LEFT;
  1611. break;
  1612. case 7:
  1613. hat = SDL_HAT_LEFTUP;
  1614. break;
  1615. default:
  1616. hat = SDL_HAT_CENTERED;
  1617. break;
  1618. }
  1619. SDL_SendJoystickHat(timestamp, joystick, 0, hat);
  1620. }
  1621. axis = (packet->rgucButtons[0] & 0x40) ? 32767 : -32768;
  1622. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis);
  1623. axis = (packet->rgucButtons[0] & 0x80) ? 32767 : -32768;
  1624. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis);
  1625. if (packet->rgucJoystickLeft[0] != ctx->m_lastInputOnlyState.rgucJoystickLeft[0]) {
  1626. axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickLeft[0], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16);
  1627. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis);
  1628. }
  1629. if (packet->rgucJoystickLeft[1] != ctx->m_lastInputOnlyState.rgucJoystickLeft[1]) {
  1630. axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickLeft[1], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16);
  1631. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis);
  1632. }
  1633. if (packet->rgucJoystickRight[0] != ctx->m_lastInputOnlyState.rgucJoystickRight[0]) {
  1634. axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickRight[0], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16);
  1635. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis);
  1636. }
  1637. if (packet->rgucJoystickRight[1] != ctx->m_lastInputOnlyState.rgucJoystickRight[1]) {
  1638. axis = (Sint16)HIDAPI_RemapVal(packet->rgucJoystickRight[1], SDL_MIN_UINT8, SDL_MAX_UINT8, SDL_MIN_SINT16, SDL_MAX_SINT16);
  1639. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis);
  1640. }
  1641. ctx->m_lastInputOnlyState = *packet;
  1642. }
  1643. static void HandleCombinedSimpleControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet)
  1644. {
  1645. if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) {
  1646. Uint8 data = packet->rgucButtons[0];
  1647. Uint8 hat = 0;
  1648. if (data & 0x01) {
  1649. hat |= SDL_HAT_LEFT;
  1650. }
  1651. if (data & 0x02) {
  1652. hat |= SDL_HAT_DOWN;
  1653. }
  1654. if (data & 0x04) {
  1655. hat |= SDL_HAT_UP;
  1656. }
  1657. if (data & 0x08) {
  1658. hat |= SDL_HAT_RIGHT;
  1659. }
  1660. SDL_SendJoystickHat(timestamp, joystick, 0, hat);
  1661. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x10) != 0));
  1662. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x20) != 0));
  1663. }
  1664. if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) {
  1665. Uint8 data = packet->rgucButtons[1];
  1666. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0));
  1667. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0));
  1668. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0));
  1669. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x40) != 0));
  1670. }
  1671. Sint16 axis = (packet->rgucButtons[1] & 0x80) ? 32767 : -32768;
  1672. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis);
  1673. if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) {
  1674. switch (packet->ucStickHat) {
  1675. case 0:
  1676. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1677. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1678. break;
  1679. case 1:
  1680. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1681. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1682. break;
  1683. case 2:
  1684. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1685. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1686. break;
  1687. case 3:
  1688. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1689. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1690. break;
  1691. case 4:
  1692. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1693. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1694. break;
  1695. case 5:
  1696. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1697. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1698. break;
  1699. case 6:
  1700. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1701. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1702. break;
  1703. case 7:
  1704. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1705. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1706. break;
  1707. default:
  1708. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1709. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1710. break;
  1711. }
  1712. }
  1713. }
  1714. static void HandleCombinedSimpleControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet)
  1715. {
  1716. if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) {
  1717. Uint8 data = packet->rgucButtons[0];
  1718. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x01) != 0));
  1719. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x02) != 0));
  1720. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x04) != 0));
  1721. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x08) != 0));
  1722. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x10) != 0));
  1723. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x20) != 0));
  1724. }
  1725. if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) {
  1726. Uint8 data = packet->rgucButtons[1];
  1727. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  1728. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x08) != 0));
  1729. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  1730. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x40) != 0));
  1731. }
  1732. Sint16 axis = (packet->rgucButtons[1] & 0x80) ? 32767 : -32768;
  1733. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis);
  1734. if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) {
  1735. switch (packet->ucStickHat) {
  1736. case 0:
  1737. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MIN);
  1738. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, 0);
  1739. break;
  1740. case 1:
  1741. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MIN);
  1742. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MIN);
  1743. break;
  1744. case 2:
  1745. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, 0);
  1746. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MIN);
  1747. break;
  1748. case 3:
  1749. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MAX);
  1750. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MIN);
  1751. break;
  1752. case 4:
  1753. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MAX);
  1754. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, 0);
  1755. break;
  1756. case 5:
  1757. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MAX);
  1758. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MAX);
  1759. break;
  1760. case 6:
  1761. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, 0);
  1762. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MAX);
  1763. break;
  1764. case 7:
  1765. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, SDL_JOYSTICK_AXIS_MIN);
  1766. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, SDL_JOYSTICK_AXIS_MAX);
  1767. break;
  1768. default:
  1769. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, 0);
  1770. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, 0);
  1771. break;
  1772. }
  1773. }
  1774. }
  1775. static void HandleMiniSimpleControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet)
  1776. {
  1777. if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) {
  1778. Uint8 data = packet->rgucButtons[0];
  1779. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x01) != 0));
  1780. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0));
  1781. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0));
  1782. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0));
  1783. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0));
  1784. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0));
  1785. }
  1786. if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) {
  1787. Uint8 data = packet->rgucButtons[1];
  1788. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x01) != 0));
  1789. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0));
  1790. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x20) != 0));
  1791. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x40) != 0));
  1792. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x80) != 0));
  1793. }
  1794. if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) {
  1795. switch (packet->ucStickHat) {
  1796. case 0:
  1797. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1798. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1799. break;
  1800. case 1:
  1801. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1802. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1803. break;
  1804. case 2:
  1805. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1806. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1807. break;
  1808. case 3:
  1809. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1810. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1811. break;
  1812. case 4:
  1813. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1814. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1815. break;
  1816. case 5:
  1817. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1818. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1819. break;
  1820. case 6:
  1821. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1822. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1823. break;
  1824. case 7:
  1825. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1826. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1827. break;
  1828. default:
  1829. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1830. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1831. break;
  1832. }
  1833. }
  1834. }
  1835. static void HandleMiniSimpleControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet)
  1836. {
  1837. if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) {
  1838. Uint8 data = packet->rgucButtons[0];
  1839. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x01) != 0));
  1840. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0));
  1841. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0));
  1842. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0));
  1843. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0));
  1844. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0));
  1845. }
  1846. if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) {
  1847. Uint8 data = packet->rgucButtons[1];
  1848. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  1849. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0));
  1850. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  1851. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0));
  1852. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x40) != 0));
  1853. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x80) != 0));
  1854. }
  1855. if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) {
  1856. switch (packet->ucStickHat) {
  1857. case 0:
  1858. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1859. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1860. break;
  1861. case 1:
  1862. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1863. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1864. break;
  1865. case 2:
  1866. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1867. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1868. break;
  1869. case 3:
  1870. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MAX);
  1871. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1872. break;
  1873. case 4:
  1874. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1875. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1876. break;
  1877. case 5:
  1878. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1879. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MAX);
  1880. break;
  1881. case 6:
  1882. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1883. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1884. break;
  1885. case 7:
  1886. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, SDL_JOYSTICK_AXIS_MIN);
  1887. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, SDL_JOYSTICK_AXIS_MIN);
  1888. break;
  1889. default:
  1890. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, 0);
  1891. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, 0);
  1892. break;
  1893. }
  1894. }
  1895. }
  1896. static void HandleSimpleControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchSimpleStatePacket_t *packet)
  1897. {
  1898. Uint64 timestamp = SDL_GetTicksNS();
  1899. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) {
  1900. if (ctx->device->parent || ctx->m_bVerticalMode) {
  1901. HandleCombinedSimpleControllerStateL(timestamp, joystick, ctx, packet);
  1902. } else {
  1903. HandleMiniSimpleControllerStateL(timestamp, joystick, ctx, packet);
  1904. }
  1905. } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  1906. if (ctx->device->parent || ctx->m_bVerticalMode) {
  1907. HandleCombinedSimpleControllerStateR(timestamp, joystick, ctx, packet);
  1908. } else {
  1909. HandleMiniSimpleControllerStateR(timestamp, joystick, ctx, packet);
  1910. }
  1911. } else {
  1912. Sint16 axis;
  1913. if (packet->rgucButtons[0] != ctx->m_lastSimpleState.rgucButtons[0]) {
  1914. Uint8 data = packet->rgucButtons[0];
  1915. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x01) != 0));
  1916. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0));
  1917. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0));
  1918. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x08) != 0));
  1919. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x10) != 0));
  1920. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x20) != 0));
  1921. }
  1922. if (packet->rgucButtons[1] != ctx->m_lastSimpleState.rgucButtons[1]) {
  1923. Uint8 data = packet->rgucButtons[1];
  1924. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0));
  1925. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  1926. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0));
  1927. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x08) != 0));
  1928. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  1929. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0));
  1930. }
  1931. if (packet->ucStickHat != ctx->m_lastSimpleState.ucStickHat) {
  1932. Uint8 hat;
  1933. switch (packet->ucStickHat) {
  1934. case 0:
  1935. hat = SDL_HAT_UP;
  1936. break;
  1937. case 1:
  1938. hat = SDL_HAT_RIGHTUP;
  1939. break;
  1940. case 2:
  1941. hat = SDL_HAT_RIGHT;
  1942. break;
  1943. case 3:
  1944. hat = SDL_HAT_RIGHTDOWN;
  1945. break;
  1946. case 4:
  1947. hat = SDL_HAT_DOWN;
  1948. break;
  1949. case 5:
  1950. hat = SDL_HAT_LEFTDOWN;
  1951. break;
  1952. case 6:
  1953. hat = SDL_HAT_LEFT;
  1954. break;
  1955. case 7:
  1956. hat = SDL_HAT_LEFTUP;
  1957. break;
  1958. default:
  1959. hat = SDL_HAT_CENTERED;
  1960. break;
  1961. }
  1962. SDL_SendJoystickHat(timestamp, joystick, 0, hat);
  1963. }
  1964. axis = (packet->rgucButtons[0] & 0x40) ? 32767 : -32768;
  1965. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis);
  1966. axis = ((packet->rgucButtons[0] & 0x80) || (packet->rgucButtons[1] & 0x80)) ? 32767 : -32768;
  1967. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis);
  1968. axis = ApplySimpleStickCalibration(ctx, 0, 0, packet->sJoystickLeft[0]);
  1969. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis);
  1970. axis = ApplySimpleStickCalibration(ctx, 0, 1, packet->sJoystickLeft[1]);
  1971. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis);
  1972. axis = ApplySimpleStickCalibration(ctx, 1, 0, packet->sJoystickRight[0]);
  1973. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis);
  1974. axis = ApplySimpleStickCalibration(ctx, 1, 1, packet->sJoystickRight[1]);
  1975. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, axis);
  1976. }
  1977. ctx->m_lastSimpleState = *packet;
  1978. }
  1979. static void SendSensorUpdate(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SDL_SensorType type, Uint64 sensor_timestamp, const Sint16 *values)
  1980. {
  1981. float data[3];
  1982. /* Note the order of components has been shuffled to match PlayStation controllers,
  1983. * since that's our de facto standard from already supporting those controllers, and
  1984. * users will want consistent axis mappings across devices.
  1985. */
  1986. if (type == SDL_SENSOR_GYRO || type == SDL_SENSOR_GYRO_L || type == SDL_SENSOR_GYRO_R) {
  1987. data[0] = -(ctx->m_IMUScaleData.fGyroScaleY * (float)values[1]);
  1988. data[1] = ctx->m_IMUScaleData.fGyroScaleZ * (float)values[2];
  1989. data[2] = -(ctx->m_IMUScaleData.fGyroScaleX * (float)values[0]);
  1990. } else {
  1991. data[0] = -(ctx->m_IMUScaleData.fAccelScaleY * (float)values[1]);
  1992. data[1] = ctx->m_IMUScaleData.fAccelScaleZ * (float)values[2];
  1993. data[2] = -(ctx->m_IMUScaleData.fAccelScaleX * (float)values[0]);
  1994. }
  1995. // Right Joy-Con flips some axes, so let's flip them back for consistency
  1996. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  1997. data[0] = -data[0];
  1998. data[1] = -data[1];
  1999. }
  2000. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft &&
  2001. !ctx->device->parent && !ctx->m_bVerticalMode) {
  2002. // Mini-gamepad mode, swap some axes around
  2003. float tmp = data[2];
  2004. data[2] = -data[0];
  2005. data[0] = tmp;
  2006. }
  2007. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight &&
  2008. !ctx->device->parent && !ctx->m_bVerticalMode) {
  2009. // Mini-gamepad mode, swap some axes around
  2010. float tmp = data[2];
  2011. data[2] = data[0];
  2012. data[0] = -tmp;
  2013. }
  2014. SDL_SendJoystickSensor(timestamp, joystick, type, sensor_timestamp, data, 3);
  2015. }
  2016. static void HandleCombinedControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet)
  2017. {
  2018. Sint16 axis;
  2019. if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) {
  2020. Uint8 data = packet->controllerState.rgucButtons[1];
  2021. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0));
  2022. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0));
  2023. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0));
  2024. }
  2025. if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) {
  2026. Uint8 data = packet->controllerState.rgucButtons[2];
  2027. Uint8 hat = 0;
  2028. if (data & 0x01) {
  2029. hat |= SDL_HAT_DOWN;
  2030. }
  2031. if (data & 0x02) {
  2032. hat |= SDL_HAT_UP;
  2033. }
  2034. if (data & 0x04) {
  2035. hat |= SDL_HAT_RIGHT;
  2036. }
  2037. if (data & 0x08) {
  2038. hat |= SDL_HAT_LEFT;
  2039. }
  2040. SDL_SendJoystickHat(timestamp, joystick, 0, hat);
  2041. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x10) != 0));
  2042. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x20) != 0));
  2043. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x40) != 0));
  2044. axis = (data & 0x80) ? 32767 : -32768;
  2045. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis);
  2046. }
  2047. axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8);
  2048. axis = ApplyStickCalibration(ctx, 0, 0, axis);
  2049. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis);
  2050. axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4);
  2051. axis = ApplyStickCalibration(ctx, 0, 1, axis);
  2052. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis);
  2053. }
  2054. static void HandleCombinedControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet)
  2055. {
  2056. Sint16 axis;
  2057. if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) {
  2058. Uint8 data = packet->controllerState.rgucButtons[0];
  2059. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x04) != 0));
  2060. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x08) != 0));
  2061. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x01) != 0));
  2062. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x02) != 0));
  2063. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x10) != 0));
  2064. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x20) != 0));
  2065. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x40) != 0));
  2066. axis = (data & 0x80) ? 32767 : -32768;
  2067. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis);
  2068. }
  2069. if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) {
  2070. Uint8 data = packet->controllerState.rgucButtons[1];
  2071. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  2072. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x04) != 0));
  2073. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  2074. }
  2075. axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8);
  2076. axis = ApplyStickCalibration(ctx, 1, 0, axis);
  2077. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis);
  2078. axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4);
  2079. axis = ApplyStickCalibration(ctx, 1, 1, axis);
  2080. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~axis);
  2081. }
  2082. static void HandleMiniControllerStateL(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet)
  2083. {
  2084. Sint16 axis;
  2085. if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) {
  2086. Uint8 data = packet->controllerState.rgucButtons[1];
  2087. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x01) != 0));
  2088. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0));
  2089. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x20) != 0));
  2090. }
  2091. if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) {
  2092. Uint8 data = packet->controllerState.rgucButtons[2];
  2093. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x08) != 0));
  2094. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x01) != 0));
  2095. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x02) != 0));
  2096. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x04) != 0));
  2097. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x10) != 0));
  2098. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x20) != 0));
  2099. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE1, ((data & 0x40) != 0));
  2100. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_LEFT_PADDLE2, ((data & 0x80) != 0));
  2101. }
  2102. axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8);
  2103. axis = ApplyStickCalibration(ctx, 0, 0, axis);
  2104. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis);
  2105. axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4);
  2106. axis = ApplyStickCalibration(ctx, 0, 1, axis);
  2107. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, ~axis);
  2108. }
  2109. static void HandleMiniControllerStateR(Uint64 timestamp, SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet)
  2110. {
  2111. Sint16 axis;
  2112. if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) {
  2113. Uint8 data = packet->controllerState.rgucButtons[0];
  2114. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x08) != 0));
  2115. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x02) != 0));
  2116. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x04) != 0));
  2117. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x01) != 0));
  2118. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x10) != 0));
  2119. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x20) != 0));
  2120. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE1, ((data & 0x40) != 0));
  2121. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_RIGHT_PADDLE2, ((data & 0x80) != 0));
  2122. }
  2123. if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) {
  2124. Uint8 data = packet->controllerState.rgucButtons[1];
  2125. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  2126. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x04) != 0));
  2127. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  2128. }
  2129. axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8);
  2130. axis = ApplyStickCalibration(ctx, 1, 0, axis);
  2131. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, axis);
  2132. axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4);
  2133. axis = ApplyStickCalibration(ctx, 1, 1, axis);
  2134. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis);
  2135. }
  2136. static void HandleFullControllerState(SDL_Joystick *joystick, SDL_DriverSwitch_Context *ctx, SwitchStatePacket_t *packet) SDL_NO_THREAD_SAFETY_ANALYSIS // We unlock and lock the device lock to be able to change IMU state
  2137. {
  2138. Uint64 timestamp = SDL_GetTicksNS();
  2139. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) {
  2140. if (ctx->device->parent || ctx->m_bVerticalMode) {
  2141. HandleCombinedControllerStateL(timestamp, joystick, ctx, packet);
  2142. } else {
  2143. HandleMiniControllerStateL(timestamp, joystick, ctx, packet);
  2144. }
  2145. } else if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  2146. if (ctx->device->parent || ctx->m_bVerticalMode) {
  2147. HandleCombinedControllerStateR(timestamp, joystick, ctx, packet);
  2148. } else {
  2149. HandleMiniControllerStateR(timestamp, joystick, ctx, packet);
  2150. }
  2151. } else {
  2152. Sint16 axis;
  2153. if (packet->controllerState.rgucButtons[0] != ctx->m_lastFullState.controllerState.rgucButtons[0]) {
  2154. Uint8 data = packet->controllerState.rgucButtons[0];
  2155. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_SOUTH), ((data & 0x04) != 0));
  2156. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_EAST), ((data & 0x08) != 0));
  2157. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_WEST), ((data & 0x01) != 0));
  2158. SDL_SendJoystickButton(timestamp, joystick, RemapButton(ctx, SDL_GAMEPAD_BUTTON_NORTH), ((data & 0x02) != 0));
  2159. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER, ((data & 0x40) != 0));
  2160. }
  2161. if (packet->controllerState.rgucButtons[1] != ctx->m_lastFullState.controllerState.rgucButtons[1]) {
  2162. Uint8 data = packet->controllerState.rgucButtons[1];
  2163. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_BACK, ((data & 0x01) != 0));
  2164. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_START, ((data & 0x02) != 0));
  2165. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_RIGHT_STICK, ((data & 0x04) != 0));
  2166. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_STICK, ((data & 0x08) != 0));
  2167. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_GUIDE, ((data & 0x10) != 0));
  2168. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_SWITCH_SHARE, ((data & 0x20) != 0));
  2169. }
  2170. if (packet->controllerState.rgucButtons[2] != ctx->m_lastFullState.controllerState.rgucButtons[2]) {
  2171. Uint8 data = packet->controllerState.rgucButtons[2];
  2172. Uint8 hat = 0;
  2173. if (data & 0x01) {
  2174. hat |= SDL_HAT_DOWN;
  2175. }
  2176. if (data & 0x02) {
  2177. hat |= SDL_HAT_UP;
  2178. }
  2179. if (data & 0x04) {
  2180. hat |= SDL_HAT_RIGHT;
  2181. }
  2182. if (data & 0x08) {
  2183. hat |= SDL_HAT_LEFT;
  2184. }
  2185. SDL_SendJoystickHat(timestamp, joystick, 0, hat);
  2186. SDL_SendJoystickButton(timestamp, joystick, SDL_GAMEPAD_BUTTON_LEFT_SHOULDER, ((data & 0x40) != 0));
  2187. }
  2188. axis = (packet->controllerState.rgucButtons[0] & 0x80) ? 32767 : -32768;
  2189. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHT_TRIGGER, axis);
  2190. axis = (packet->controllerState.rgucButtons[2] & 0x80) ? 32767 : -32768;
  2191. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFT_TRIGGER, axis);
  2192. axis = packet->controllerState.rgucJoystickLeft[0] | ((packet->controllerState.rgucJoystickLeft[1] & 0xF) << 8);
  2193. axis = ApplyStickCalibration(ctx, 0, 0, axis);
  2194. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTX, axis);
  2195. axis = ((packet->controllerState.rgucJoystickLeft[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickLeft[2] << 4);
  2196. axis = ApplyStickCalibration(ctx, 0, 1, axis);
  2197. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_LEFTY, ~axis);
  2198. axis = packet->controllerState.rgucJoystickRight[0] | ((packet->controllerState.rgucJoystickRight[1] & 0xF) << 8);
  2199. axis = ApplyStickCalibration(ctx, 1, 0, axis);
  2200. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTX, axis);
  2201. axis = ((packet->controllerState.rgucJoystickRight[1] & 0xF0) >> 4) | (packet->controllerState.rgucJoystickRight[2] << 4);
  2202. axis = ApplyStickCalibration(ctx, 1, 1, axis);
  2203. SDL_SendJoystickAxis(timestamp, joystick, SDL_GAMEPAD_AXIS_RIGHTY, ~axis);
  2204. }
  2205. /* High nibble of battery/connection byte is battery level, low nibble is connection status (always 0 on 8BitDo Pro 2)
  2206. * LSB of connection nibble is USB/Switch connection status
  2207. * LSB of the battery nibble is used to report charging.
  2208. * The battery level is reported from 0(empty)-8(full)
  2209. */
  2210. SDL_PowerState state;
  2211. int charging = (packet->controllerState.ucBatteryAndConnection & 0x10);
  2212. int level = (packet->controllerState.ucBatteryAndConnection & 0xE0) >> 4;
  2213. int percent = (int)SDL_roundf((level / 8.0f) * 100.0f);
  2214. if (charging) {
  2215. if (level == 8) {
  2216. state = SDL_POWERSTATE_CHARGED;
  2217. } else {
  2218. state = SDL_POWERSTATE_CHARGING;
  2219. }
  2220. } else {
  2221. state = SDL_POWERSTATE_ON_BATTERY;
  2222. }
  2223. SDL_SendJoystickPowerInfo(joystick, state, percent);
  2224. if (ctx->m_bReportSensors) {
  2225. bool bHasSensorData = (packet->imuState[0].sAccelZ != 0 ||
  2226. packet->imuState[0].sAccelY != 0 ||
  2227. packet->imuState[0].sAccelX != 0);
  2228. if (bHasSensorData) {
  2229. const Uint32 IMU_UPDATE_RATE_SAMPLE_FREQUENCY = 1000;
  2230. Uint64 sensor_timestamp[3];
  2231. ctx->m_bHasSensorData = true;
  2232. // We got three IMU samples, calculate the IMU update rate and timestamps
  2233. ctx->m_unIMUSamples += 3;
  2234. if (ctx->m_unIMUSamples >= IMU_UPDATE_RATE_SAMPLE_FREQUENCY) {
  2235. Uint64 now = SDL_GetTicksNS();
  2236. Uint64 elapsed = (now - ctx->m_ulIMUSampleTimestampNS);
  2237. if (elapsed > 0) {
  2238. ctx->m_ulIMUUpdateIntervalNS = elapsed / ctx->m_unIMUSamples;
  2239. }
  2240. ctx->m_unIMUSamples = 0;
  2241. ctx->m_ulIMUSampleTimestampNS = now;
  2242. }
  2243. ctx->m_ulTimestampNS += ctx->m_ulIMUUpdateIntervalNS;
  2244. sensor_timestamp[0] = ctx->m_ulTimestampNS;
  2245. ctx->m_ulTimestampNS += ctx->m_ulIMUUpdateIntervalNS;
  2246. sensor_timestamp[1] = ctx->m_ulTimestampNS;
  2247. ctx->m_ulTimestampNS += ctx->m_ulIMUUpdateIntervalNS;
  2248. sensor_timestamp[2] = ctx->m_ulTimestampNS;
  2249. if (!ctx->device->parent ||
  2250. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  2251. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO, sensor_timestamp[0], &packet->imuState[2].sGyroX);
  2252. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL, sensor_timestamp[0], &packet->imuState[2].sAccelX);
  2253. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO, sensor_timestamp[1], &packet->imuState[1].sGyroX);
  2254. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL, sensor_timestamp[1], &packet->imuState[1].sAccelX);
  2255. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO, sensor_timestamp[2], &packet->imuState[0].sGyroX);
  2256. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL, sensor_timestamp[2], &packet->imuState[0].sAccelX);
  2257. }
  2258. if (ctx->device->parent &&
  2259. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft) {
  2260. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_L, sensor_timestamp[0], &packet->imuState[2].sGyroX);
  2261. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_L, sensor_timestamp[0], &packet->imuState[2].sAccelX);
  2262. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_L, sensor_timestamp[1], &packet->imuState[1].sGyroX);
  2263. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_L, sensor_timestamp[1], &packet->imuState[1].sAccelX);
  2264. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_L, sensor_timestamp[2], &packet->imuState[0].sGyroX);
  2265. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_L, sensor_timestamp[2], &packet->imuState[0].sAccelX);
  2266. }
  2267. if (ctx->device->parent &&
  2268. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  2269. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_R, sensor_timestamp[0], &packet->imuState[2].sGyroX);
  2270. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_R, sensor_timestamp[0], &packet->imuState[2].sAccelX);
  2271. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_R, sensor_timestamp[1], &packet->imuState[1].sGyroX);
  2272. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_R, sensor_timestamp[1], &packet->imuState[1].sAccelX);
  2273. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_GYRO_R, sensor_timestamp[2], &packet->imuState[0].sGyroX);
  2274. SendSensorUpdate(timestamp, joystick, ctx, SDL_SENSOR_ACCEL_R, sensor_timestamp[2], &packet->imuState[0].sAccelX);
  2275. }
  2276. } else if (ctx->m_bHasSensorData) {
  2277. // Uh oh, someone turned off the IMU?
  2278. const int IMU_RESET_DELAY_MS = 3000;
  2279. Uint64 now = SDL_GetTicks();
  2280. if (now >= (ctx->m_ulLastIMUReset + IMU_RESET_DELAY_MS)) {
  2281. SDL_HIDAPI_Device *device = ctx->device;
  2282. if (device->updating) {
  2283. SDL_UnlockMutex(device->dev_lock);
  2284. }
  2285. SetIMUEnabled(ctx, true);
  2286. if (device->updating) {
  2287. SDL_LockMutex(device->dev_lock);
  2288. }
  2289. ctx->m_ulLastIMUReset = now;
  2290. }
  2291. } else {
  2292. // We have never gotten IMU data, probably not supported on this device
  2293. }
  2294. }
  2295. ctx->m_lastFullState = *packet;
  2296. }
  2297. static bool HIDAPI_DriverSwitch_UpdateDevice(SDL_HIDAPI_Device *device)
  2298. {
  2299. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  2300. SDL_Joystick *joystick = NULL;
  2301. int size;
  2302. int packet_count = 0;
  2303. Uint64 now = SDL_GetTicks();
  2304. if (device->num_joysticks > 0) {
  2305. joystick = SDL_GetJoystickFromID(device->joysticks[0]);
  2306. }
  2307. while ((size = ReadInput(ctx)) > 0) {
  2308. #ifdef DEBUG_SWITCH_PROTOCOL
  2309. HIDAPI_DumpPacket("Nintendo Switch packet: size = %d", ctx->m_rgucReadBuffer, size);
  2310. #endif
  2311. ++packet_count;
  2312. ctx->m_ulLastInput = now;
  2313. if (!joystick) {
  2314. continue;
  2315. }
  2316. if (ctx->m_bInputOnly) {
  2317. HandleInputOnlyControllerState(joystick, ctx, (SwitchInputOnlyControllerStatePacket_t *)&ctx->m_rgucReadBuffer[0]);
  2318. } else {
  2319. if (ctx->m_rgucReadBuffer[0] == k_eSwitchInputReportIDs_SubcommandReply) {
  2320. continue;
  2321. }
  2322. ctx->m_nCurrentInputMode = ctx->m_rgucReadBuffer[0];
  2323. switch (ctx->m_rgucReadBuffer[0]) {
  2324. case k_eSwitchInputReportIDs_SimpleControllerState:
  2325. HandleSimpleControllerState(joystick, ctx, (SwitchSimpleStatePacket_t *)&ctx->m_rgucReadBuffer[1]);
  2326. break;
  2327. case k_eSwitchInputReportIDs_FullControllerState:
  2328. case k_eSwitchInputReportIDs_FullControllerAndMcuState:
  2329. // This is the extended report, we can enable sensors now in auto mode
  2330. UpdateEnhancedModeOnEnhancedReport(ctx);
  2331. HandleFullControllerState(joystick, ctx, (SwitchStatePacket_t *)&ctx->m_rgucReadBuffer[1]);
  2332. break;
  2333. default:
  2334. break;
  2335. }
  2336. }
  2337. }
  2338. if (joystick) {
  2339. if (packet_count == 0) {
  2340. if (!ctx->m_bInputOnly && !device->is_bluetooth &&
  2341. ctx->device->product_id != USB_PRODUCT_NINTENDO_SWITCH_JOYCON_GRIP) {
  2342. const int INPUT_WAIT_TIMEOUT_MS = 100;
  2343. if (now >= (ctx->m_ulLastInput + INPUT_WAIT_TIMEOUT_MS)) {
  2344. // Steam may have put the controller back into non-reporting mode
  2345. bool wasSyncWrite = ctx->m_bSyncWrite;
  2346. ctx->m_bSyncWrite = true;
  2347. WriteProprietary(ctx, k_eSwitchProprietaryCommandIDs_ForceUSB, NULL, 0, false);
  2348. ctx->m_bSyncWrite = wasSyncWrite;
  2349. }
  2350. } else if (device->is_bluetooth &&
  2351. ctx->m_nCurrentInputMode != k_eSwitchInputReportIDs_SimpleControllerState) {
  2352. const int INPUT_WAIT_TIMEOUT_MS = 3000;
  2353. if (now >= (ctx->m_ulLastInput + INPUT_WAIT_TIMEOUT_MS)) {
  2354. // Bluetooth may have disconnected, try reopening the controller
  2355. size = -1;
  2356. }
  2357. }
  2358. }
  2359. if (ctx->m_bRumblePending || ctx->m_bRumbleZeroPending) {
  2360. HIDAPI_DriverSwitch_SendPendingRumble(ctx);
  2361. } else if (ctx->m_bRumbleActive &&
  2362. now >= (ctx->m_ulRumbleSent + RUMBLE_REFRESH_FREQUENCY_MS)) {
  2363. #ifdef DEBUG_RUMBLE
  2364. SDL_Log("Sent continuing rumble, %d ms after previous rumble", now - ctx->m_ulRumbleSent);
  2365. #endif
  2366. WriteRumble(ctx);
  2367. }
  2368. }
  2369. // Reconnect the Bluetooth device once the USB device is gone
  2370. if (device->num_joysticks == 0 && device->is_bluetooth && packet_count > 0 &&
  2371. !device->parent &&
  2372. !HIDAPI_HasConnectedUSBDevice(device->serial)) {
  2373. HIDAPI_JoystickConnected(device, NULL);
  2374. }
  2375. if (size < 0 && device->num_joysticks > 0) {
  2376. // Read error, device is disconnected
  2377. HIDAPI_JoystickDisconnected(device, device->joysticks[0]);
  2378. }
  2379. return (size >= 0);
  2380. }
  2381. static void HIDAPI_DriverSwitch_CloseJoystick(SDL_HIDAPI_Device *device, SDL_Joystick *joystick)
  2382. {
  2383. SDL_DriverSwitch_Context *ctx = (SDL_DriverSwitch_Context *)device->context;
  2384. if (!ctx->m_bInputOnly) {
  2385. // Restore simple input mode for other applications
  2386. if (!ctx->m_nInitialInputMode ||
  2387. ctx->m_nInitialInputMode == k_eSwitchInputReportIDs_SimpleControllerState) {
  2388. SetInputMode(ctx, k_eSwitchInputReportIDs_SimpleControllerState);
  2389. }
  2390. }
  2391. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_ENHANCED_REPORTS,
  2392. SDL_EnhancedReportsChanged, ctx);
  2393. if (ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConLeft ||
  2394. ctx->m_eControllerType == k_eSwitchDeviceInfoControllerType_JoyConRight) {
  2395. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_JOYCON_HOME_LED,
  2396. SDL_HomeLEDHintChanged, ctx);
  2397. } else {
  2398. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED,
  2399. SDL_HomeLEDHintChanged, ctx);
  2400. }
  2401. SDL_RemoveHintCallback(SDL_HINT_JOYSTICK_HIDAPI_SWITCH_PLAYER_LED,
  2402. SDL_PlayerLEDHintChanged, ctx);
  2403. ctx->joystick = NULL;
  2404. ctx->m_bReportSensors = false;
  2405. ctx->m_bEnhancedMode = false;
  2406. ctx->m_bEnhancedModeAvailable = false;
  2407. }
  2408. static void HIDAPI_DriverSwitch_FreeDevice(SDL_HIDAPI_Device *device)
  2409. {
  2410. }
  2411. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverNintendoClassic = {
  2412. SDL_HINT_JOYSTICK_HIDAPI_NINTENDO_CLASSIC,
  2413. true,
  2414. HIDAPI_DriverNintendoClassic_RegisterHints,
  2415. HIDAPI_DriverNintendoClassic_UnregisterHints,
  2416. HIDAPI_DriverNintendoClassic_IsEnabled,
  2417. HIDAPI_DriverNintendoClassic_IsSupportedDevice,
  2418. HIDAPI_DriverSwitch_InitDevice,
  2419. HIDAPI_DriverSwitch_GetDevicePlayerIndex,
  2420. HIDAPI_DriverSwitch_SetDevicePlayerIndex,
  2421. HIDAPI_DriverSwitch_UpdateDevice,
  2422. HIDAPI_DriverSwitch_OpenJoystick,
  2423. HIDAPI_DriverSwitch_RumbleJoystick,
  2424. HIDAPI_DriverSwitch_RumbleJoystickTriggers,
  2425. HIDAPI_DriverSwitch_GetJoystickCapabilities,
  2426. HIDAPI_DriverSwitch_SetJoystickLED,
  2427. HIDAPI_DriverSwitch_SendJoystickEffect,
  2428. HIDAPI_DriverSwitch_SetJoystickSensorsEnabled,
  2429. HIDAPI_DriverSwitch_CloseJoystick,
  2430. HIDAPI_DriverSwitch_FreeDevice,
  2431. };
  2432. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverJoyCons = {
  2433. SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS,
  2434. true,
  2435. HIDAPI_DriverJoyCons_RegisterHints,
  2436. HIDAPI_DriverJoyCons_UnregisterHints,
  2437. HIDAPI_DriverJoyCons_IsEnabled,
  2438. HIDAPI_DriverJoyCons_IsSupportedDevice,
  2439. HIDAPI_DriverSwitch_InitDevice,
  2440. HIDAPI_DriverSwitch_GetDevicePlayerIndex,
  2441. HIDAPI_DriverSwitch_SetDevicePlayerIndex,
  2442. HIDAPI_DriverSwitch_UpdateDevice,
  2443. HIDAPI_DriverSwitch_OpenJoystick,
  2444. HIDAPI_DriverSwitch_RumbleJoystick,
  2445. HIDAPI_DriverSwitch_RumbleJoystickTriggers,
  2446. HIDAPI_DriverSwitch_GetJoystickCapabilities,
  2447. HIDAPI_DriverSwitch_SetJoystickLED,
  2448. HIDAPI_DriverSwitch_SendJoystickEffect,
  2449. HIDAPI_DriverSwitch_SetJoystickSensorsEnabled,
  2450. HIDAPI_DriverSwitch_CloseJoystick,
  2451. HIDAPI_DriverSwitch_FreeDevice,
  2452. };
  2453. SDL_HIDAPI_DeviceDriver SDL_HIDAPI_DriverSwitch = {
  2454. SDL_HINT_JOYSTICK_HIDAPI_SWITCH,
  2455. true,
  2456. HIDAPI_DriverSwitch_RegisterHints,
  2457. HIDAPI_DriverSwitch_UnregisterHints,
  2458. HIDAPI_DriverSwitch_IsEnabled,
  2459. HIDAPI_DriverSwitch_IsSupportedDevice,
  2460. HIDAPI_DriverSwitch_InitDevice,
  2461. HIDAPI_DriverSwitch_GetDevicePlayerIndex,
  2462. HIDAPI_DriverSwitch_SetDevicePlayerIndex,
  2463. HIDAPI_DriverSwitch_UpdateDevice,
  2464. HIDAPI_DriverSwitch_OpenJoystick,
  2465. HIDAPI_DriverSwitch_RumbleJoystick,
  2466. HIDAPI_DriverSwitch_RumbleJoystickTriggers,
  2467. HIDAPI_DriverSwitch_GetJoystickCapabilities,
  2468. HIDAPI_DriverSwitch_SetJoystickLED,
  2469. HIDAPI_DriverSwitch_SendJoystickEffect,
  2470. HIDAPI_DriverSwitch_SetJoystickSensorsEnabled,
  2471. HIDAPI_DriverSwitch_CloseJoystick,
  2472. HIDAPI_DriverSwitch_FreeDevice,
  2473. };
  2474. #endif // SDL_JOYSTICK_HIDAPI_SWITCH
  2475. #endif // SDL_JOYSTICK_HIDAPI