trade.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. /*
  2. * NOTE:
  3. * The documentation below is slightly out of date but mostly still correct,
  4. * and only for gen i trades. Gen ii trades are very similar but have a few
  5. * different patterns. I'm currently lazy and working on features, so better
  6. * documentation on the trade protocol to follow, and potentially will push
  7. * it all to bulbapedia or similar for the world to benefit from.
  8. *
  9. *
  10. * This setup always forces the flipper to the follower/slave role in the link.
  11. * This just makes our logic consistent and since we're going to be gobs faster
  12. * than a real Game Boy, we can be guaranteed to always be ready to respond.
  13. *
  14. * As documented here: http://www.adanscotney.com/2014/01/spoofing-pokemon-trades-with-stellaris.html
  15. * The general gist of the communication is as follows:
  16. * 1) Each Game Boy tries to listen for an external clock coming in on the link cable.
  17. * After some unknown timeout, this Game Boy decides its going to take the leader/master role.
  18. * In this state, it generates a clock and repeatedly sends out PKMN_MASTER(0x01)
  19. * 2) The other side, sensing a clock from the leader/master, then responds with PKMN_SLAVE(0x02)
  20. * 3) Once both sides understand their roles, they both respond with PKMN_BLANK(0x00) for a bit.
  21. * 4) Next, the leader/master sends CONNECTED(0x60) bytes that the follower/slave repeats
  22. * back. Then a bunch of BLANK bytes.
  23. * 5) At this point, each Game Boy repeatedly sends the menu item it has highlighted,
  24. * prepended by a BLANK, in groups of 3 bytes. These are ITEM_*_HIGHLIGHTED.
  25. * 6) Then, once both sides send ITEM_*_SELECTED, the next step occurs.
  26. * This application, from steps 3 through 6, just repeats bytes back and lets the Game Boy
  27. * dictate the steps. We stay here until we start seeing PREAMBLE(0xFD) bytes,
  28. * as those dictate the start of the next sections.
  29. *
  30. * The Flipper is now in the "READY" state.
  31. *
  32. * 7) Once the player on the Game Boy side uses the trade table, a block of data is
  33. * transmitted. This starts with 10x PREAMBLE(0xFD) bytes, 10x random bytes (to
  34. *
  35. * I missed another 9x fd bytes after rand? State machine below confirms these bytes
  36. *
  37. * sync the RNG between two devices, unused at this time), and then the 415 trade_block,
  38. * struct gets transferred. At the end of this is 3 ending bytes, DF FE 15. And, weirdly,
  39. * 3 PREAMBLE(0xFD) bytes.
  40. * 8) The patch list starts with 3x more PREAMBLE(0xFD) bytes for a total of 6x PREAMBLE,
  41. * followed by 7x BLANK bytes. Then remaining 189 bytes of patch list data. The patch
  42. * list is used to compensate for byte values of NO_DATA_BYE(0xFE) being transmitted.
  43. * The patch list is specifically for the party data of the trade_block. To patch
  44. * outgoing data, if a byte is 0xFE, it is changed to 0xFF, and the index+1 is
  45. * added to the patch list. There are two parts to the patch list as the data it
  46. * covers is longer than 0xFC. After each part is complete, 0xFF is added to the
  47. * patch list. The first part of the patch list can patch 0x00:0xFB of the party,
  48. * the second part can patch 0xFC:0x107 of the party. If there are no bytes to
  49. * patch in a part, 0xFF is just appended. After both terminators, it is expected
  50. * all remaining bytes are 0x00.
  51. *
  52. * The Flipper is now in the "WAITING" state.
  53. *
  54. * 9) At this point, both sides have full copies of each other's current party. The sides
  55. * simply indicate which Pokemon they are sending. This is done with a BLANK byte to
  56. * start, and then each side indicates which Pokemon it wants to trade with SEL_NUM_MASK(0x60)
  57. * + party index. We always transmit the first Pokemon. Once in a agreement, both
  58. * sides transmit a handful of BLANK bytes.
  59. *
  60. * The Flipper is now in the "DEAL?" state.
  61. *
  62. * A) Starting with another BLANK byte, both sides need to agree to the trade by
  63. * sending TRADE_ACCEPT(0x62) repeatedly, and then a handful of BLANK bytes.
  64. * To disagree with a trade, either side would send TRADE_REJECT(0x61), the
  65. * Flipper will never send this on its own. If the Game Boy does, both it and
  66. * the flipper got back to step 9 again.
  67. *
  68. * The Flipper is now in the "TRADING" state.
  69. *
  70. * B) The Flipper actually goes back to step 7, but keeps the drawing mode as
  71. * TRADING. After the trade is complete on the Game Boy, it re-sends the
  72. * trade_block data. This re-syncs the states between the Flipper and
  73. * Game Boy and another trade can occur.
  74. *
  75. * *) A point of note is that the Flipper can go back to the main menu from
  76. * any state. Though, doing so in the TRADING state might actually cause
  77. * the Game Boy to have issues. When in READY or WAITING state, the Flipper
  78. * can go back and modify the Pokemon that the Game Boy sent to it. If the
  79. * Flipper then goes back to Trade from the main menu, it will be in the
  80. * READY state. If the Game Boy is still on the trade menu, and it tries
  81. * to trade, the trade will be rejected. The Game Boy needs to exit the
  82. * trade menu, and then re-enter it by selecting the table in the trade
  83. * center. This will then push the Flipper to the WAITING state, and the
  84. * trade_blocks will re-sync between them with the new data. If the Game Boy
  85. * leave the trade menu while the Flipper is in the WAITING state, the
  86. * Flipper will go back to the READY state.
  87. */
  88. #include <furi.h>
  89. #include <furi_hal.h>
  90. #include <gui/elements.h>
  91. #include <gui/view.h>
  92. #include <pokemon_icons.h>
  93. #include <gblink.h>
  94. #include "../pokemon_app.h"
  95. #include "../pokemon_data.h"
  96. #include "trade_patch_list.h"
  97. /* Uncomment the following line to enable graphics testing for the different
  98. * phases of the trade view. Pressing the okay button will step through each
  99. * gameboy_status. Note that while trades will still function with this enabled,
  100. * forcing the advance of the status will certainly break trades.
  101. */
  102. //#define GRAPHICS_TESTING
  103. #define DELAY_MICROSECONDS 15
  104. #define PKMN_BLANK 0x00
  105. #define ITEM_1_HIGHLIGHTED 0xD0
  106. #define ITEM_2_HIGHLIGHTED 0xD1
  107. #define ITEM_3_HIGHLIGHTED 0xD2
  108. #define ITEM_1_SELECTED 0xD4
  109. #define ITEM_2_SELECTED 0xD5
  110. #define ITEM_3_SELECTED 0xD6
  111. #define SERIAL_PREAMBLE_BYTE 0xFD
  112. #define SERIAL_PREAMBLE_LENGTH 6
  113. #define SERIAL_RN_PREAMBLE_LENGTH 7
  114. #define SERIAL_TRADE_PREAMBLE_LENGTH 9
  115. #define SERIAL_RNS_LENGTH 10
  116. #define SERIAL_PATCH_LIST_PART_TERMINATOR 0xFF
  117. #define SERIAL_NO_DATA_BYTE 0xFE
  118. #define PKMN_MASTER 0x01
  119. #define PKMN_SLAVE 0x02
  120. #define PKMN_CONNECTED 0x60
  121. #define PKMN_CONNECTED_II 0x61
  122. #define PKMN_TRADE_ACCEPT_GEN_I 0x62
  123. #define PKMN_TRADE_ACCEPT_GEN_II 0x72
  124. #define PKMN_TRADE_REJECT_GEN_I 0x61
  125. #define PKMN_TRADE_REJECT_GEN_II 0x71
  126. #define PKMN_TABLE_LEAVE_GEN_I 0x6f
  127. #define PKMN_TABLE_LEAVE_GEN_II 0x7f
  128. #define PKMN_SEL_NUM_MASK_GEN_I 0x60
  129. #define PKMN_SEL_NUM_MASK_GEN_II 0x70
  130. #define PKMN_SEL_NUM_ONE_GEN_I 0x60
  131. #define PKMN_SEL_NUM_ONE_GEN_II 0x70
  132. #define PKMN_ACTION 0x60
  133. #define PKMN_TRADE_CENTRE ITEM_1_SELECTED
  134. #define PKMN_COLOSSEUM ITEM_2_SELECTED
  135. #define PKMN_BREAK_LINK ITEM_3_SELECTED
  136. struct important_bytes {
  137. const uint8_t connected;
  138. const uint8_t trade_accept;
  139. const uint8_t trade_reject;
  140. const uint8_t table_leave;
  141. const uint8_t sel_num_mask;
  142. const uint8_t sel_num_one;
  143. };
  144. static const struct important_bytes gen_i = {
  145. PKMN_CONNECTED,
  146. PKMN_TRADE_ACCEPT_GEN_I,
  147. PKMN_TRADE_REJECT_GEN_I,
  148. PKMN_TABLE_LEAVE_GEN_I,
  149. PKMN_SEL_NUM_MASK_GEN_I,
  150. PKMN_SEL_NUM_ONE_GEN_I,
  151. };
  152. static const struct important_bytes gen_ii = {
  153. PKMN_CONNECTED_II,
  154. PKMN_TRADE_ACCEPT_GEN_II,
  155. PKMN_TRADE_REJECT_GEN_II,
  156. PKMN_TABLE_LEAVE_GEN_II,
  157. PKMN_SEL_NUM_MASK_GEN_II,
  158. PKMN_SEL_NUM_ONE_GEN_II,
  159. };
  160. /* States specific to the trade process. */
  161. typedef enum {
  162. TRADE_RESET,
  163. TRADE_INIT,
  164. TRADE_RANDOM,
  165. TRADE_DATA,
  166. TRADE_PATCH_HEADER,
  167. TRADE_PATCH_DATA,
  168. TRADE_SELECT,
  169. TRADE_MAIL,
  170. TRADE_PENDING,
  171. TRADE_CONFIRMATION,
  172. TRADE_DONE,
  173. TRADE_CANCEL
  174. } trade_centre_state_t;
  175. /* Global states for the trade logic. These are used to dictate what gets drawn
  176. * to the screen but also handle a few sync states. The CONN states are to denote
  177. * if a link has been established or note. READY through TRADING are all specific
  178. * screens to draw in the trade center. COLOSSEUM causes a data loopback so the
  179. * player can fight themselves.
  180. */
  181. typedef enum {
  182. GAMEBOY_CONN_FALSE,
  183. GAMEBOY_CONN_TRUE,
  184. GAMEBOY_READY,
  185. GAMEBOY_WAITING,
  186. GAMEBOY_TRADE_PENDING,
  187. GAMEBOY_TRADING,
  188. GAMEBOY_TRADE_CANCEL,
  189. GAMEBOY_COLOSSEUM,
  190. GAMEBOY_STATE_COUNT
  191. } render_gameboy_state_t;
  192. /* Anonymous struct */
  193. struct trade_ctx {
  194. trade_centre_state_t trade_centre_state;
  195. FuriTimer* draw_timer;
  196. View* view;
  197. uint8_t in_data;
  198. uint8_t out_data;
  199. uint8_t shift;
  200. PokemonData* input_pdata;
  201. struct patch_list* patch_list;
  202. void* gblink_handle;
  203. struct gblink_pins* gblink_pins;
  204. PokemonData* pdata;
  205. };
  206. /* These are the needed variables for the draw callback */
  207. struct trade_model {
  208. render_gameboy_state_t gameboy_status;
  209. bool ledon; // Controls the blue LED during trade
  210. uint8_t curr_pokemon;
  211. PokemonData* pdata;
  212. };
  213. /* Input callback, used to handle the user trying to back out of the trade
  214. * screen.
  215. * Normally, when trade_centre_state is <= READY, pressing back would just go
  216. * back without issue. However, when WAITING, we need to tell the gameboy that
  217. * the flipper wants to exit the trade menu. Anything beyond WAITING should not
  218. * go back nor try to tell the gameboy to cancel; instead, by holding back in
  219. * these states, we can forcefully go back one menu.
  220. *
  221. * Returning false here then ends up calling the view_dispatcher nav callback
  222. * if the button pressed/held is Back. Returning true tells the OS that we
  223. * dealt with the button press and no further action is needed.
  224. */
  225. static bool trade_input_callback(InputEvent* event, void* context) {
  226. furi_assert(context);
  227. struct trade_ctx* trade = context;
  228. render_gameboy_state_t gameboy_status;
  229. #ifdef GRAPHICS_TESTING
  230. if(event->type == InputTypePress) {
  231. with_view_model(
  232. trade->view,
  233. struct trade_model * model,
  234. {
  235. if(event->key == InputKeyRight) {
  236. model->gameboy_status++;
  237. if(model->gameboy_status == GAMEBOY_STATE_COUNT)
  238. model->gameboy_status = GAMEBOY_CONN_FALSE;
  239. } else if(event->key == InputKeyLeft) {
  240. if(model->gameboy_status == GAMEBOY_CONN_FALSE)
  241. model->gameboy_status = GAMEBOY_COLOSSEUM;
  242. else
  243. model->gameboy_status--;
  244. }
  245. },
  246. true);
  247. }
  248. #endif
  249. /* Only handling back button */
  250. if(event->key != InputKeyBack) return false;
  251. with_view_model(
  252. trade->view,
  253. struct trade_model * model,
  254. { gameboy_status = model->gameboy_status; },
  255. false);
  256. /* States READY or lower can be exited without issue, let the view_dispatcher
  257. * nav callback handle it.
  258. */
  259. if(gameboy_status <= GAMEBOY_READY) return false;
  260. /* Long presses we want the view_dispatcher nav callback to handle */
  261. if(event->type == InputTypeLong) return false;
  262. /* In the waiting state, we need to move to cancelled. This locks us up
  263. * until the gameboy side gets the hint and cancels as well.
  264. */
  265. if(gameboy_status == GAMEBOY_WAITING && event->type == InputTypeShort) {
  266. with_view_model(
  267. trade->view,
  268. struct trade_model * model,
  269. { model->gameboy_status = GAMEBOY_TRADE_CANCEL; },
  270. false);
  271. trade->trade_centre_state = TRADE_CANCEL;
  272. }
  273. /* Anything here, we should consider handled */
  274. return true;
  275. }
  276. /* A callback function that must be called outside of an interrupt context,
  277. * This will completely destroy the current patch list, and then rebuild it from
  278. * the current trade_block state. This is used mostly after a trade to rebuild
  279. * the list with the new data we just copied in.
  280. */
  281. static void pokemon_plist_recreate_callback(void* context, uint32_t arg) {
  282. furi_assert(context);
  283. UNUSED(arg);
  284. struct trade_ctx* trade = context;
  285. plist_create(&(trade->patch_list), trade->pdata);
  286. }
  287. static void trade_draw_bottom_bar(Canvas* const canvas) {
  288. furi_assert(canvas);
  289. /* Paint the area behind the bottom background bar white to prevent overlap */
  290. canvas_set_color(canvas, ColorWhite);
  291. canvas_draw_box(canvas, 0, 53, 9, 7);
  292. canvas_draw_box(canvas, 6, 56, 59, 6);
  293. canvas_draw_box(canvas, 60, 53, 32, 7);
  294. canvas_draw_box(canvas, 87, 56, 38, 6);
  295. canvas_set_color(canvas, ColorBlack);
  296. /* Draw bar with transparencies */
  297. canvas_set_bitmap_mode(canvas, 1);
  298. canvas_draw_icon(canvas, 0, 53, &I_Background_128x11);
  299. canvas_set_bitmap_mode(canvas, 0);
  300. }
  301. /* Draws a whole screen image with Flipper mascot, Game Boy, etc. */
  302. static void trade_draw_connection(Canvas* const canvas, bool connected) {
  303. furi_assert(canvas);
  304. canvas_draw_icon(canvas, 9, 26, &I_dolphin);
  305. trade_draw_bottom_bar(canvas);
  306. canvas_draw_icon(canvas, 80, 0, &I_game_boy);
  307. elements_frame(canvas, 9, 2, 64, 17);
  308. if(connected) {
  309. canvas_draw_str(canvas, 18, 13, "Connected!");
  310. canvas_draw_icon(canvas, 61, 23, &I_hand_thumbsup);
  311. } else {
  312. canvas_draw_str(canvas, 18, 13, "Connect GB");
  313. canvas_draw_icon(canvas, 56, 23, &I_hand_cable);
  314. }
  315. }
  316. /* Draws a frame around the screen, with a box at the top for a text string,
  317. * and an icon of the player.
  318. */
  319. static void trade_draw_frame(Canvas* canvas, const char* str) {
  320. furi_assert(canvas);
  321. trade_draw_bottom_bar(canvas);
  322. /* Paint the area behind the text box white to prevent overlap, similar
  323. * to the bottom background bar */
  324. canvas_set_color(canvas, ColorWhite);
  325. canvas_draw_box(canvas, 59, 0, 67, 19);
  326. canvas_set_color(canvas, ColorBlack);
  327. /* Draw text box and populate it with string and Red icon */
  328. elements_frame(canvas, 59, 0, 67, 19);
  329. canvas_draw_str(canvas, 82, 12, str);
  330. canvas_draw_icon(canvas, 61, 2, &I_red_16x15);
  331. }
  332. /* Draws the Pokemon's image in the middle of the screen */
  333. static void trade_draw_pkmn_avatar(Canvas* canvas, PokemonData* pdata) {
  334. furi_assert(canvas);
  335. furi_assert(pdata);
  336. /* First, ensure the icon we want is already loaded in to pdata->bitmap */
  337. pokemon_icon_get(pdata, pokemon_stat_get(pdata, STAT_NUM, NONE) + 1);
  338. canvas_draw_xbm(
  339. canvas, 0, 0, pdata->bitmap->width, pdata->bitmap->height, pdata->bitmap->data);
  340. furi_hal_light_set(LightBlue, 0x00);
  341. furi_hal_light_set(LightGreen, 0x00);
  342. }
  343. /* Called every 250 ms on a timer. This controls the blue LED when in TRADING
  344. * state. This is necessary as Flipper OS does not make any guarantees on when
  345. * draw updates may or may not be called. There are situations where a draw
  346. * update is called much faster. Therefore, we need to control the update rate
  347. * via the ledon view_model variable.
  348. */
  349. static void trade_draw_timer_callback(void* context) {
  350. furi_assert(context);
  351. struct trade_ctx* trade = (struct trade_ctx*)context;
  352. with_view_model(
  353. trade->view, struct trade_model * model, { model->ledon ^= 1; }, true);
  354. }
  355. static void trade_draw_callback(Canvas* canvas, void* view_model) {
  356. furi_assert(view_model);
  357. struct trade_model* model = view_model;
  358. canvas_clear(canvas);
  359. switch(model->gameboy_status) {
  360. case GAMEBOY_CONN_FALSE:
  361. furi_hal_light_set(LightGreen, 0x00);
  362. furi_hal_light_set(LightRed, 0xff);
  363. trade_draw_connection(canvas, false);
  364. break;
  365. case GAMEBOY_CONN_TRUE:
  366. furi_hal_light_set(LightGreen, 0xff);
  367. furi_hal_light_set(LightRed, 0x00);
  368. trade_draw_connection(canvas, true);
  369. break;
  370. case GAMEBOY_READY:
  371. trade_draw_pkmn_avatar(canvas, model->pdata);
  372. trade_draw_frame(canvas, "READY");
  373. break;
  374. case GAMEBOY_WAITING:
  375. trade_draw_pkmn_avatar(canvas, model->pdata);
  376. trade_draw_frame(canvas, "WAITING");
  377. break;
  378. case GAMEBOY_TRADE_PENDING:
  379. trade_draw_pkmn_avatar(canvas, model->pdata);
  380. trade_draw_frame(canvas, "DEAL?");
  381. break;
  382. case GAMEBOY_TRADING:
  383. furi_hal_light_set(LightGreen, 0x00);
  384. if(model->ledon) {
  385. furi_hal_light_set(LightBlue, 0xff);
  386. canvas_draw_icon(canvas, 0, 5, &I_gb_step_1);
  387. } else {
  388. furi_hal_light_set(LightBlue, 0x00);
  389. canvas_draw_icon(canvas, 0, 5, &I_gb_step_2);
  390. }
  391. trade_draw_frame(canvas, "TRADING");
  392. break;
  393. case GAMEBOY_TRADE_CANCEL:
  394. trade_draw_frame(canvas, "CANCEL");
  395. break;
  396. case GAMEBOY_COLOSSEUM:
  397. trade_draw_frame(canvas, "FIGHT!");
  398. break;
  399. default:
  400. trade_draw_frame(canvas, "INITIAL");
  401. break;
  402. }
  403. }
  404. /* Get the response byte from the link partner, updating the connection
  405. * state if needed.
  406. */
  407. static uint8_t getConnectResponse(struct trade_ctx* trade) {
  408. furi_assert(trade);
  409. uint8_t ret = trade->in_data;
  410. switch(trade->in_data) {
  411. case PKMN_CONNECTED:
  412. case PKMN_CONNECTED_II:
  413. with_view_model(
  414. trade->view,
  415. struct trade_model * model,
  416. { model->gameboy_status = GAMEBOY_CONN_TRUE; },
  417. false);
  418. break;
  419. case PKMN_MASTER:
  420. ret = PKMN_SLAVE;
  421. break;
  422. case PKMN_BLANK:
  423. ret = PKMN_BLANK;
  424. break;
  425. default:
  426. with_view_model(
  427. trade->view,
  428. struct trade_model * model,
  429. { model->gameboy_status = GAMEBOY_CONN_FALSE; },
  430. false);
  431. ret = PKMN_BREAK_LINK;
  432. break;
  433. }
  434. return ret;
  435. }
  436. /* Receive what the Pokemon game is requesting and move to that mode.
  437. *
  438. * This reads bytes sent by the Game Boy and responds. The only things
  439. * we care about are when menu items are actually selected. The protocol
  440. * seems to send data both when one of the link menu items is highlighted
  441. * and when one of them is selected.
  442. *
  443. * If somehow we get a leader/master byte received, then go back to the
  444. * NOT_CONNECTED state. For the leader/master byte likely means that
  445. * the linked Game Boy is still trying to negotiate roles and we need to
  446. * respond with a follower/slave byte.
  447. *
  448. * Note that, we can probably eventually drop colosseum/battle connections,
  449. * though it may be an interesting exercise in better understanding how the
  450. * "random" seeding is done between the units. As noted here:
  451. * http://www.adanscotney.com/2014/01/spoofing-pokemon-trades-with-stellaris.html
  452. * it is presumed these bytes are to sync the RNG seed between the units to
  453. * not need arbitration on various die rolls.
  454. */
  455. static uint8_t getMenuResponse(struct trade_ctx* trade) {
  456. furi_assert(trade);
  457. uint8_t response = PKMN_BLANK;
  458. switch(trade->in_data) {
  459. case PKMN_CONNECTED:
  460. case PKMN_CONNECTED_II:
  461. response = trade->in_data;
  462. break;
  463. case ITEM_2_HIGHLIGHTED:
  464. if(trade->pdata->gen == GEN_I) {
  465. response = trade->in_data;
  466. break;
  467. }
  468. [[fallthrough]];
  469. case PKMN_TRADE_CENTRE:
  470. with_view_model(
  471. trade->view,
  472. struct trade_model * model,
  473. { model->gameboy_status = GAMEBOY_READY; },
  474. false);
  475. break;
  476. case PKMN_COLOSSEUM:
  477. with_view_model(
  478. trade->view,
  479. struct trade_model * model,
  480. { model->gameboy_status = GAMEBOY_COLOSSEUM; },
  481. false);
  482. break;
  483. case PKMN_BREAK_LINK:
  484. case PKMN_MASTER:
  485. with_view_model(
  486. trade->view,
  487. struct trade_model * model,
  488. { model->gameboy_status = GAMEBOY_CONN_FALSE; },
  489. false);
  490. response = PKMN_BREAK_LINK;
  491. break;
  492. default:
  493. response = trade->in_data;
  494. break;
  495. }
  496. return response;
  497. }
  498. static uint8_t getTradeCentreResponse(struct trade_ctx* trade) {
  499. furi_assert(trade);
  500. uint8_t* trade_block_flat = (uint8_t*)trade->pdata->trade_block;
  501. uint8_t* input_block_flat = (uint8_t*)trade->input_pdata->trade_block;
  502. uint8_t* input_party_flat = (uint8_t*)trade->input_pdata->party;
  503. struct trade_model* model = NULL;
  504. uint8_t in = trade->in_data;
  505. uint8_t send = in;
  506. static bool patch_pt_2;
  507. static size_t counter;
  508. static uint8_t in_pkmn_idx;
  509. const struct important_bytes* bytes = NULL;
  510. if(trade->pdata->gen == GEN_I) bytes = &gen_i;
  511. if(trade->pdata->gen == GEN_II) bytes = &gen_ii;
  512. /* TODO: Figure out how we should respond to a no_data_byte and/or how to
  513. * send one and what response to expect.
  514. *
  515. * This isn't a high priority since it should be unlikely that we would
  516. * actually ever receive a NO_DATA_BYE as the Game Boy is the leader/master
  517. * and therefore would only transmit when it has data ready.
  518. */
  519. /* Since this is a fairly long function, it doesn't call any other functions,
  520. * the view model isn't locked, and we're in an interrupt context, lets just
  521. * map the view model to a local var and commit it back when we're done.
  522. */
  523. model = view_get_model(trade->view);
  524. /* There is a handful of communications that happen once the Game Boy
  525. * clicks on the table. For all of them, the Flipper can just mirror back
  526. * the byte the Game Boy sends. We can spin in this forever until we see 10x
  527. * SERIAL_PREAMBLE_BYTEs. Once we receive those, the counters are synced,
  528. * and every byte after that can be easily counted for the actual transfer
  529. * of Pokemon data.
  530. */
  531. switch(trade->trade_centre_state) {
  532. case TRADE_RESET:
  533. /* Reset counters and other static variables */
  534. counter = 0;
  535. patch_pt_2 = false;
  536. trade->trade_centre_state = TRADE_INIT;
  537. break;
  538. /* This state runs through the end of the random preamble */
  539. case TRADE_INIT:
  540. if(in == SERIAL_PREAMBLE_BYTE) {
  541. counter++;
  542. model->gameboy_status = GAMEBOY_WAITING;
  543. }
  544. if(counter == SERIAL_RNS_LENGTH) {
  545. trade->trade_centre_state = TRADE_RANDOM;
  546. counter = 0;
  547. }
  548. break;
  549. /* Once we start getting PKMN_BLANKs, we mirror them until we get 10x
  550. * SERIAL_PREAMBLE_BYTE, and then 10 random numbers. The 10 random
  551. * numbers are for synchronizing the PRNG between the two systems,
  552. * we do not use these numbers at this time.
  553. *
  554. * This waits through the end of the trade block preamble, a total of 19
  555. * bytes.
  556. */
  557. case TRADE_RANDOM:
  558. counter++;
  559. if(counter == (SERIAL_RNS_LENGTH + SERIAL_TRADE_PREAMBLE_LENGTH)) {
  560. trade->trade_centre_state = TRADE_DATA;
  561. counter = 0;
  562. }
  563. break;
  564. /* This is where we exchange trade_block data with the Game Boy */
  565. case TRADE_DATA:
  566. input_block_flat[counter] = in;
  567. send = trade_block_flat[counter];
  568. counter++;
  569. if(counter == trade->input_pdata->trade_block_sz) {
  570. trade->trade_centre_state = TRADE_PATCH_HEADER;
  571. counter = 0;
  572. }
  573. break;
  574. /* This absorbs the 3 byte ending sequence (DF FE 15) after the trade data is
  575. * swapped, then the 3x SERIAL_PREAMBLE_BYTEs that end the trade data, and
  576. * another 3x of them that start the patch data. By the time we're done with
  577. * this state, the patch list BLANK bytes are ready to be transmitted.
  578. * We only care about the 6x total preamble bytes.
  579. */
  580. case TRADE_PATCH_HEADER:
  581. if(in == SERIAL_PREAMBLE_BYTE) {
  582. counter++;
  583. }
  584. if(counter == 6) {
  585. counter = 0;
  586. trade->trade_centre_state = TRADE_PATCH_DATA;
  587. } else {
  588. break;
  589. }
  590. [[fallthrough]];
  591. case TRADE_PATCH_DATA:
  592. counter++;
  593. /* This magic number is basically the header length, 10, minus
  594. * the 3x 0xFD that we should be transmitting as part of the patch
  595. * list header.
  596. */
  597. if(counter > 8) {
  598. send = plist_index_get(trade->patch_list, (counter - 9));
  599. }
  600. /* Patch received data */
  601. /* This relies on the data sent only ever sending 0x00 after
  602. * part 2 of the patch list has been terminated. This is the
  603. * case in official Gen I code at this time.
  604. */
  605. switch(in) {
  606. case PKMN_BLANK:
  607. break;
  608. case SERIAL_PATCH_LIST_PART_TERMINATOR:
  609. patch_pt_2 = true;
  610. break;
  611. default: // Any nonzero value will cause a patch
  612. if(!patch_pt_2) {
  613. /* Pt 1 is 0x00 - 0xFB */
  614. input_party_flat[in - 1] = SERIAL_NO_DATA_BYTE;
  615. } else {
  616. /* Pt 2 is 0xFC - 0x107
  617. * 0xFC + in - 1
  618. */
  619. input_party_flat[0xFB + in] = SERIAL_NO_DATA_BYTE;
  620. }
  621. break;
  622. }
  623. /* What is interesting about the following check, is the Pokemon code
  624. * seems to allocate 203 bytes, 3x for the preamble, and then 200 bytes
  625. * of patch list. But in practice, the Game Boy seems to transmit 3x
  626. * preamble bytes, 7x 0x00, then 189 bytes for the patch list. A
  627. * total of 199 bytes transmitted.
  628. */
  629. /* Gen I and II patch lists seem to be the same length */
  630. if(counter == 196) {
  631. if(trade->pdata->gen == GEN_I)
  632. trade->trade_centre_state = TRADE_SELECT;
  633. else if(trade->pdata->gen == GEN_II)
  634. trade->trade_centre_state = TRADE_MAIL;
  635. counter = 0;
  636. }
  637. break;
  638. /* Preambled with 6x 0x20 bytes; 33*6 == 198 bytes of Mail, for each pokemon,
  639. * even if they have no mail set; 14*6 == 84 bytes, for each pokemon's mail,
  640. * the OT Name and ID; a 0xff; 100 zero bytes (unsure if they are always 0).
  641. * This is 6 + 198 + 84 + 1 + 100 == 389.
  642. */
  643. case TRADE_MAIL:
  644. counter++;
  645. if(counter == 389) trade->trade_centre_state = TRADE_SELECT;
  646. break;
  647. /* Resets the incoming Pokemon index, and once a BLANK byte is received,
  648. * moves to the pending state.
  649. */
  650. case TRADE_SELECT:
  651. in_pkmn_idx = 0;
  652. if(in == PKMN_BLANK) {
  653. trade->trade_centre_state = TRADE_PENDING;
  654. } else {
  655. break;
  656. }
  657. [[fallthrough]];
  658. /* Handle the Game Boy selecting a Pokemon to trade, or leaving the table */
  659. /* XXX: TODO: Clean this up. Easiest is probably to use vars rather than
  660. * macros to check against and set output to.
  661. */
  662. case TRADE_PENDING:
  663. /* If the player leaves the trade menu and returns to the room */
  664. if(in == bytes->table_leave) {
  665. trade->trade_centre_state = TRADE_RESET;
  666. send = bytes->table_leave;
  667. model->gameboy_status = GAMEBOY_READY;
  668. /* If the player selected a Pokemon to send from the Game Boy */
  669. } else if((in & bytes->sel_num_mask) == bytes->sel_num_mask) {
  670. in_pkmn_idx = in;
  671. send = bytes->sel_num_one; // We always send the first pokemon
  672. model->gameboy_status = GAMEBOY_TRADE_PENDING;
  673. /* BLANKs are sent in a few places, we want to do nothing about them
  674. * unless the Game Boy already sent us an index they want to trade.
  675. */
  676. } else if(in == PKMN_BLANK) {
  677. if(in_pkmn_idx != 0) {
  678. send = 0;
  679. trade->trade_centre_state = TRADE_CONFIRMATION;
  680. in_pkmn_idx &= 0x0F;
  681. }
  682. }
  683. break;
  684. /* Handle the Game Boy accepting or rejecting a trade deal */
  685. case TRADE_CONFIRMATION:
  686. if(in == bytes->trade_reject) {
  687. trade->trade_centre_state = TRADE_SELECT;
  688. model->gameboy_status = GAMEBOY_WAITING;
  689. } else if(in == bytes->trade_accept) {
  690. trade->trade_centre_state = TRADE_DONE;
  691. }
  692. break;
  693. /* Start the actual trade. Waits in reset until the Game Boy is done with
  694. * its animation and re-exchanges updated party data.
  695. */
  696. case TRADE_DONE:
  697. if(in == PKMN_BLANK) {
  698. trade->trade_centre_state = TRADE_RESET;
  699. model->gameboy_status = GAMEBOY_TRADING;
  700. /* Copy the traded-in Pokemon's main data to our struct */
  701. pokemon_stat_memcpy(trade->pdata, trade->input_pdata, in_pkmn_idx);
  702. model->curr_pokemon = pokemon_stat_get(trade->pdata, STAT_NUM, NONE);
  703. /* Schedule a callback outside of ISR context to rebuild the patch
  704. * list with the new Pokemon that we just accepted.
  705. */
  706. furi_timer_pending_callback(pokemon_plist_recreate_callback, trade, 0);
  707. }
  708. break;
  709. case TRADE_CANCEL:
  710. if(in == bytes->table_leave) {
  711. trade->trade_centre_state = TRADE_RESET;
  712. model->gameboy_status = GAMEBOY_READY;
  713. }
  714. send = bytes->table_leave;
  715. break;
  716. default:
  717. // Do Nothing
  718. break;
  719. }
  720. view_commit_model(trade->view, false);
  721. return send;
  722. }
  723. static void transferBit(void* context, uint8_t in_byte) {
  724. furi_assert(context);
  725. struct trade_ctx* trade = (struct trade_ctx*)context;
  726. render_gameboy_state_t status;
  727. with_view_model(
  728. trade->view, struct trade_model * model, { status = model->gameboy_status; }, false);
  729. trade->in_data = in_byte;
  730. /* Once a byte of data has been shifted in, process it */
  731. switch(status) {
  732. case GAMEBOY_CONN_FALSE:
  733. gblink_transfer(trade->gblink_handle, getConnectResponse(trade));
  734. break;
  735. case GAMEBOY_CONN_TRUE:
  736. gblink_transfer(trade->gblink_handle, getMenuResponse(trade));
  737. break;
  738. case GAMEBOY_COLOSSEUM:
  739. gblink_transfer(trade->gblink_handle, in_byte);
  740. break;
  741. /* Every other state is trade related */
  742. default:
  743. gblink_transfer(trade->gblink_handle, getTradeCentreResponse(trade));
  744. break;
  745. }
  746. }
  747. void trade_enter_callback(void* context) {
  748. furi_assert(context);
  749. struct trade_ctx* trade = (struct trade_ctx*)context;
  750. struct trade_model* model;
  751. struct gblink_def gblink_def = {0};
  752. model = view_get_model(trade->view);
  753. if(model->gameboy_status == GAMEBOY_COLOSSEUM) {
  754. model->gameboy_status = GAMEBOY_CONN_FALSE;
  755. } else if(model->gameboy_status > GAMEBOY_READY) {
  756. model->gameboy_status = GAMEBOY_READY;
  757. }
  758. trade->trade_centre_state = TRADE_RESET;
  759. model->curr_pokemon = pokemon_stat_get(trade->pdata, STAT_NUM, NONE);
  760. model->ledon = false;
  761. view_commit_model(trade->view, true);
  762. gblink_def.pins = trade->gblink_pins;
  763. gblink_def.callback = transferBit;
  764. gblink_def.cb_context = trade;
  765. trade->gblink_handle = gblink_alloc(&gblink_def);
  766. gblink_nobyte_set(trade->gblink_handle, SERIAL_NO_DATA_BYTE);
  767. /* Every 250 ms, trigger a draw update. 250 ms was chosen so that during
  768. * the trade process, each update can flip the LED and screen to make the
  769. * trade animation.
  770. */
  771. trade->draw_timer = furi_timer_alloc(trade_draw_timer_callback, FuriTimerTypePeriodic, trade);
  772. furi_timer_start(trade->draw_timer, furi_ms_to_ticks(250));
  773. /* Create a trade patch list from the current trade block */
  774. plist_create(&(trade->patch_list), trade->pdata);
  775. }
  776. void disconnect_pin(const GpioPin* pin) {
  777. /* Existing projects seem to set the pin back to analog mode upon exit */
  778. furi_hal_gpio_init_simple(pin, GpioModeAnalog);
  779. }
  780. void trade_exit_callback(void* context) {
  781. furi_assert(context);
  782. struct trade_ctx* trade = (struct trade_ctx*)context;
  783. furi_hal_light_set(LightGreen, 0x00);
  784. furi_hal_light_set(LightBlue, 0x00);
  785. furi_hal_light_set(LightRed, 0x00);
  786. /* Stop the timer, and deallocate it as the enter callback allocates it on entry */
  787. furi_timer_free(trade->draw_timer);
  788. trade->draw_timer = NULL;
  789. /* Unset the pin settings */
  790. gblink_free(trade->gblink_handle);
  791. /* Destroy the patch list, it is allocated on the enter callback */
  792. plist_free(trade->patch_list);
  793. trade->patch_list = NULL;
  794. }
  795. void* trade_alloc(
  796. PokemonData* pdata,
  797. struct gblink_pins* gblink_pins,
  798. ViewDispatcher* view_dispatcher,
  799. uint32_t view_id) {
  800. furi_assert(pdata);
  801. struct trade_ctx* trade = malloc(sizeof(struct trade_ctx));
  802. memset(trade, '\0', sizeof(struct trade_ctx));
  803. trade->view = view_alloc();
  804. trade->pdata = pdata;
  805. trade->input_pdata = pokemon_data_alloc(pdata->gen);
  806. trade->patch_list = NULL;
  807. trade->gblink_pins = gblink_pins;
  808. view_set_context(trade->view, trade);
  809. view_allocate_model(trade->view, ViewModelTypeLockFree, sizeof(struct trade_model));
  810. with_view_model(
  811. trade->view, struct trade_model * model, { model->pdata = pdata; }, false);
  812. view_set_draw_callback(trade->view, trade_draw_callback);
  813. view_set_input_callback(trade->view, trade_input_callback);
  814. view_set_enter_callback(trade->view, trade_enter_callback);
  815. view_set_exit_callback(trade->view, trade_exit_callback);
  816. view_dispatcher_add_view(view_dispatcher, view_id, trade->view);
  817. return trade;
  818. }
  819. void trade_free(ViewDispatcher* view_dispatcher, uint32_t view_id, void* trade_ctx) {
  820. furi_assert(trade_ctx);
  821. struct trade_ctx* trade = (struct trade_ctx*)trade_ctx;
  822. view_dispatcher_remove_view(view_dispatcher, view_id);
  823. view_free(trade->view);
  824. pokemon_data_free(trade->input_pdata);
  825. free(trade);
  826. }