wii_anal.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. //----------------------------------------------------------------------------- ----------------------------------------
  2. // Includes
  3. //
  4. // System libs
  5. #include <stdlib.h> // malloc
  6. #include <stdint.h> // uint32_t
  7. #include <stdarg.h> // __VA_ARGS__
  8. #include <stdio.h>
  9. #include <ctype.h>
  10. // FlipperZero libs
  11. #include <furi.h> // Core API
  12. #include <gui/gui.h> // GUI (screen/keyboard) API
  13. #include <input/input.h> // GUI Input extensions
  14. #include <notification/notification_messages.h>
  15. // Do this first!
  16. #define ERR_C_ // Do this in precisely ONE file
  17. #include "err.h" // Error numbers & messages
  18. #include "bc_logging.h"
  19. // Local headers
  20. #include "wii_anal.h" // Various enums and struct declarations
  21. #include "wii_i2c.h" // Wii i2c functions
  22. #include "wii_ec.h" // Wii Extension Controller functions (eg. draw)
  23. #include "wii_anal_keys.h" // key mappings
  24. #include "gfx/images.h" // Images
  25. #include "wii_anal_lcd.h" // Drawing functions
  26. #include "wii_anal_ec.h" // Wii controller events
  27. #include "wii_anal_ver.h" // Version number
  28. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  29. // OOOOO // SSSSS CCCCC AAA L L BBBB AAA CCCC K K SSSSS
  30. // O O /// S C A A L L B B A A C K K S
  31. // O O /// SSSSS C AAAAA L L BBBB AAAAA C KKK SSSSS
  32. // O O /// S C A A L L B B A A C K K S
  33. // OOOOO // SSSSS CCCCC A A LLLLL LLLLL BBBB A A CCCC K K SSSSS
  34. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  35. //+============================================================================ ========================================
  36. // OS Callback : Timer tick
  37. // We register this function to be called when the OS signals a timer 'tick' event
  38. //
  39. static
  40. void cbTimer (FuriMessageQueue* queue)
  41. {
  42. ENTER;
  43. furi_assert(queue);
  44. eventMsg_t message = {.id = EVID_TICK};
  45. furi_message_queue_put(queue, &message, 0);
  46. LEAVE;
  47. return;
  48. }
  49. //+============================================================================ ========================================
  50. // OS Callback : Keypress
  51. // We register this function to be called when the OS detects a keypress
  52. //
  53. static
  54. void cbInput (InputEvent* event, FuriMessageQueue* queue)
  55. {
  56. ENTER;
  57. furi_assert(queue);
  58. furi_assert(event);
  59. // Put an "input" event message on the message queue
  60. eventMsg_t message = {.id = EVID_KEY, .input = *event};
  61. furi_message_queue_put(queue, &message, FuriWaitForever);
  62. LEAVE;
  63. return;
  64. }
  65. //+============================================================================
  66. // Show version number
  67. //
  68. static
  69. void showVer (Canvas* const canvas)
  70. {
  71. show(canvas, 0,59, &img_3x5_v, SHOW_SET_BLK);
  72. show(canvas, 4,59, VER_MAJ, SHOW_SET_BLK);
  73. canvas_draw_frame(canvas, 8,62, 2,2);
  74. show(canvas, 11,59, VER_MIN, SHOW_SET_BLK);
  75. }
  76. //+============================================================================
  77. // OS Callback : Draw request
  78. // We register this function to be called when the OS requests that the screen is redrawn
  79. //
  80. // We actually instruct the OS to perform this request, after we update the interface
  81. // I guess it's possible that this instruction may able be issued by other threads !?
  82. //
  83. static
  84. void cbDraw (Canvas* const canvas, void* ctx)
  85. {
  86. ENTER;
  87. furi_assert(canvas);
  88. furi_assert(ctx);
  89. state_t* state = NULL;
  90. // Try to acquire the mutex for the plugin state variables, timeout = 25mS
  91. if ( !(state = (state_t*)acquire_mutex((ValueMutex*)ctx, 25)) ) return ;
  92. switch (state->scene) {
  93. //---------------------------------------------------------------------
  94. case SCENE_SPLASH:
  95. show(canvas, 2,0, &img_csLogo_FULL, SHOW_SET_BLK);
  96. canvas_set_font(canvas, FontSecondary);
  97. canvas_draw_str_aligned(canvas, 64,43, AlignCenter, AlignTop, "Wii Extension Controller");
  98. canvas_draw_str_aligned(canvas, 64,55, AlignCenter, AlignTop, "Protocol Analyser");
  99. showVer(canvas);
  100. break;
  101. //---------------------------------------------------------------------
  102. case SCENE_RIP:
  103. show(canvas, 0,0, &img_RIP, SHOW_SET_BLK);
  104. break;
  105. //---------------------------------------------------------------------
  106. case SCENE_WAIT:
  107. # define xo 2
  108. show(canvas, 3+xo,10, &img_ecp_port, SHOW_SET_BLK);
  109. BOX_TL(22+xo, 6, 82+xo,23); // 3v3
  110. BOX_TL(48+xo,21, 82+xo,23); // C1
  111. BOX_BL(22+xo,41, 82+xo,58); // C0
  112. BOX_BL(48+xo,41, 82+xo,44); // Gnd
  113. show(canvas, 90+xo, 3, &img_6x8_3, SHOW_SET_BLK); // 3v3
  114. show(canvas, 97+xo, 3, &img_6x8_v, SHOW_SET_BLK);
  115. show(canvas, 104+xo, 3, &img_6x8_3, SHOW_SET_BLK);
  116. show(canvas, 90+xo,18, &img_6x8_C, SHOW_SET_BLK); // C1 <->
  117. show(canvas, 98+xo,18, &img_6x8_1, SHOW_SET_BLK);
  118. show(canvas, 107+xo,16, &img_ecp_SDA, SHOW_SET_BLK);
  119. show(canvas, 90+xo,40, &img_6x8_G, SHOW_SET_BLK); // Gnd
  120. show(canvas, 97+xo,40, &img_6x8_n, SHOW_SET_BLK);
  121. show(canvas, 104+xo,40, &img_6x8_d, SHOW_SET_BLK);
  122. show(canvas, 90+xo,54, &img_6x8_C, SHOW_SET_BLK); // C0 _-_-
  123. show(canvas, 98+xo,54, &img_6x8_0, SHOW_SET_BLK);
  124. show(canvas, 108+xo,54, &img_ecp_SCL, SHOW_SET_BLK);
  125. show(canvas, 0,0, &img_csLogo_Small, SHOW_SET_BLK);
  126. showVer(canvas);
  127. # undef xo
  128. break;
  129. //---------------------------------------------------------------------
  130. case SCENE_DEBUG:
  131. canvas_set_font(canvas, FontSecondary);
  132. show(canvas, 0,0, &img_key_U, SHOW_SET_BLK);
  133. canvas_draw_str_aligned(canvas, 11, 0, AlignLeft, AlignTop, "Initialise Perhipheral");
  134. show(canvas, 0,11, &img_key_OK, SHOW_SET_BLK);
  135. canvas_draw_str_aligned(canvas, 11,11, AlignLeft, AlignTop, "Read values [see log]");
  136. show(canvas, 0,23, &img_key_D, SHOW_SET_BLK);
  137. canvas_draw_str_aligned(canvas, 11,22, AlignLeft, AlignTop, "Restart Scanner");
  138. show(canvas, 0,33, &img_key_Back, SHOW_SET_BLK);
  139. canvas_draw_str_aligned(canvas, 11,33, AlignLeft, AlignTop, "Exit");
  140. break ;
  141. //---------------------------------------------------------------------
  142. default:
  143. if (state->ec.pidx >= PID_ERROR) {
  144. ERROR("%s : bad PID = %d", __func__, state->ec.pidx);
  145. } else {
  146. if ((state->scene == SCENE_DUMP) || !ecId[state->ec.pidx].show)
  147. ecId[PID_UNKNOWN].show(canvas, state);
  148. else
  149. ecId[state->ec.pidx].show(canvas, state);
  150. }
  151. break;
  152. }
  153. // Release the mutex
  154. release_mutex((ValueMutex*)ctx, state);
  155. LEAVE;
  156. return;
  157. }
  158. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  159. // SSSSS TTTTT AAA TTTTT EEEEE V V AAA RRRR IIIII AAA BBBB L EEEEE SSSSS
  160. // S T A A T E V V A A R R I A A B B L E S
  161. // SSSSS T AAAAA T EEE V V AAAAA RRRR I AAAAA BBBB L EEE SSSSS
  162. // S T A A T E V V A A R R I A A B B L E S
  163. // SSSSS T A A T EEEEE V A A R R IIIII A A BBBB LLLLL EEEEE SSSSS
  164. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  165. //+============================================================================ ========================================
  166. // Initialise plugin state variables
  167. //
  168. static inline
  169. bool stateInit (state_t* const state)
  170. {
  171. ENTER;
  172. furi_assert(state);
  173. bool rv = true; // assume success
  174. // Enable the main loop
  175. state->run = true;
  176. // Timer
  177. state->timerEn = false;
  178. state->timer = NULL;
  179. state->timerHz = furi_kernel_get_tick_frequency();
  180. state->fps = 30;
  181. // Scene
  182. state->scene = SCENE_SPLASH;
  183. state->scenePrev = SCENE_NONE;
  184. state->scenePegg = SCENE_NONE;
  185. state->hold = 0; // show hold meters (-1=lowest, 0=current, +1=highest}
  186. state->calib = CAL_TRACK;
  187. state->pause = false; // animation running
  188. state->apause = false; // auto-pause animation
  189. // Notifications
  190. state->notify = NULL;
  191. // Perhipheral
  192. state->ec.init = false;
  193. state->ec.pidx = PID_UNKNOWN;
  194. state->ec.sid = ecId[state->ec.pidx].name;
  195. // Controller data
  196. memset(state->ec.pid, 0xC5, PID_LEN); // Cyborg 5ystems
  197. memset(state->ec.calF, 0xC5, CAL_LEN);
  198. memset(state->ec.joy, 0xC5, JOY_LEN);
  199. // Encryption details
  200. state->ec.encrypt = false;
  201. memset(state->ec.encKey, 0x00, ENC_LEN);
  202. // Seed the PRNG
  203. // CYCCNT --> lib/STM32CubeWB/Drivers/CMSIS/Include/core_cm7.h
  204. // srand(DWT->CYCCNT);
  205. LEAVE;
  206. return rv;
  207. }
  208. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  209. // MM MM AAA IIIII N N
  210. // M M M A A I NN N
  211. // M M M AAAAA I N N N
  212. // M M A A I N NN
  213. // M M A A IIIII N N
  214. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  215. //+============================================================================ ========================================
  216. // Enable/Disable scanning
  217. //
  218. void timerEn (state_t* state, bool on)
  219. {
  220. ENTER;
  221. furi_assert(state);
  222. // ENable scanning
  223. if (on) {
  224. if (state->timerEn) {
  225. WARN(wii_errs[WARN_SCAN_START]);
  226. } else {
  227. // Set the timer to fire at 'fps' times/second
  228. if (furi_timer_start(state->timer, state->timerHz/state->fps) == FuriStatusOk) {
  229. state->timerEn = true;
  230. INFO("%s : monitor started", __func__);
  231. } else {
  232. ERROR(wii_errs[ERR_TIMER_START]);
  233. }
  234. }
  235. // DISable scanning
  236. } else {
  237. if (!state->timerEn) {
  238. WARN(wii_errs[WARN_SCAN_STOP]);
  239. } else {
  240. // Stop the timer
  241. if (furi_timer_stop(state->timer) == FuriStatusOk) {
  242. state->timerEn = false;
  243. INFO("%s : monitor stopped", __func__);
  244. } else {
  245. ERROR(wii_errs[ERR_TIMER_STOP]);
  246. }
  247. }
  248. }
  249. LEAVE;
  250. return;
  251. }
  252. //+============================================================================ ========================================
  253. // Plugin entry point
  254. //
  255. int32_t wii_ec_anal (void)
  256. {
  257. ENTER;
  258. // ===== Variables =====
  259. err_t error = 0; // assume success
  260. Gui* gui = NULL;
  261. ViewPort* vpp = NULL;
  262. state_t* state = NULL;
  263. ValueMutex mutex = {0};
  264. FuriMessageQueue* queue = NULL;
  265. const uint32_t queueSz = 20; // maximum messages in queue
  266. uint32_t tmo = (3.5f *1000); // timeout splash screen after N seconds
  267. // The queue will contain plugin event-messages
  268. // --> local
  269. eventMsg_t msg = {0};
  270. INFO("BEGIN");
  271. // ===== Message queue =====
  272. // 1. Create a message queue (for up to 8 (keyboard) event messages)
  273. if ( !(queue = furi_message_queue_alloc(queueSz, sizeof(msg))) ) {
  274. ERROR(wii_errs[(error = ERR_MALLOC_QUEUE)]);
  275. goto bail;
  276. }
  277. // ===== Create GUI Interface =====
  278. // 2. Create a GUI interface
  279. if ( !(gui = furi_record_open("gui")) ) {
  280. ERROR(wii_errs[(error = ERR_NO_GUI)]);
  281. goto bail;
  282. }
  283. // ===== Plugin state variables =====
  284. // 3. Allocate space on the heap for the plugin state variables
  285. if ( !(state = malloc(sizeof(state_t))) ) {
  286. ERROR(wii_errs[(error = ERR_MALLOC_STATE)]);
  287. goto bail;
  288. }
  289. // 4. Initialise the plugin state variables
  290. if (!stateInit(state)) {
  291. // error message(s) is/are output by stateInit()
  292. error = 15;
  293. goto bail;
  294. }
  295. // 5. Create a mutex for (reading/writing) the plugin state variables
  296. if (!init_mutex(&mutex, state, sizeof(state))) {
  297. ERROR(wii_errs[(error = ERR_NO_MUTEX)]);
  298. goto bail;
  299. }
  300. // ===== Viewport =====
  301. // 6. Allocate space on the heap for the viewport
  302. if ( !(vpp = view_port_alloc()) ) {
  303. ERROR(wii_errs[(error = ERR_MALLOC_VIEW)]);
  304. goto bail;
  305. }
  306. // 7a. Register a callback for input events
  307. view_port_input_callback_set(vpp, cbInput, queue);
  308. // 7b. Register a callback for draw events
  309. view_port_draw_callback_set(vpp, cbDraw, &mutex);
  310. // ===== Start GUI Interface =====
  311. // 8. Attach the viewport to the GUI
  312. gui_add_view_port(gui, vpp, GuiLayerFullscreen);
  313. // ===== Timer =====
  314. // 9. Allocate a timer
  315. if ( !(state->timer = furi_timer_alloc(cbTimer, FuriTimerTypePeriodic, queue)) ) {
  316. ERROR(wii_errs[(error = ERR_NO_TIMER)]);
  317. goto bail;
  318. }
  319. // === System Notifications ===
  320. // 10. Acquire a handle for the system notification queue
  321. if ( !(state->notify = furi_record_open(RECORD_NOTIFICATION)) ) {
  322. ERROR(wii_errs[(error = ERR_NO_NOTIFY)]);
  323. goto bail;
  324. }
  325. patBacklight(state); // Turn on the backlight [qv. remote FAP launch]
  326. INFO("INITIALISED");
  327. // ==================== Main event loop ====================
  328. if (state->run) do {
  329. bool redraw = false;
  330. FuriStatus status = FuriStatusErrorTimeout;
  331. // Wait for a message
  332. // while ((status = furi_message_queue_get(queue, &msg, tmo)) == FuriStatusErrorTimeout) ;
  333. status = furi_message_queue_get(queue, &msg, tmo);
  334. // Clear splash screen
  335. if ( (state->scene == SCENE_SPLASH) && (state->scenePrev == SCENE_NONE) && // Initial splash
  336. ( (status == FuriStatusErrorTimeout) || // timeout
  337. ((msg.id == EVID_KEY) && (msg.input.type == InputTypeShort)) ) // or <any> key-short
  338. ) {
  339. tmo = 60 *1000; // increase message-wait timeout to 60secs
  340. timerEn(state, true); // start scanning the i2c bus
  341. status = FuriStatusOk; // pass status check
  342. msg.id = EVID_NONE; // valid msg ID
  343. sceneSet(state, SCENE_WAIT); // move to wait screen
  344. }
  345. // Check for queue errors
  346. if (status != FuriStatusOk) {
  347. switch (status) {
  348. case FuriStatusErrorTimeout: DEBUG(wii_errs[DEBUG_QUEUE_TIMEOUT]); continue ;
  349. case FuriStatusError: ERROR(wii_errs[(error = ERR_QUEUE_RTOS)]); goto bail ;
  350. case FuriStatusErrorResource: ERROR(wii_errs[(error = ERR_QUEUE_RESOURCE)]); goto bail ;
  351. case FuriStatusErrorParameter: ERROR(wii_errs[(error = ERR_QUEUE_BADPRM)]); goto bail ;
  352. case FuriStatusErrorNoMemory: ERROR(wii_errs[(error = ERR_QUEUE_NOMEM)]); goto bail ;
  353. case FuriStatusErrorISR: ERROR(wii_errs[(error = ERR_QUEUE_ISR)]); goto bail ;
  354. default: ERROR(wii_errs[(error = ERR_QUEUE_UNK)]); goto bail ;
  355. }
  356. }
  357. // Read successful
  358. // *** Try to lock the plugin state variables ***
  359. if ( !(state = (state_t*)acquire_mutex_block(&mutex)) ) {
  360. ERROR(wii_errs[(error = ERR_MUTEX_BLOCK)]);
  361. goto bail;
  362. }
  363. // *** Handle events ***
  364. switch (msg.id) {
  365. //---------------------------------------------
  366. case EVID_TICK: // Timer events
  367. //! I would prefer to have ecPoll() called by cbTimer()
  368. //! ...but how does cbTimer() get the required access to the state variables? Namely: 'state->ec'
  369. //! So, for now, the timer pushes a message to call ecPoll()
  370. //! which, in turn, will push WIIEC event meesages! <facepalm>
  371. ecPoll(&state->ec, queue);
  372. break;
  373. //---------------------------------------------
  374. case EVID_WIIEC: // WiiMote Perhipheral
  375. if (evWiiEC(&msg, state)) redraw = true ;
  376. break;
  377. //---------------------------------------------
  378. case EVID_KEY: // Key events
  379. patBacklight(state);
  380. if (evKey(&msg, state)) redraw = true;
  381. break;
  382. //---------------------------------------------
  383. case EVID_NONE:
  384. break;
  385. //---------------------------------------------
  386. default: // Unknown event
  387. WARN("Unknown message.ID [%d]", msg.id);
  388. break;
  389. }
  390. // *** Update the GUI screen via the viewport ***
  391. if (redraw) view_port_update(vpp) ;
  392. // *** Try to release the plugin state variables ***
  393. if ( !release_mutex(&mutex, state) ) {
  394. ERROR(wii_errs[(error = ERR_MUTEX_RELEASE)]);
  395. goto bail;
  396. }
  397. } while (state->run);
  398. // ===== Game Over =====
  399. INFO("USER EXIT");
  400. bail:
  401. // 10. Release system notification queue
  402. if (state->notify) {
  403. furi_record_close(RECORD_NOTIFICATION);
  404. state->notify = NULL;
  405. }
  406. // 9. Stop the timer
  407. if (state->timer) {
  408. (void)furi_timer_stop(state->timer);
  409. furi_timer_free(state->timer);
  410. state->timer = NULL;
  411. state->timerEn = false;
  412. }
  413. // 8. Detach the viewport
  414. gui_remove_view_port(gui, vpp);
  415. // 7. No need to unreqgister the callbacks
  416. // ...they will go when the viewport is destroyed
  417. // 6. Destroy the viewport
  418. if (vpp) {
  419. view_port_enabled_set(vpp, false);
  420. view_port_free(vpp);
  421. vpp = NULL;
  422. }
  423. // 5. Free the mutex
  424. if (mutex.mutex) {
  425. delete_mutex(&mutex);
  426. mutex.mutex = NULL;
  427. }
  428. // 4. Free up state pointer(s)
  429. // none
  430. // 3. Free the plugin state variables
  431. if (state) {
  432. free(state);
  433. state = NULL;
  434. }
  435. // 2. Close the GUI
  436. furi_record_close("gui");
  437. // 1. Destroy the message queue
  438. if (queue) {
  439. furi_message_queue_free(queue);
  440. queue = NULL;
  441. }
  442. INFO("CLEAN EXIT ... Exit code: %d", error);
  443. LEAVE;
  444. return (int32_t)error;
  445. }