wii_i2c.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. //----------------------------------------------------------------------------- ----------------------------------------
  2. // Biblio: [standing on the shoulders of giants]
  3. // https://bootlin.com/labs/doc/nunchuk.pdf
  4. // https://www.hackster.io/infusion/using-a-wii-nunchuk-with-arduino-597254#toc-i2c-protocol-9
  5. // https://web.archive.org/web/20220000000000*/https://www.hackster.io/infusion/using-a-wii-nunchuk-with-arduino-597254
  6. // https://github.com/madhephaestus/WiiChuck/blob/master/src/Accessory.cpp#L14
  7. // https://wiibrew.org/wiki/Wiimote/Extension_Controllers
  8. // https://www.best-microcontroller-projects.com/i2c-tutorial.html
  9. //
  10. // WiiMote Extension Controller:
  11. // Bus Address : 0x52
  12. // Register autoincrements after each (byte is) read
  13. // 0x00..0x05 ( 6 bytes) ... [r] Controller Data
  14. // 0x20..0x2F (16 bytes) ... [r] Calibration Data
  15. // 0x30..0x3F (16 bytes) ... [r] (A copy of the) Calibration Data
  16. // 0x40..0x4F (16 bytes) ... [w] Encryption key(s)
  17. // 0xFA..0xFF ( 6 bytes) ... [r] Perhipheral ID
  18. //----------------------------------------------------------------------------- ----------------------------------------
  19. #include <stdlib.h>
  20. #include <stdint.h>
  21. #include <stdbool.h>
  22. #include <furi.h>
  23. #include <furi_hal.h>
  24. #include <furi_hal_i2c.h>
  25. #include "i2c_workaround.h" //! temporary workaround for a bug in furi i2c [see header]
  26. #include "wii_anal.h"
  27. #include "wii_i2c.h"
  28. #include "wii_ec.h"
  29. #include "bc_logging.h"
  30. //----------------------------------------------------------------------------- ----------------------------------------
  31. // Wii Extension Controller i2c Bus address
  32. static const uint8_t ec_i2cAddr = 0x52;
  33. // Initialise for UNencrypted comms
  34. static const uint8_t regInit1 = 0xF0;
  35. static const uint8_t regInit2 = 0xFB;
  36. static const uint8_t cmdInit1[] = {regInit1, 0x55};
  37. static const uint8_t cmdInit2[] = {regInit2, 0x00};
  38. // Initialise for ENcrypted comms
  39. static const uint8_t regInitEnc = 0x40;
  40. static const uint8_t cmdInitEnc[] = {regInitEnc, 0x00};
  41. // Crypto key (PSK), base register : {0x40..0x4F}[2][8]
  42. static const uint8_t regEnc = 0x40; // ENC_LEN
  43. // Controller State data, base register : {0x00..0x05}[6]
  44. static const uint8_t regJoy = 0x00; // JOY_LEN
  45. // Calibration data, base register : {0x20..0x2F}[16]
  46. static const uint8_t regCal = 0x20; // CAL_LEN
  47. // Controller ID, base register : {0xFA..0xFF}[6]
  48. static const uint8_t regPid = 0xFA; // PID_LEN
  49. //+============================================================================ ========================================
  50. // Hexdump a buffer to the logfile
  51. //
  52. #if LOG_LEVEL >= 4 // INFO
  53. static void dump(const uint8_t* buf, const unsigned int len, const char* id) {
  54. // snprintf() would be useful!
  55. char s[128] = {0};
  56. char* p = NULL;
  57. strcpy(s, id);
  58. p = s + strlen(s);
  59. *p++ = ':';
  60. *p++ = ' ';
  61. *p++ = '{';
  62. for(unsigned int i = 0; i < len; i++) {
  63. uint8_t hi = (buf[i] & 0xF0) >> 4;
  64. uint8_t lo = (buf[i] & 0x0F);
  65. hi = hi + ((hi > 9) ? ('A' - 10) : '0');
  66. lo = lo + ((lo > 9) ? ('A' - 10) : '0');
  67. *p++ = (char)hi;
  68. *p++ = (char)lo;
  69. *p++ = ',';
  70. }
  71. *p = '\0';
  72. *--p = '}';
  73. INFO(s);
  74. }
  75. #else
  76. #define dump(...)
  77. #endif
  78. //+============================================================================ ========================================
  79. //
  80. //! -W-A-R-N-I-N-G- : THIS ENCRYPTION CODE SHOULD NEVER BE REQUIRED ... AS SUCH, I'VE NEVER TESTED IT
  81. //
  82. static void decrypt(uint8_t* buf, const uint8_t* encKey, const uint8_t reg, unsigned int len) {
  83. #if 1 // Use standard algorithm
  84. // decrypted_byte = (encrypted_byte XOR encKey[1][address%8]) + encKey[2][address%8]
  85. for(uint8_t* p = buf; p < buf + len; p++)
  86. *p = (*p ^ encKey[(reg + (p - buf)) % 8]) + encKey[8 + ((reg + (p - buf)) % 8)];
  87. #else //! This is (I think) a shortcut for an all-zero key [not tested]
  88. (void)encKey;
  89. (void)reg;
  90. for(uint8_t* p = buf; p < buf + len; p++)
  91. *p = (*p ^ 0x17) + 0x17;
  92. #endif
  93. }
  94. //+============================================================================ ========================================
  95. // Read the Extension Controller state
  96. // ...and decode it in to something sane
  97. //
  98. // Returns: {0:OK, >0:Error}
  99. //
  100. int ecRead(wiiEC_t* pec) {
  101. ENTER;
  102. int rv = 0; // assume success
  103. if(!pec->init) {
  104. WARN("%s : device not initialised", __func__);
  105. rv = 1;
  106. goto bail;
  107. }
  108. if(!furi_hal_i2c_is_device_ready(i2cBus, i2cAddr, i2cTimeout)) {
  109. INFO("%s : device disconnected", __func__);
  110. pec->init = false;
  111. rv = 2;
  112. goto bail;
  113. }
  114. if(!furi_hal_i2c_trxd(
  115. i2cBus, i2cAddr, &regJoy, 1, pec->joy, JOY_LEN, i2cTimeout, i2cReadWait)) {
  116. ERROR("%s : trxd fail", __func__);
  117. rv = 3;
  118. goto bail;
  119. }
  120. if(pec->encrypt) decrypt(pec->joy, pec->encKey, regJoy, JOY_LEN);
  121. // Decode the readings (according to Controller type)
  122. ecDecode(pec);
  123. bail:
  124. LEAVE;
  125. return rv;
  126. }
  127. //+============================================================================ ========================================
  128. // Initialise an Extension Controller
  129. //
  130. //! To disable encryption, pass a NULL encryption key <-- this is currently ALWAYS the case
  131. //
  132. bool ecInit(wiiEC_t* pec, const uint8_t* encKey) {
  133. ENTER;
  134. bool rv = false; // assume failure
  135. #if 0 //! i2c workaround
  136. //! I think this is done during OS startup - long before the plugin starts
  137. furi_hal_i2c_init();
  138. #endif
  139. #if 0 //! i2c workaround
  140. // May become relevant when the i2c issues are resolved
  141. // Take control of the i2c bus [which returns void !?]
  142. // --> targets/f7/furi_hal/furi_hal_i2c.c
  143. furi_hal_i2c_acquire(i2cBus);
  144. #endif
  145. pec->init = false; // assume failure
  146. // === See if the device is alive ===
  147. if(!furi_hal_i2c_is_device_ready(i2cBus, i2cAddr, i2cTimeout)) {
  148. TRACE("%s : waiting for device", __func__);
  149. goto bail;
  150. }
  151. INFO("%s : device connected", __func__);
  152. // === Initialise the device ===
  153. pec->init = false; // This goes true AFTER the (optional) controller-specific init code
  154. // === Start the Extension Controller ===
  155. if(encKey) { //! start in encrypted mode
  156. //! todo - should this happen here, or AFTER we've got the ID ?
  157. } else {
  158. if(!furi_hal_i2c_tx(i2cBus, i2cAddr, cmdInit1, sizeof(cmdInit1), i2cTimeout)) {
  159. ERROR("%s : init fail (dec1)", __func__);
  160. goto bail;
  161. }
  162. TRACE("%s : init OK1", __func__);
  163. if(!furi_hal_i2c_tx(i2cBus, i2cAddr, cmdInit2, sizeof(cmdInit2), i2cTimeout)) {
  164. ERROR("%s : init fail (dec2)", __func__);
  165. goto bail;
  166. }
  167. TRACE("%s : init OK2", __func__);
  168. }
  169. // === Retrieve the Extension Controller ID ===
  170. if(!furi_hal_i2c_trx(i2cBus, i2cAddr, &regPid, 1, pec->pid, PID_LEN, i2cTimeout)) {
  171. ERROR("%s : T(R)x fail (pid)", __func__);
  172. goto bail;
  173. }
  174. if(pec->encrypt) decrypt(pec->joy, pec->encKey, regJoy, JOY_LEN);
  175. dump(pec->pid, PID_LEN, "pid"); // debug INFO
  176. // Find the StringID in the lookup table
  177. for(pec->pidx = PID_FIRST; pec->pidx < PID_ERROR; pec->pidx++)
  178. if(memcmp(pec->pid, ecId[pec->pidx].id, PID_LEN) == 0) break;
  179. if(pec->pidx == PID_ERROR) pec->pidx = PID_UNKNOWN;
  180. pec->sid = ecId[pec->pidx].name;
  181. INFO("sid: %s", pec->sid);
  182. // === (optionally) Enable encryption ===
  183. if(!encKey) {
  184. pec->encrypt = false;
  185. } else { // Controller WILL encrypt ALL tranmissions
  186. //! this encryption code fails - should it be done earlier?
  187. //! as it is probably never of any use, I'm kinda loathed to spend time on it
  188. //! https://github.com/madhephaestus/WiiChuck/blob/master/src/Accessory.cpp#L138
  189. uint8_t encTx[1 + ENC_LEN] = {0};
  190. uint8_t* ep = encTx;
  191. pec->encrypt = true;
  192. // ** Start the Controller in ENcrytped mode
  193. if(!furi_hal_i2c_tx(i2cBus, i2cAddr, cmdInitEnc, sizeof(cmdInitEnc), i2cTimeout)) {
  194. ERROR("%s : init fail (enc)", __func__);
  195. goto bail;
  196. }
  197. // Copy the (symmetric) encryption key to the controller state table
  198. if(pec->encKey != encKey) memcpy(pec->encKey, encKey, ENC_LEN);
  199. // Build the encryption key packet
  200. *ep++ = regEnc;
  201. memcpy(ep, pec->encKey, ENC_LEN);
  202. // ** Send encryption key (PSK)
  203. if(!furi_hal_i2c_tx(i2cBus, i2cAddr, encTx, (1 + ENC_LEN), i2cTimeout)) {
  204. ERROR("%s : key fail", __func__);
  205. goto bail;
  206. }
  207. TRACE("%s : init OK (enc)", __func__);
  208. }
  209. // === Some devices [eg. Drawsome/uDraw] require additional init code ===
  210. if(ecId[pec->init].init && (ecId[pec->init].init(pec) == false)) goto bail;
  211. pec->init = true;
  212. // === Read calibration data ===
  213. if(!furi_hal_i2c_trx(i2cBus, i2cAddr, &regCal, 1, pec->calF, CAL_LEN, i2cTimeout)) {
  214. ERROR("%s : trx fail (cal)", __func__);
  215. goto bail;
  216. }
  217. if(pec->encrypt) decrypt(pec->joy, pec->encKey, regJoy, JOY_LEN);
  218. dump(pec->calF, CAL_LEN, "cal");
  219. ecCalibrate(pec, CAL_RESET | CAL_FACTORY); // Load factory default calibration
  220. // === Initialise decode buffers ===
  221. pec->decN = 0; // read in to decode[1] (yes, N=0 -> read in to dec[1])
  222. switch(ecRead(pec)) {
  223. case 0: // read OK
  224. memcpy(&pec->dec[0], &pec->dec[1], sizeof(pec->dec[0]));
  225. dump(pec->joy, JOY_LEN, "joy");
  226. break;
  227. default: // bug: unknown
  228. case 1: // bug: not initialised - should never happen
  229. ERROR("%s : read bug", __func__);
  230. break;
  231. case 2: // device gone
  232. case 3: // read fail
  233. // Logging done by ecRead()
  234. pec->init = false;
  235. goto bail;
  236. }
  237. rv = true; // yay :)
  238. bail:
  239. #if 0 //! i2c workaround
  240. furi_hal_i2c_release(i2cBus);
  241. #endif
  242. LEAVE;
  243. return rv;
  244. }