opal.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. /*
  2. * opal.c - Parser for Opal card (Sydney, Australia).
  3. *
  4. * Copyright 2023 Michael Farrell <micolous+git@gmail.com>
  5. *
  6. * This will only read "standard" MIFARE DESFire-based Opal cards. Free travel
  7. * cards (including School Opal cards, veteran, vision-impaired persons and
  8. * TfNSW employees' cards) and single-trip tickets are MIFARE Ultralight C
  9. * cards and not supported.
  10. *
  11. * Reference: https://github.com/metrodroid/metrodroid/wiki/Opal
  12. *
  13. * Note: The card values are all little-endian (like Flipper), but the above
  14. * reference was originally written based on Java APIs, which are big-endian.
  15. * This implementation presumes a little-endian system.
  16. *
  17. * This program is free software: you can redistribute it and/or modify it
  18. * under the terms of the GNU General Public License as published by
  19. * the Free Software Foundation, either version 3 of the License, or
  20. * (at your option) any later version.
  21. *
  22. * This program is distributed in the hope that it will be useful, but
  23. * WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  25. * General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU General Public License
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  29. */
  30. #include "../../metroflip_i.h"
  31. #include <flipper_application.h>
  32. #include <lib/nfc/protocols/mf_desfire/mf_desfire.h>
  33. #include <lib/nfc/protocols/mf_desfire/mf_desfire_poller.h>
  34. #include "../../api/metroflip/metroflip_api.h"
  35. #include "../../metroflip_plugins.h"
  36. #include <applications/services/locale/locale.h>
  37. #include <datetime.h>
  38. #define TAG "Metroflip:Scene:Opal"
  39. static const MfDesfireApplicationId opal_app_id = {.data = {0x31, 0x45, 0x53}};
  40. static const MfDesfireFileId opal_file_id = 0x07;
  41. static const char* opal_modes[5] =
  42. {"Rail / Metro", "Ferry / Light Rail", "Bus", "Unknown mode", "Manly Ferry"};
  43. static const char* opal_usages[14] = {
  44. "New / Unused",
  45. "Tap on: new journey",
  46. "Tap on: transfer from same mode",
  47. "Tap on: transfer from other mode",
  48. NULL, // Manly Ferry: new journey
  49. NULL, // Manly Ferry: transfer from ferry
  50. NULL, // Manly Ferry: transfer from other
  51. "Tap off: distance fare",
  52. "Tap off: flat fare",
  53. "Automated tap off: failed to tap off",
  54. "Tap off: end of trip without start",
  55. "Tap off: reversal",
  56. "Tap on: rejected",
  57. "Unknown usage",
  58. };
  59. // Opal file 0x7 structure. Assumes a little-endian CPU.
  60. typedef struct FURI_PACKED {
  61. uint32_t serial : 32;
  62. uint8_t check_digit : 4;
  63. bool blocked : 1;
  64. uint16_t txn_number : 16;
  65. int32_t balance : 21;
  66. uint16_t days : 15;
  67. uint16_t minutes : 11;
  68. uint8_t mode : 3;
  69. uint16_t usage : 4;
  70. bool auto_topup : 1;
  71. uint8_t weekly_journeys : 4;
  72. uint16_t checksum : 16;
  73. } OpalFile;
  74. static_assert(sizeof(OpalFile) == 16, "OpalFile");
  75. // Converts an Opal timestamp to DateTime.
  76. //
  77. // Opal measures days since 1980-01-01 and minutes since midnight, and presumes
  78. // all days are 1440 minutes.
  79. static void opal_days_minutes_to_datetime(uint16_t days, uint16_t minutes, DateTime* out) {
  80. out->year = 1980;
  81. out->month = 1;
  82. // 1980-01-01 is a Tuesday
  83. out->weekday = ((days + 1) % 7) + 1;
  84. out->hour = minutes / 60;
  85. out->minute = minutes % 60;
  86. out->second = 0;
  87. // What year is it?
  88. for(;;) {
  89. const uint16_t num_days_in_year = datetime_get_days_per_year(out->year);
  90. if(days < num_days_in_year) break;
  91. days -= num_days_in_year;
  92. out->year++;
  93. }
  94. // 1-index the day of the year
  95. days++;
  96. for(;;) {
  97. // What month is it?
  98. const bool is_leap = datetime_is_leap_year(out->year);
  99. const uint8_t num_days_in_month = datetime_get_days_per_month(is_leap, out->month);
  100. if(days <= num_days_in_month) break;
  101. days -= num_days_in_month;
  102. out->month++;
  103. }
  104. out->day = days;
  105. }
  106. bool opal_parse(const MfDesfireData* data, FuriString* parsed_data) {
  107. furi_assert(parsed_data);
  108. bool parsed = false;
  109. do {
  110. const MfDesfireApplication* app = mf_desfire_get_application(data, &opal_app_id);
  111. if(app == NULL) break;
  112. const MfDesfireFileSettings* file_settings =
  113. mf_desfire_get_file_settings(app, &opal_file_id);
  114. if(file_settings == NULL || file_settings->type != MfDesfireFileTypeStandard ||
  115. file_settings->data.size != sizeof(OpalFile))
  116. break;
  117. const MfDesfireFileData* file_data = mf_desfire_get_file_data(app, &opal_file_id);
  118. if(file_data == NULL) break;
  119. const OpalFile* opal_file = simple_array_cget_data(file_data->data);
  120. const uint8_t serial2 = opal_file->serial / 10000000;
  121. const uint16_t serial3 = (opal_file->serial / 1000) % 10000;
  122. const uint16_t serial4 = (opal_file->serial % 1000);
  123. if(opal_file->check_digit > 9) break;
  124. // Negative balance. Make this a positive value again and record the
  125. // sign separately, because then we can handle balances of -99..-1
  126. // cents, as the "dollars" division below would result in a positive
  127. // zero value.
  128. const bool is_negative_balance = (opal_file->balance < 0);
  129. const char* sign = is_negative_balance ? "-" : "";
  130. const int32_t balance = is_negative_balance ? labs(opal_file->balance) : //-V1081
  131. opal_file->balance;
  132. const uint8_t balance_cents = balance % 100;
  133. const int32_t balance_dollars = balance / 100;
  134. DateTime timestamp;
  135. opal_days_minutes_to_datetime(opal_file->days, opal_file->minutes, &timestamp);
  136. // Usages 4..6 associated with the Manly Ferry, which correspond to
  137. // usages 1..3 for other modes.
  138. const bool is_manly_ferry = (opal_file->usage >= 4) && (opal_file->usage <= 6);
  139. // 3..7 are "reserved", but we use 4 to indicate the Manly Ferry.
  140. const uint8_t mode = is_manly_ferry ? 4 : opal_file->mode;
  141. const uint8_t usage = is_manly_ferry ? opal_file->usage - 3 : opal_file->usage;
  142. const char* mode_str = opal_modes[mode > 4 ? 3 : mode];
  143. const char* usage_str = opal_usages[usage > 12 ? 13 : usage];
  144. furi_string_printf(
  145. parsed_data,
  146. "\e#Opal: $%s%ld.%02hu\nNo.: 3085 22%02hhu %04hu %03hu%01hhu\n%s, %s\n",
  147. sign,
  148. balance_dollars,
  149. balance_cents,
  150. serial2,
  151. serial3,
  152. serial4,
  153. opal_file->check_digit,
  154. mode_str,
  155. usage_str);
  156. FuriString* timestamp_str = furi_string_alloc();
  157. locale_format_date(timestamp_str, &timestamp, locale_get_date_format(), "-");
  158. furi_string_cat(parsed_data, timestamp_str);
  159. furi_string_cat(parsed_data, " at ");
  160. locale_format_time(timestamp_str, &timestamp, locale_get_time_format(), false);
  161. furi_string_cat(parsed_data, timestamp_str);
  162. furi_string_free(timestamp_str);
  163. furi_string_cat_printf(
  164. parsed_data,
  165. "\nWeekly journeys: %hhu, Txn #%hu\n",
  166. opal_file->weekly_journeys,
  167. opal_file->txn_number);
  168. if(opal_file->auto_topup) {
  169. furi_string_cat_str(parsed_data, "Auto-topup enabled\n");
  170. }
  171. if(opal_file->blocked) {
  172. furi_string_cat_str(parsed_data, "Card blocked\n");
  173. }
  174. parsed = true;
  175. } while(false);
  176. return parsed;
  177. }
  178. static NfcCommand opal_poller_callback(NfcGenericEvent event, void* context) {
  179. furi_assert(event.protocol == NfcProtocolMfDesfire);
  180. Metroflip* app = context;
  181. NfcCommand command = NfcCommandContinue;
  182. FuriString* parsed_data = furi_string_alloc();
  183. Widget* widget = app->widget;
  184. furi_string_reset(app->text_box_store);
  185. const MfDesfirePollerEvent* mf_desfire_event = event.event_data;
  186. if(mf_desfire_event->type == MfDesfirePollerEventTypeReadSuccess) {
  187. nfc_device_set_data(
  188. app->nfc_device, NfcProtocolMfDesfire, nfc_poller_get_data(app->poller));
  189. const MfDesfireData* data = nfc_device_get_data(app->nfc_device, NfcProtocolMfDesfire);
  190. if(!opal_parse(data, parsed_data)) {
  191. furi_string_reset(app->text_box_store);
  192. FURI_LOG_I(TAG, "Unknown card type");
  193. furi_string_printf(parsed_data, "\e#Unknown card\n");
  194. }
  195. widget_add_text_scroll_element(widget, 0, 0, 128, 64, furi_string_get_cstr(parsed_data));
  196. widget_add_button_element(
  197. widget, GuiButtonTypeRight, "Exit", metroflip_exit_widget_callback, app);
  198. widget_add_button_element(
  199. widget, GuiButtonTypeCenter, "Save", metroflip_save_widget_callback, app);
  200. furi_string_free(parsed_data);
  201. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewWidget);
  202. metroflip_app_blink_stop(app);
  203. command = NfcCommandStop;
  204. } else if(mf_desfire_event->type == MfDesfirePollerEventTypeReadFailed) {
  205. view_dispatcher_send_custom_event(app->view_dispatcher, MetroflipCustomEventPollerSuccess);
  206. command = NfcCommandContinue;
  207. }
  208. return command;
  209. }
  210. static void opal_on_enter(Metroflip* app) {
  211. dolphin_deed(DolphinDeedNfcRead);
  212. if(app->data_loaded) {
  213. Storage* storage = furi_record_open(RECORD_STORAGE);
  214. FlipperFormat* ff = flipper_format_file_alloc(storage);
  215. if(flipper_format_file_open_existing(ff, app->file_path)) {
  216. mf_desfire_load(app->mfdes_data, ff, 2);
  217. FuriString* parsed_data = furi_string_alloc();
  218. Widget* widget = app->widget;
  219. furi_string_reset(app->text_box_store);
  220. opal_parse(app->mfdes_data, parsed_data);
  221. widget_add_text_scroll_element(
  222. widget, 0, 0, 128, 64, furi_string_get_cstr(parsed_data));
  223. widget_add_button_element(
  224. widget, GuiButtonTypeRight, "Exit", metroflip_exit_widget_callback, app);
  225. widget_add_button_element(
  226. widget, GuiButtonTypeCenter, "Delete", metroflip_delete_widget_callback, app);
  227. furi_string_free(parsed_data);
  228. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewWidget);
  229. }
  230. flipper_format_free(ff);
  231. } else {
  232. // Setup view
  233. Popup* popup = app->popup;
  234. popup_set_header(popup, "Apply\n card to\nthe back", 68, 30, AlignLeft, AlignTop);
  235. popup_set_icon(popup, 0, 3, &I_RFIDDolphinReceive_97x61);
  236. // Start worker
  237. view_dispatcher_switch_to_view(app->view_dispatcher, MetroflipViewPopup);
  238. nfc_scanner_alloc(app->nfc);
  239. app->poller = nfc_poller_alloc(app->nfc, NfcProtocolMfDesfire);
  240. nfc_poller_start(app->poller, opal_poller_callback, app);
  241. metroflip_app_blink_start(app);
  242. }
  243. }
  244. static bool opal_on_event(Metroflip* app, SceneManagerEvent event) {
  245. bool consumed = false;
  246. if(event.type == SceneManagerEventTypeCustom) {
  247. if(event.event == MetroflipCustomEventCardDetected) {
  248. Popup* popup = app->popup;
  249. popup_set_header(popup, "DON'T\nMOVE", 68, 30, AlignLeft, AlignTop);
  250. consumed = true;
  251. } else if(event.event == MetroflipCustomEventCardLost) {
  252. Popup* popup = app->popup;
  253. popup_set_header(popup, "Card \n lost", 68, 30, AlignLeft, AlignTop);
  254. consumed = true;
  255. } else if(event.event == MetroflipCustomEventWrongCard) {
  256. Popup* popup = app->popup;
  257. popup_set_header(popup, "WRONG \n CARD", 68, 30, AlignLeft, AlignTop);
  258. consumed = true;
  259. } else if(event.event == MetroflipCustomEventPollerFail) {
  260. Popup* popup = app->popup;
  261. popup_set_header(popup, "Failed", 68, 30, AlignLeft, AlignTop);
  262. consumed = true;
  263. }
  264. } else if(event.type == SceneManagerEventTypeBack) {
  265. scene_manager_search_and_switch_to_previous_scene(app->scene_manager, MetroflipSceneStart);
  266. scene_manager_set_scene_state(app->scene_manager, MetroflipSceneStart, MetroflipSceneAuto);
  267. consumed = true;
  268. }
  269. return consumed;
  270. }
  271. static void opal_on_exit(Metroflip* app) {
  272. widget_reset(app->widget);
  273. metroflip_app_blink_stop(app);
  274. if(app->poller && !app->data_loaded) {
  275. nfc_poller_stop(app->poller);
  276. nfc_poller_free(app->poller);
  277. }
  278. }
  279. /* Actual implementation of app<>plugin interface */
  280. static const MetroflipPlugin opal_plugin = {
  281. .card_name = "Opal",
  282. .plugin_on_enter = opal_on_enter,
  283. .plugin_on_event = opal_on_event,
  284. .plugin_on_exit = opal_on_exit,
  285. };
  286. /* Plugin descriptor to comply with basic plugin specification */
  287. static const FlipperAppPluginDescriptor opal_plugin_descriptor = {
  288. .appid = METROFLIP_SUPPORTED_CARD_PLUGIN_APP_ID,
  289. .ep_api_version = METROFLIP_SUPPORTED_CARD_PLUGIN_API_VERSION,
  290. .entry_point = &opal_plugin,
  291. };
  292. /* Plugin entry point - must return a pointer to const descriptor */
  293. const FlipperAppPluginDescriptor* opal_plugin_ep(void) {
  294. return &opal_plugin_descriptor;
  295. }