trade.c 33 KB

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