10 more apps ported

This commit is contained in:
Willy-JL
2023-10-22 06:02:25 +01:00
parent 32679525e0
commit 25516358d1
133 changed files with 0 additions and 21609 deletions

View File

@@ -1,18 +0,0 @@
App(
appid="mifare_fuzzer",
name="Mifare Fuzzer",
apptype=FlipperAppType.EXTERNAL,
entry_point="mifare_fuzzer_app",
requires=[
"storage",
"gui",
],
stack_size=4 * 1024,
fap_icon="images/mifare_fuzzer_10px.png",
fap_category="NFC",
fap_icon_assets="images",
fap_author="@spheeere98",
fap_weburl="https://github.com/spheeere98/mifare_fuzzer",
fap_version="1.0",
fap_description="App emulates Mifare Classic cards with various UIDs to check how reader reacts on them",
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 139 B

View File

@@ -1,158 +0,0 @@
#include "mifare_fuzzer_i.h"
/// @brief mifare_fuzzer_custom_event_callback()
/// @param context
/// @param event
/// @return
static bool mifare_fuzzer_custom_event_callback(void* context, uint32_t event) {
furi_assert(context);
MifareFuzzerApp* app = context;
return scene_manager_handle_custom_event(app->scene_manager, event);
}
/// @brief mifare_fuzzer_back_event_callback()
/// @param context
/// @return
static bool mifare_fuzzer_back_event_callback(void* context) {
furi_assert(context);
MifareFuzzerApp* app = context;
return scene_manager_handle_back_event(app->scene_manager);
}
/// @brief mifare_fuzzer_tick_event_callback()
/// @param context
static void mifare_fuzzer_tick_event_callback(void* context) {
furi_assert(context);
MifareFuzzerApp* app = context;
scene_manager_handle_tick_event(app->scene_manager);
}
/// @brief mifare_fuzzer_alloc()
/// @return
MifareFuzzerApp* mifare_fuzzer_alloc() {
MifareFuzzerApp* app = malloc(sizeof(MifareFuzzerApp));
app->view_dispatcher = view_dispatcher_alloc();
app->scene_manager = scene_manager_alloc(&mifare_fuzzer_scene_handlers, app);
view_dispatcher_enable_queue(app->view_dispatcher);
view_dispatcher_set_event_callback_context(app->view_dispatcher, app);
view_dispatcher_set_custom_event_callback(
app->view_dispatcher, mifare_fuzzer_custom_event_callback);
view_dispatcher_set_navigation_event_callback(
app->view_dispatcher, mifare_fuzzer_back_event_callback);
// 1000 ticks are about 1 sec
view_dispatcher_set_tick_event_callback(
app->view_dispatcher, mifare_fuzzer_tick_event_callback, MIFARE_FUZZER_TICK_PERIOD);
// Open GUI record
app->gui = furi_record_open(RECORD_GUI);
view_dispatcher_attach_to_gui(app->view_dispatcher, app->gui, ViewDispatcherTypeFullscreen);
// view: select card type
app->submenu_card = submenu_alloc();
view_dispatcher_add_view(
app->view_dispatcher, MifareFuzzerViewSelectCard, submenu_get_view(app->submenu_card));
// view: select attack type
app->submenu_attack = submenu_alloc();
view_dispatcher_add_view(
app->view_dispatcher, MifareFuzzerViewSelectAttack, submenu_get_view(app->submenu_attack));
// view: emulator
app->emulator_view = mifare_fuzzer_emulator_alloc();
view_dispatcher_add_view(
app->view_dispatcher,
MifareFuzzerViewEmulator,
mifare_fuzzer_emulator_get_view(app->emulator_view));
// worker
app->worker = mifare_fuzzer_worker_alloc();
// storage
app->storage = furi_record_open(RECORD_STORAGE);
if(!storage_simply_mkdir(app->storage, MIFARE_FUZZER_APP_FOLDER)) {
FURI_LOG_E(TAG, "Could not create folder: %s", MIFARE_FUZZER_APP_FOLDER);
}
// dialog
app->dialogs = furi_record_open(RECORD_DIALOGS);
// furi strings
app->uid_str = furi_string_alloc();
app->file_path = furi_string_alloc();
app->app_folder = furi_string_alloc_set(MIFARE_FUZZER_APP_FOLDER);
return app;
}
/// @brief mifare_fuzzer_free()
/// @param app
void mifare_fuzzer_free(MifareFuzzerApp* app) {
furi_assert(app);
// Views
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Views");
view_dispatcher_remove_view(app->view_dispatcher, MifareFuzzerViewSelectCard);
view_dispatcher_remove_view(app->view_dispatcher, MifareFuzzerViewSelectAttack);
view_dispatcher_remove_view(app->view_dispatcher, MifareFuzzerViewEmulator);
// Submenus
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Submenus");
submenu_free(app->submenu_card);
submenu_free(app->submenu_attack);
// View Dispatcher
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: View Dispatcher");
view_dispatcher_free(app->view_dispatcher);
// Scene Manager
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Scene Manager");
scene_manager_free(app->scene_manager);
// GUI
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: GUI");
furi_record_close(RECORD_GUI);
app->gui = NULL;
// Worker
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: Worker");
mifare_fuzzer_worker_free(app->worker);
// storage
furi_record_close(RECORD_STORAGE);
app->storage = NULL;
// dialog
furi_record_close(RECORD_DIALOGS);
app->dialogs = NULL;
// furi strings
furi_string_free(app->uid_str);
furi_string_free(app->file_path);
furi_string_free(app->app_folder);
// App
//FURI_LOG_D(TAG, "mifare_fuzzer_free() :: App");
free(app);
}
/// @brief mifare_fuzzer_app (ENTRYPOINT)
/// @param p
/// @return
int32_t mifare_fuzzer_app(void* p) {
UNUSED(p);
//FURI_LOG_D(TAG, "mifare_fuzzer_app()");
MifareFuzzerApp* app = mifare_fuzzer_alloc();
// init some defaults
scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneStart, 0);
scene_manager_set_scene_state(app->scene_manager, MifareFuzzerSceneAttack, 0);
// open scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneStart);
view_dispatcher_run(app->view_dispatcher);
// free
mifare_fuzzer_free(app);
return 0;
}

View File

@@ -1,3 +0,0 @@
#pragma once
typedef struct MifareFuzzerApp MifareFuzzerApp;

View File

@@ -1,14 +0,0 @@
#pragma once
typedef enum MifareFuzzerEvent {
MifareFuzzerEventClassic1k = 1,
MifareFuzzerEventClassic4k,
MifareFuzzerEventUltralight,
MifareFuzzerEventTestValueAttack,
MifareFuzzerEventRandomValuesAttack,
MifareFuzzerEventLoadUIDsFromFileAttack,
MifareFuzzerEventStartAttack,
MifareFuzzerEventStopAttack,
MifareFuzzerEventIncrementTicks,
MifareFuzzerEventDecrementTicks,
} MifareFuzzerEvent;

View File

@@ -1,76 +0,0 @@
#pragma once
#include <furi.h>
#include <furi_hal.h>
#include <gui/gui.h>
#include <gui/view_dispatcher.h>
#include <gui/scene_manager.h>
#include <gui/modules/submenu.h>
#include <dialogs/dialogs.h>
#include <input/input.h>
#include <toolbox/stream/stream.h>
//#include <toolbox/stream/string_stream.h>
//#include <toolbox/stream/file_stream.h>
#include <toolbox/stream/buffered_file_stream.h>
#include "mifare_fuzzer.h"
#include "scenes/mifare_fuzzer_scene.h"
#include "views/mifare_fuzzer_emulator.h"
#include "mifare_fuzzer_worker.h"
#define TAG "MifareFuzzerApp"
#define MIFARE_FUZZER_APP_FOLDER EXT_PATH("mifare_fuzzer")
#define MIFARE_FUZZER_FILE_EXT ".txt"
#define MIFARE_FUZZER_TICK_PERIOD 200
#define MIFARE_FUZZER_DEFAULT_TICKS_BETWEEN_CARDS 10
#define MIFARE_FUZZER_MIN_TICKS_BETWEEN_CARDS 5
#define MIFARE_FUZZER_MAX_TICKS_BETWEEN_CARDS 50
typedef enum MifareFuzzerSceneState {
MifareFuzzerSceneStateClassic1k,
MifareFuzzerSceneStateClassic4k,
MifareFuzzerSceneStateUltralight,
} MifareFuzzerSceneState;
typedef enum {
MifareFuzzerViewSelectCard,
MifareFuzzerViewSelectAttack,
MifareFuzzerViewEmulator,
} MifareFuzzerView;
struct MifareFuzzerApp {
Gui* gui;
ViewDispatcher* view_dispatcher;
SceneManager* scene_manager;
DialogsApp* dialogs;
Storage* storage;
// Common Views
Submenu* submenu_card;
Submenu* submenu_attack;
MifareFuzzerEmulator* emulator_view;
MifareFuzzerWorker* worker;
MifareCard card;
MifareFuzzerAttack attack;
FuriHalNfcDevData nfc_dev_data;
FuriString* app_folder;
FuriString* file_path;
FuriString* uid_str;
Stream* uids_stream;
};

View File

@@ -1,87 +0,0 @@
#include "mifare_fuzzer_worker.h"
/// @brief mifare_fuzzer_worker_alloc()
/// @return
MifareFuzzerWorker* mifare_fuzzer_worker_alloc() {
MifareFuzzerWorker* mifare_fuzzer_worker = malloc(sizeof(MifareFuzzerWorker));
// Worker thread attributes
mifare_fuzzer_worker->thread = furi_thread_alloc_ex(
"MifareFuzzerWorker", 8192, mifare_fuzzer_worker_task, mifare_fuzzer_worker);
mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
return mifare_fuzzer_worker;
}
/// @brief mifare_fuzzer_worker_free()
/// @param mifare_fuzzer_worker
void mifare_fuzzer_worker_free(MifareFuzzerWorker* mifare_fuzzer_worker) {
furi_assert(mifare_fuzzer_worker);
furi_thread_free(mifare_fuzzer_worker->thread);
free(mifare_fuzzer_worker);
}
/// @brief mifare_fuzzer_worker_stop()
/// @param mifare_fuzzer_worker
void mifare_fuzzer_worker_stop(MifareFuzzerWorker* mifare_fuzzer_worker) {
furi_assert(mifare_fuzzer_worker);
if(mifare_fuzzer_worker->state != MifareFuzzerWorkerStateStop) {
mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
furi_thread_join(mifare_fuzzer_worker->thread);
}
}
/// @brief mifare_fuzzer_worker_start()
/// @param mifare_fuzzer_worker
void mifare_fuzzer_worker_start(MifareFuzzerWorker* mifare_fuzzer_worker) {
furi_assert(mifare_fuzzer_worker);
mifare_fuzzer_worker->state = MifareFuzzerWorkerStateEmulate;
furi_thread_start(mifare_fuzzer_worker->thread);
}
/// @brief mifare_fuzzer_worker_task()
/// @param context
/// @return
int32_t mifare_fuzzer_worker_task(void* context) {
MifareFuzzerWorker* mifare_fuzzer_worker = context;
if(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
FuriHalNfcDevData params = mifare_fuzzer_worker->nfc_dev_data;
furi_hal_nfc_exit_sleep();
while(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
furi_hal_nfc_listen(params.uid, params.uid_len, params.atqa, params.sak, false, 500);
furi_delay_ms(50);
}
furi_hal_nfc_sleep();
}
mifare_fuzzer_worker->state = MifareFuzzerWorkerStateStop;
return 0;
}
/// @brief mifare_fuzzer_worker_is_emulating()
/// @param mifare_fuzzer_worker
/// @return
bool mifare_fuzzer_worker_is_emulating(MifareFuzzerWorker* mifare_fuzzer_worker) {
if(mifare_fuzzer_worker->state == MifareFuzzerWorkerStateEmulate) {
return true;
}
return false;
}
/// @brief mifare_fuzzer_worker_set_nfc_dev_data()
/// @param mifare_fuzzer_worker
/// @param nfc_dev_data
void mifare_fuzzer_worker_set_nfc_dev_data(
MifareFuzzerWorker* mifare_fuzzer_worker,
FuriHalNfcDevData nfc_dev_data) {
mifare_fuzzer_worker->nfc_dev_data = nfc_dev_data;
}
/// @brief mifare_fuzzer_worker_get_nfc_dev_data()
/// @param mifare_fuzzer_worker
/// @return
FuriHalNfcDevData mifare_fuzzer_worker_get_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker) {
return mifare_fuzzer_worker->nfc_dev_data;
}

View File

@@ -1,31 +0,0 @@
#pragma once
#include <furi.h>
#include <furi_hal.h>
typedef enum MifareFuzzerWorkerState {
MifareFuzzerWorkerStateEmulate,
MifareFuzzerWorkerStateStop,
} MifareFuzzerWorkerState;
#define UID_LEN 7
#define ATQA_LEN 2
typedef struct MifareFuzzerWorker {
FuriThread* thread;
MifareFuzzerWorkerState state;
FuriHalNfcDevData nfc_dev_data;
} MifareFuzzerWorker;
// worker
MifareFuzzerWorker* mifare_fuzzer_worker_alloc();
void mifare_fuzzer_worker_free(MifareFuzzerWorker* mifare_fuzzer_worker);
void mifare_fuzzer_worker_stop(MifareFuzzerWorker* mifare_fuzzer_worker);
void mifare_fuzzer_worker_start(MifareFuzzerWorker* mifare_fuzzer_worker);
// task
int32_t mifare_fuzzer_worker_task(void* context);
//
bool mifare_fuzzer_worker_is_emulating(MifareFuzzerWorker* mifare_fuzzer_worker);
void mifare_fuzzer_worker_set_nfc_dev_data(
MifareFuzzerWorker* mifare_fuzzer_worker,
FuriHalNfcDevData nfc_dev_data);
FuriHalNfcDevData mifare_fuzzer_worker_get_nfc_dev_data(MifareFuzzerWorker* mifare_fuzzer_worker);

View File

@@ -1,30 +0,0 @@
#include "mifare_fuzzer_scene.h"
// Generate scene on_enter handlers array
#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,
void (*const mifare_fuzzer_on_enter_handlers[])(void*) = {
#include "mifare_fuzzer_scene_config.h"
};
#undef ADD_SCENE
// Generate scene on_event handlers array
#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,
bool (*const mifare_fuzzer_on_event_handlers[])(void* context, SceneManagerEvent event) = {
#include "mifare_fuzzer_scene_config.h"
};
#undef ADD_SCENE
// Generate scene on_exit handlers array
#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,
void (*const mifare_fuzzer_on_exit_handlers[])(void* context) = {
#include "mifare_fuzzer_scene_config.h"
};
#undef ADD_SCENE
// Initialize scene handlers configuration structure
const SceneManagerHandlers mifare_fuzzer_scene_handlers = {
.on_enter_handlers = mifare_fuzzer_on_enter_handlers,
.on_event_handlers = mifare_fuzzer_on_event_handlers,
.on_exit_handlers = mifare_fuzzer_on_exit_handlers,
.scene_num = MifareFuzzerSceneNum,
};

View File

@@ -1,29 +0,0 @@
#pragma once
#include <gui/scene_manager.h>
// Generate scene id and total number
#define ADD_SCENE(prefix, name, id) MifareFuzzerScene##id,
typedef enum {
#include "mifare_fuzzer_scene_config.h"
MifareFuzzerSceneNum,
} MifareFuzzerScene;
#undef ADD_SCENE
extern const SceneManagerHandlers mifare_fuzzer_scene_handlers;
// Generate scene on_enter handlers declaration
#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);
#include "mifare_fuzzer_scene_config.h"
#undef ADD_SCENE
// Generate scene on_event handlers declaration
#define ADD_SCENE(prefix, name, id) \
bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);
#include "mifare_fuzzer_scene_config.h"
#undef ADD_SCENE
// Generate scene on_exit handlers declaration
#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);
#include "mifare_fuzzer_scene_config.h"
#undef ADD_SCENE

View File

@@ -1,143 +0,0 @@
#include "../mifare_fuzzer_i.h"
#include "../mifare_fuzzer_custom_events.h"
enum SubmenuIndex {
SubmenuIndexTestValue,
SubmenuIndexRandomValuesAttack,
SubmenuIndexLoadUIDsFromFile,
};
/// @brief mifare_fuzzer_scene_attack_submenu_callback()
/// @param context
/// @param index
void mifare_fuzzer_scene_attack_submenu_callback(void* context, uint32_t index) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_submenu_callback() :: index = %ld", index);
MifareFuzzerApp* app = context;
uint8_t custom_event = 255;
switch(index) {
case SubmenuIndexTestValue:
custom_event = MifareFuzzerEventTestValueAttack;
break;
case SubmenuIndexRandomValuesAttack:
custom_event = MifareFuzzerEventRandomValuesAttack;
break;
case SubmenuIndexLoadUIDsFromFile:
custom_event = MifareFuzzerEventLoadUIDsFromFileAttack;
break;
default:
return;
}
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_submenu_callback() :: custom_event = %d", custom_event);
view_dispatcher_send_custom_event(app->view_dispatcher, custom_event);
}
/// @brief mifare_fuzzer_scene_attack_on_enter()
/// @param context
void mifare_fuzzer_scene_attack_on_enter(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_enter()");
MifareFuzzerApp* app = context;
Submenu* submenu_attack = app->submenu_attack;
submenu_set_header(submenu_attack, "Mifare Fuzzer (attack)");
submenu_add_item(
submenu_attack,
"Test Values",
SubmenuIndexTestValue,
mifare_fuzzer_scene_attack_submenu_callback,
app);
submenu_add_item(
submenu_attack,
"Random Values",
SubmenuIndexRandomValuesAttack,
mifare_fuzzer_scene_attack_submenu_callback,
app);
submenu_add_item(
submenu_attack,
"Load UIDs from file",
SubmenuIndexLoadUIDsFromFile,
mifare_fuzzer_scene_attack_submenu_callback,
app);
// set selected menu
submenu_set_selected_item(
submenu_attack,
scene_manager_get_scene_state(app->scene_manager, MifareFuzzerSceneAttack));
view_dispatcher_switch_to_view(app->view_dispatcher, MifareFuzzerViewSelectAttack);
}
/// @brief mifare_fuzzer_scene_attack_on_event()
/// @param context
/// @param event
/// @return
bool mifare_fuzzer_scene_attack_on_event(void* context, SceneManagerEvent event) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_event()");
MifareFuzzerApp* app = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_event() :: event.event = %ld", event.event);
if(event.event == MifareFuzzerEventTestValueAttack) {
// save selected item
scene_manager_set_scene_state(
app->scene_manager, MifareFuzzerSceneAttack, SubmenuIndexTestValue);
// set emulator attack
app->attack = MifareFuzzerAttackTestValues;
mifare_fuzzer_emulator_set_attack(app->emulator_view, app->attack);
// open next scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneEmulator);
consumed = true;
} else if(event.event == MifareFuzzerEventRandomValuesAttack) {
// save selected item
scene_manager_set_scene_state(
app->scene_manager, MifareFuzzerSceneAttack, SubmenuIndexRandomValuesAttack);
// set emulator attack
app->attack = MifareFuzzerAttackRandomValues;
mifare_fuzzer_emulator_set_attack(app->emulator_view, app->attack);
// open next scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneEmulator);
consumed = true;
} else if(event.event == MifareFuzzerEventLoadUIDsFromFileAttack) {
// save selected item
scene_manager_set_scene_state(
app->scene_manager, MifareFuzzerSceneAttack, SubmenuIndexLoadUIDsFromFile);
// set emulator attack
app->attack = MifareFuzzerAttackLoadUidsFromFile;
mifare_fuzzer_emulator_set_attack(app->emulator_view, app->attack);
// open dialog file
DialogsFileBrowserOptions browser_options;
dialog_file_browser_set_basic_options(&browser_options, MIFARE_FUZZER_FILE_EXT, NULL);
browser_options.hide_ext = false;
bool res = dialog_file_browser_show(
app->dialogs, app->file_path, app->app_folder, &browser_options);
if(res) {
app->uids_stream = buffered_file_stream_alloc(app->storage);
res = buffered_file_stream_open(
app->uids_stream,
furi_string_get_cstr(app->file_path),
FSAM_READ,
FSOM_OPEN_EXISTING);
if(res) {
// open next scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneEmulator);
} else {
buffered_file_stream_close(app->uids_stream);
}
}
consumed = true;
}
} else if(event.type == SceneManagerEventTypeTick) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_event() :: SceneManagerEventTypeTick");
//consumed = true;
}
return consumed;
}
/// @brief mifare_fuzzer_scene_attack_on_exit()
/// @param context
void mifare_fuzzer_scene_attack_on_exit(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_attack_on_exit()");
MifareFuzzerApp* app = context;
submenu_reset(app->submenu_attack);
}

View File

@@ -1,3 +0,0 @@
ADD_SCENE(mifare_fuzzer, start, Start)
ADD_SCENE(mifare_fuzzer, attack, Attack)
ADD_SCENE(mifare_fuzzer, emulator, Emulator)

View File

@@ -1,242 +0,0 @@
#include "../mifare_fuzzer_i.h"
uint8_t tick_counter = 0;
uint8_t attack_step = 0;
uint8_t id_uid_test[9][7] = {
{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17},
{0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28},
{0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39},
{0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a},
{0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b},
{0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c},
{0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d},
{0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e},
{0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f},
};
/// @brief mifare_fuzzer_scene_emulator_callback()
/// @param event
/// @param context
static void mifare_fuzzer_scene_emulator_callback(MifareFuzzerEvent event, void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_callback()");
furi_assert(context);
MifareFuzzerApp* app = context;
view_dispatcher_send_custom_event(app->view_dispatcher, event);
}
/// @brief mifare_fuzzer_scene_emulator_on_enter()
/// @param context
void mifare_fuzzer_scene_emulator_on_enter(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_enter()");
MifareFuzzerApp* app = context;
MifareFuzzerEmulator* emulator = app->emulator_view;
// init callback
mifare_fuzzer_emulator_set_callback(emulator, mifare_fuzzer_scene_emulator_callback, app);
// init ticks
tick_counter = 0;
mifare_fuzzer_emulator_set_tick_num(app->emulator_view, tick_counter);
emulator->ticks_between_cards = MIFARE_FUZZER_DEFAULT_TICKS_BETWEEN_CARDS;
mifare_fuzzer_emulator_set_ticks_between_cards(
app->emulator_view, emulator->ticks_between_cards);
// init default card data
FuriHalNfcDevData nfc_dev_data;
nfc_dev_data.atqa[0] = 0x00;
nfc_dev_data.atqa[1] = 0x00;
nfc_dev_data.sak = 0x00;
if(app->card == MifareCardUltralight) {
nfc_dev_data.uid_len = 0x07;
} else {
nfc_dev_data.uid_len = 0x04;
}
for(uint32_t i = 0; i < nfc_dev_data.uid_len; i++) {
nfc_dev_data.uid[i] = 0x00;
}
mifare_fuzzer_emulator_set_nfc_dev_data(app->emulator_view, nfc_dev_data);
// init other vars
attack_step = 0;
// switch to view
view_dispatcher_switch_to_view(app->view_dispatcher, MifareFuzzerViewEmulator);
}
/// @brief mifare_fuzzer_scene_emulator_on_event()
/// @param context
/// @param event
/// @return
bool mifare_fuzzer_scene_emulator_on_event(void* context, SceneManagerEvent event) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event()");
FuriHalNfcDevData nfc_dev_data;
MifareFuzzerApp* app = context;
MifareFuzzerEmulator* emulator = app->emulator_view;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == MifareFuzzerEventStartAttack) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event() :: MifareFuzzerEventStartAttack");
// Stop worker
mifare_fuzzer_worker_stop(app->worker);
// Set card type
// TODO: Move somewhere else, I do not like this to be there
if(app->card == MifareCardClassic1k) {
nfc_dev_data.atqa[0] = 0x04;
nfc_dev_data.atqa[1] = 0x00;
nfc_dev_data.sak = 0x08;
nfc_dev_data.uid_len = 0x04;
} else if(app->card == MifareCardClassic4k) {
nfc_dev_data.atqa[0] = 0x02;
nfc_dev_data.atqa[1] = 0x00;
nfc_dev_data.sak = 0x18;
nfc_dev_data.uid_len = 0x04;
} else if(app->card == MifareCardUltralight) {
nfc_dev_data.atqa[0] = 0x44;
nfc_dev_data.atqa[1] = 0x00;
nfc_dev_data.sak = 0x00;
nfc_dev_data.uid_len = 0x07;
}
// Set UIDs
if(app->attack == MifareFuzzerAttackTestValues) {
// Load test UIDs
for(uint8_t i = 0; i < nfc_dev_data.uid_len; i++) {
nfc_dev_data.uid[i] = id_uid_test[attack_step][i];
}
// Next UIDs on next loop
if(attack_step >= 8) {
attack_step = 0;
} else {
attack_step++;
}
} else if(app->attack == MifareFuzzerAttackRandomValues) {
if(app->card == MifareCardUltralight) {
// First byte of a 7 byte UID is the manufacturer-code
// https://github.com/Proxmark/proxmark3/blob/master/client/taginfo.c
// https://stackoverflow.com/questions/37837730/mifare-cards-distinguish-between-4-byte-and-7-byte-uids
// https://stackoverflow.com/questions/31233652/how-to-detect-manufacturer-from-nfc-tag-using-android
// TODO: Manufacture-code must be selectable from a list
// use a fixed manufacture-code for now: 0x04 = NXP Semiconductors Germany
nfc_dev_data.uid[0] = 0x04;
for(uint8_t i = 1; i < nfc_dev_data.uid_len; i++) {
nfc_dev_data.uid[i] = (furi_hal_random_get() & 0xFF);
}
} else {
for(uint8_t i = 0; i < nfc_dev_data.uid_len; i++) {
nfc_dev_data.uid[i] = (furi_hal_random_get() & 0xFF);
}
}
} else if(app->attack == MifareFuzzerAttackLoadUidsFromFile) {
//bool end_of_list = false;
// read stream
while(true) {
furi_string_reset(app->uid_str);
if(!stream_read_line(app->uids_stream, app->uid_str)) {
// restart from beginning on empty line
stream_rewind(app->uids_stream);
continue;
//end_of_list = true;
}
// Skip comments
if(furi_string_get_char(app->uid_str, 0) == '#') continue;
// Skip lines with invalid length
if((furi_string_size(app->uid_str) != 9) &&
(furi_string_size(app->uid_str) != 15))
continue;
break;
}
// TODO: stop on end of list?
//if(end_of_list) break;
// parse string to UID
// TODO: a better validation on input?
for(uint8_t i = 0; i < nfc_dev_data.uid_len; i++) {
if(i <= ((furi_string_size(app->uid_str) - 1) / 2)) {
char temp_str[3];
temp_str[0] = furi_string_get_cstr(app->uid_str)[i * 2];
temp_str[1] = furi_string_get_cstr(app->uid_str)[i * 2 + 1];
temp_str[2] = '\0';
nfc_dev_data.uid[i] = (uint8_t)strtol(temp_str, NULL, 16);
} else {
nfc_dev_data.uid[i] = 0x00;
}
}
}
mifare_fuzzer_worker_set_nfc_dev_data(app->worker, nfc_dev_data);
mifare_fuzzer_emulator_set_nfc_dev_data(app->emulator_view, nfc_dev_data);
// Reset tick_counter
tick_counter = 0;
mifare_fuzzer_emulator_set_tick_num(app->emulator_view, tick_counter);
// Start worker
mifare_fuzzer_worker_start(app->worker);
} else if(event.event == MifareFuzzerEventStopAttack) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event() :: MifareFuzzerEventStopAttack");
// Stop worker
mifare_fuzzer_worker_stop(app->worker);
} else if(event.event == MifareFuzzerEventIncrementTicks) {
if(!emulator->is_attacking) {
if(emulator->ticks_between_cards < MIFARE_FUZZER_MAX_TICKS_BETWEEN_CARDS) {
emulator->ticks_between_cards++;
mifare_fuzzer_emulator_set_ticks_between_cards(
app->emulator_view, emulator->ticks_between_cards);
};
};
} else if(event.event == MifareFuzzerEventDecrementTicks) {
if(!emulator->is_attacking) {
if(emulator->ticks_between_cards > MIFARE_FUZZER_MIN_TICKS_BETWEEN_CARDS) {
emulator->ticks_between_cards--;
mifare_fuzzer_emulator_set_ticks_between_cards(
app->emulator_view, emulator->ticks_between_cards);
};
};
}
consumed = true;
} else if(event.type == SceneManagerEventTypeTick) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_event() :: SceneManagerEventTypeTick");
// Used to check tick length (not perfect but enough)
//FuriHalRtcDateTime curr_dt;
//furi_hal_rtc_get_datetime(&curr_dt);
//FURI_LOG_D(TAG, "Time is: %.2d:%.2d:%.2d", curr_dt.hour, curr_dt.minute, curr_dt.second);
// If emulator is attacking
if(emulator->is_attacking) {
// increment tick_counter
tick_counter++;
mifare_fuzzer_emulator_set_tick_num(app->emulator_view, tick_counter);
//FURI_LOG_D(TAG, "tick_counter is: %.2d", tick_counter);
if(tick_counter >= emulator->ticks_between_cards) {
// Queue event for changing UID
view_dispatcher_send_custom_event(
app->view_dispatcher, MifareFuzzerEventStartAttack);
}
}
consumed = true;
}
return consumed;
}
/// @brief mifare_fuzzer_scene_emulator_on_exit()
/// @param context
void mifare_fuzzer_scene_emulator_on_exit(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_emulator_on_exit()");
MifareFuzzerApp* app = context;
mifare_fuzzer_worker_stop(app->worker);
if(app->attack == MifareFuzzerAttackLoadUidsFromFile) {
furi_string_reset(app->uid_str);
stream_rewind(app->uids_stream);
buffered_file_stream_close(app->uids_stream);
}
}

View File

@@ -1,124 +0,0 @@
#include "../mifare_fuzzer_i.h"
#include "../mifare_fuzzer_custom_events.h"
enum SubmenuIndex {
SubmenuIndexClassic1k,
SubmenuIndexClassic4k,
SubmenuIndexUltralight,
};
/// @brief mifare_fuzzer_scene_start_submenu_callback()
/// @param context
/// @param index
void mifare_fuzzer_scene_start_submenu_callback(void* context, uint32_t index) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_submenu_callback() :: index = %ld", index);
MifareFuzzerApp* app = context;
uint8_t custom_event = 255;
switch(index) {
case SubmenuIndexClassic1k:
custom_event = MifareFuzzerEventClassic1k;
break;
case SubmenuIndexClassic4k:
custom_event = MifareFuzzerEventClassic4k;
break;
case SubmenuIndexUltralight:
custom_event = MifareFuzzerEventUltralight;
break;
default:
return;
}
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_submenu_callback() :: custom_event = %d", custom_event);
view_dispatcher_send_custom_event(app->view_dispatcher, custom_event);
}
/// @brief mifare_fuzzer_scene_start_on_enter()
/// @param context
void mifare_fuzzer_scene_start_on_enter(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_enter()");
MifareFuzzerApp* app = context;
Submenu* submenu_card = app->submenu_card;
submenu_set_header(submenu_card, "Mifare Fuzzer (card)");
submenu_add_item(
submenu_card,
"Classic 1k",
SubmenuIndexClassic1k,
mifare_fuzzer_scene_start_submenu_callback,
app);
submenu_add_item(
submenu_card,
"Classic 4k",
SubmenuIndexClassic4k,
mifare_fuzzer_scene_start_submenu_callback,
app);
submenu_add_item(
submenu_card,
"Ultralight",
SubmenuIndexUltralight,
mifare_fuzzer_scene_start_submenu_callback,
app);
// set selected menu
submenu_set_selected_item(
submenu_card, scene_manager_get_scene_state(app->scene_manager, MifareFuzzerSceneStart));
view_dispatcher_switch_to_view(app->view_dispatcher, MifareFuzzerViewSelectCard);
}
/// @brief mifare_fuzzer_scene_start_on_event()
/// @param context
/// @param event
/// @return
bool mifare_fuzzer_scene_start_on_event(void* context, SceneManagerEvent event) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_event()");
MifareFuzzerApp* app = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_event() :: event.event = %ld", event.event);
if(event.event == MifareFuzzerEventClassic1k) {
// save selected item
scene_manager_set_scene_state(
app->scene_manager, MifareFuzzerSceneStart, SubmenuIndexClassic1k);
// set emulator card
app->card = MifareCardClassic1k;
mifare_fuzzer_emulator_set_card(app->emulator_view, app->card);
// open next scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneAttack);
consumed = true;
} else if(event.event == MifareFuzzerEventClassic4k) {
// save selected item
scene_manager_set_scene_state(
app->scene_manager, MifareFuzzerSceneStart, SubmenuIndexClassic4k);
// set emulator card
app->card = MifareCardClassic4k;
mifare_fuzzer_emulator_set_card(app->emulator_view, app->card);
// open next scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneAttack);
consumed = true;
} else if(event.event == MifareFuzzerEventUltralight) {
// save selected item
scene_manager_set_scene_state(
app->scene_manager, MifareFuzzerSceneStart, SubmenuIndexUltralight);
// set emulator card
app->card = MifareCardUltralight;
mifare_fuzzer_emulator_set_card(app->emulator_view, app->card);
// open next scene
scene_manager_next_scene(app->scene_manager, MifareFuzzerSceneAttack);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeTick) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_event() :: SceneManagerEventTypeTick");
//consumed = true;
}
return consumed;
}
/// @brief mifare_fuzzer_scene_start_on_exit()
/// @param context
void mifare_fuzzer_scene_start_on_exit(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_scene_start_on_exit()");
MifareFuzzerApp* app = context;
submenu_reset(app->submenu_card);
}

View File

@@ -1,301 +0,0 @@
#include "mifare_fuzzer_emulator.h"
#define TAG "MifareFuzzerApp_emulator_view"
// Screen is 128 × 64 pixels
/// @brief mifare_fuzzer_emulator_set_callback
/// @param mifare_fuzzer_emulator
/// @param callback
/// @param context
void mifare_fuzzer_emulator_set_callback(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
MifareFuzzerEmulatorCallback callback,
void* context) {
furi_assert(mifare_fuzzer_emulator);
furi_assert(callback);
mifare_fuzzer_emulator->callback = callback;
mifare_fuzzer_emulator->context = context;
}
/// @brief mifare_fuzzer_emulator_draw_callback
/// @param canvas
/// @param _model
static void mifare_fuzzer_emulator_draw_callback(Canvas* canvas, void* _model) {
MifareFuzzerEmulatorModel* model = _model;
FuriString* furi_string = furi_string_alloc();
canvas_clear(canvas);
canvas_set_color(canvas, ColorBlack);
// Primary font
canvas_set_font(canvas, FontPrimary);
// Title
canvas_draw_str(canvas, 4, 11, model->title);
// Emulated UID
uint8_t cpos;
char uid[25];
char uid_char[3];
cpos = 0;
for(uint8_t i = 0; i < model->nfc_dev_data.uid_len; i++) {
if(i > 0) {
uid[cpos] = ':';
cpos++;
}
snprintf(uid_char, sizeof(uid_char), "%02X", model->nfc_dev_data.uid[i]);
uid[cpos] = uid_char[0];
cpos++;
uid[cpos] = uid_char[1];
cpos++;
}
uid[cpos] = 0x00;
canvas_draw_str_aligned(canvas, 128 / 2, 43, AlignCenter, AlignCenter, uid);
// Secondary font
canvas_set_font(canvas, FontSecondary);
// Card
canvas_draw_str(canvas, 4, 22, "c:");
canvas_draw_str(canvas, 15, 22, model->mifare_card_dsc);
// Timing
furi_string_printf(furi_string, "%d", model->ticks_between_cards);
canvas_draw_str(canvas, 90, 22, "t:");
canvas_draw_str(canvas, 100, 22, furi_string_get_cstr(furi_string));
// Attack
canvas_draw_str(canvas, 4, 33, "a:");
canvas_draw_str(canvas, 15, 33, model->attack_dsc);
if(!model->is_attacking) {
elements_button_left(canvas, "t-1");
elements_button_center(canvas, "Start");
elements_button_right(canvas, "t+1");
} else {
canvas_draw_line(canvas, 1, 49, (128 * model->tick_num / model->ticks_between_cards), 49);
elements_button_center(canvas, "Stop");
}
// Free temp string
furi_string_free(furi_string);
}
/// @brief mifare_fuzzer_emulator_input_callback
/// @param event
/// @param context
/// @return
static bool mifare_fuzzer_emulator_input_callback(InputEvent* event, void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_emulator_input_callback()");
furi_assert(context);
MifareFuzzerEmulator* mifare_fuzzer_emulator = context;
bool consumed = false;
if(event->type == InputTypeShort) {
if(event->key == InputKeyRight) {
if(!mifare_fuzzer_emulator->is_attacking) {
mifare_fuzzer_emulator->callback(
MifareFuzzerEventIncrementTicks, mifare_fuzzer_emulator->context);
};
consumed = true;
} else if(event->key == InputKeyLeft) {
if(!mifare_fuzzer_emulator->is_attacking) {
mifare_fuzzer_emulator->callback(
MifareFuzzerEventDecrementTicks, mifare_fuzzer_emulator->context);
};
consumed = true;
} else if(event->key == InputKeyUp) {
consumed = true;
} else if(event->key == InputKeyDown) {
consumed = true;
} else if(event->key == InputKeyOk) {
// Toggle attack
if(mifare_fuzzer_emulator->is_attacking) {
mifare_fuzzer_emulator->is_attacking = false;
mifare_fuzzer_emulator->callback(
MifareFuzzerEventStopAttack, mifare_fuzzer_emulator->context);
} else {
mifare_fuzzer_emulator->is_attacking = true;
mifare_fuzzer_emulator->callback(
MifareFuzzerEventStartAttack, mifare_fuzzer_emulator->context);
}
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{ model->is_attacking = mifare_fuzzer_emulator->is_attacking; },
true);
consumed = true;
}
}
return consumed;
}
/// @brief mifare_fuzzer_emulator_enter_callback
/// @param context
static void mifare_fuzzer_emulator_enter_callback(void* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_emulator_enter_callback()");
furi_assert(context);
MifareFuzzerEmulator* mifare_fuzzer_emulator = context;
//UNUSED(mifare_fuzzer_emulator);
mifare_fuzzer_emulator->is_attacking = false;
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{ model->is_attacking = false; },
true);
}
/// @brief mifare_fuzzer_emulator_alloc
/// @return
MifareFuzzerEmulator* mifare_fuzzer_emulator_alloc() {
MifareFuzzerEmulator* mifare_fuzzer_emulator = malloc(sizeof(MifareFuzzerEmulator));
mifare_fuzzer_emulator->view = view_alloc();
view_set_context(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator);
view_allocate_model(
mifare_fuzzer_emulator->view, ViewModelTypeLocking, sizeof(MifareFuzzerEmulatorModel));
view_set_draw_callback(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator_draw_callback);
view_set_input_callback(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator_input_callback);
view_set_enter_callback(mifare_fuzzer_emulator->view, mifare_fuzzer_emulator_enter_callback);
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{ model->title = "Mifare Fuzzer (emulator)"; },
true);
return mifare_fuzzer_emulator;
}
/// @brief mifare_fuzzer_emulator_free
/// @param context
void mifare_fuzzer_emulator_free(MifareFuzzerEmulator* context) {
//FURI_LOG_D(TAG, "mifare_fuzzer_emulator_free()");
furi_assert(context);
MifareFuzzerEmulator* mifare_fuzzer_emulator = context;
/*
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel* model,
{
UNUSED(model);
},
true
);
*/
view_free(mifare_fuzzer_emulator->view);
free(mifare_fuzzer_emulator);
}
/// @brief mifare_fuzzer_emulator_get_view
/// @param mifare_fuzzer_emulator
/// @return
View* mifare_fuzzer_emulator_get_view(MifareFuzzerEmulator* mifare_fuzzer_emulator) {
furi_assert(mifare_fuzzer_emulator);
return mifare_fuzzer_emulator->view;
}
/// @brief Set card type
/// @param mifare_fuzzer_emulator
/// @param mifare_card
void mifare_fuzzer_emulator_set_card(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
MifareCard mifare_card) {
furi_assert(mifare_fuzzer_emulator);
furi_assert(mifare_card);
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{
model->mifare_card = mifare_card;
switch(mifare_card) {
case MifareCardClassic1k:
model->mifare_card_dsc = "Classic 1k";
break;
case MifareCardClassic4k:
model->mifare_card_dsc = "Classic 4k";
break;
case MifareCardUltralight:
model->mifare_card_dsc = "Ultralight";
break;
}
},
true);
}
/// @brief Set attack type
/// @param mifare_fuzzer_emulator
/// @param mifare_attack
void mifare_fuzzer_emulator_set_attack(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
MifareFuzzerAttack mifare_attack) {
furi_assert(mifare_fuzzer_emulator);
furi_assert(mifare_attack);
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{
model->attack = mifare_attack;
switch(mifare_attack) {
case MifareFuzzerAttackTestValues:
model->attack_dsc = "Test values";
break;
case MifareFuzzerAttackRandomValues:
model->attack_dsc = "Random values";
break;
case MifareFuzzerAttackLoadUidsFromFile:
model->attack_dsc = "Load Uids From File";
break;
}
},
true);
}
/// @brief mifare_fuzzer_emulator_set_nfc_dev_data
/// @param mifare_fuzzer_emulator
/// @param nfc_dev_data
void mifare_fuzzer_emulator_set_nfc_dev_data(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
FuriHalNfcDevData nfc_dev_data) {
furi_assert(mifare_fuzzer_emulator);
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{ model->nfc_dev_data = nfc_dev_data; },
true);
}
/// @brief mifare_fuzzer_emulator_set_ticks_between_cards
/// @param mifare_fuzzer_emulator
/// @param ticks
void mifare_fuzzer_emulator_set_ticks_between_cards(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
uint8_t ticks) {
furi_assert(mifare_fuzzer_emulator);
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{ model->ticks_between_cards = ticks; },
true);
}
/// @brief mifare_fuzzer_emulator_set_tick_num
/// @param mifare_fuzzer_emulator
/// @param tick_num
void mifare_fuzzer_emulator_set_tick_num(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
uint8_t tick_num) {
furi_assert(mifare_fuzzer_emulator);
with_view_model(
mifare_fuzzer_emulator->view,
MifareFuzzerEmulatorModel * model,
{ model->tick_num = tick_num; },
true);
}

View File

@@ -1,70 +0,0 @@
#pragma once
#include "../mifare_fuzzer_custom_events.h"
#include <furi.h>
#include <furi_hal.h>
#include <gui/view.h>
#include <gui/elements.h>
typedef void (*MifareFuzzerEmulatorCallback)(MifareFuzzerEvent event, void* context);
typedef enum MifareCard {
MifareCardClassic1k = 1,
MifareCardClassic4k,
MifareCardUltralight,
} MifareCard;
typedef enum MifareFuzzerAttack {
MifareFuzzerAttackTestValues = 1,
MifareFuzzerAttackRandomValues,
MifareFuzzerAttackLoadUidsFromFile,
} MifareFuzzerAttack;
typedef struct MifareFuzzerEmulator {
View* view;
MifareFuzzerEmulatorCallback callback;
void* context;
bool is_attacking;
uint8_t ticks_between_cards;
} MifareFuzzerEmulator;
typedef struct MifareFuzzerEmulatorModel {
const char* title;
MifareCard mifare_card;
const char* mifare_card_dsc;
MifareFuzzerAttack attack;
const char* attack_dsc;
FuriHalNfcDevData nfc_dev_data;
bool is_attacking;
uint8_t tick_num;
uint8_t ticks_between_cards;
} MifareFuzzerEmulatorModel;
MifareFuzzerEmulator* mifare_fuzzer_emulator_alloc();
void mifare_fuzzer_emulator_free(MifareFuzzerEmulator* context);
View* mifare_fuzzer_emulator_get_view(MifareFuzzerEmulator* context);
void mifare_fuzzer_emulator_set_card(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
MifareCard mifare_card);
void mifare_fuzzer_emulator_set_attack(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
MifareFuzzerAttack mifare_attack);
void mifare_fuzzer_emulator_set_callback(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
MifareFuzzerEmulatorCallback callback,
void* context);
void mifare_fuzzer_emulator_set_nfc_dev_data(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
FuriHalNfcDevData nfc_dev_data);
void mifare_fuzzer_emulator_set_ticks_between_cards(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
uint8_t ticks);
void mifare_fuzzer_emulator_set_tick_num(
MifareFuzzerEmulator* mifare_fuzzer_emulator,
uint8_t tick_num);

View File

@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -1,16 +0,0 @@
App(
appid="mifare_nested",
name="Mifare Nested",
apptype=FlipperAppType.EXTERNAL,
entry_point="mifare_nested_app",
requires=["storage", "gui", "nfc"],
stack_size=4 * 1024,
fap_icon="assets/icon.png",
fap_category="NFC",
fap_private_libs=[Lib(name="nested"), Lib(name="parity"), Lib(name="crypto1")],
fap_icon_assets="assets",
fap_author="AloneLiberty",
fap_description="Recover Mifare Classic keys",
fap_weburl="https://github.com/AloneLiberty/FlipperNested",
fap_version="1.5.2",
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 145 B

View File

@@ -1,118 +0,0 @@
#include "crypto1.h"
#include <string.h>
void crypto1_reset(Crypto1* crypto1) {
furi_assert(crypto1);
crypto1->even = 0;
crypto1->odd = 0;
}
void crypto1_init(Crypto1* crypto1, uint64_t key) {
furi_assert(crypto1);
crypto1->even = 0;
crypto1->odd = 0;
for(int8_t i = 47; i > 0; i -= 2) {
crypto1->odd = crypto1->odd << 1 | FURI_BIT(key, (i - 1) ^ 7);
crypto1->even = crypto1->even << 1 | FURI_BIT(key, i ^ 7);
}
}
uint32_t crypto1_filter(uint32_t in) {
uint32_t out = 0;
out = 0xf22c0 >> (in & 0xf) & 16;
out |= 0x6c9c0 >> (in >> 4 & 0xf) & 8;
out |= 0x3c8b0 >> (in >> 8 & 0xf) & 4;
out |= 0x1e458 >> (in >> 12 & 0xf) & 2;
out |= 0x0d938 >> (in >> 16 & 0xf) & 1;
return FURI_BIT(0xEC57E80A, out);
}
uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted) {
furi_assert(crypto1);
uint8_t out = crypto1_filter(crypto1->odd);
uint32_t feed = out & (!!is_encrypted);
feed ^= !!in;
feed ^= LF_POLY_ODD & crypto1->odd;
feed ^= LF_POLY_EVEN & crypto1->even;
crypto1->even = crypto1->even << 1 | (evenparity32(feed));
FURI_SWAP(crypto1->odd, crypto1->even);
return out;
}
uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted) {
furi_assert(crypto1);
uint8_t out = 0;
for(uint8_t i = 0; i < 8; i++) {
out |= crypto1_bit(crypto1, FURI_BIT(in, i), is_encrypted) << i;
}
return out;
}
uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted) {
furi_assert(crypto1);
uint32_t out = 0;
for(uint8_t i = 0; i < 32; i++) {
out |= (uint32_t)crypto1_bit(crypto1, BEBIT(in, i), is_encrypted) << (24 ^ i);
}
return out;
}
uint32_t prng_successor(uint32_t x, uint32_t n) {
SWAPENDIAN(x);
while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31;
return SWAPENDIAN(x);
}
void crypto1_decrypt(
Crypto1* crypto,
uint8_t* encrypted_data,
uint16_t encrypted_data_bits,
uint8_t* decrypted_data) {
furi_assert(crypto);
furi_assert(encrypted_data);
furi_assert(decrypted_data);
if(encrypted_data_bits < 8) {
uint8_t decrypted_byte = 0;
decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 0)) << 0;
decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 1)) << 1;
decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 2)) << 2;
decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 3)) << 3;
decrypted_data[0] = decrypted_byte;
} else {
for(size_t i = 0; i < encrypted_data_bits / 8; i++) {
decrypted_data[i] = crypto1_byte(crypto, 0, 0) ^ encrypted_data[i];
}
}
}
void crypto1_encrypt(
Crypto1* crypto,
uint8_t* keystream,
uint8_t* plain_data,
uint16_t plain_data_bits,
uint8_t* encrypted_data,
uint8_t* encrypted_parity) {
furi_assert(crypto);
furi_assert(plain_data);
furi_assert(encrypted_data);
furi_assert(encrypted_parity);
if(plain_data_bits < 8) {
encrypted_data[0] = 0;
for(size_t i = 0; i < plain_data_bits; i++) {
encrypted_data[0] |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(plain_data[0], i)) << i;
}
} else {
memset(encrypted_parity, 0, plain_data_bits / 8 + 1);
for(uint8_t i = 0; i < plain_data_bits / 8; i++) {
encrypted_data[i] = crypto1_byte(crypto, keystream ? keystream[i] : 0, 0) ^
plain_data[i];
encrypted_parity[i / 8] |=
(((crypto1_filter(crypto->odd) ^ oddparity8(plain_data[i])) & 0x01)
<< (7 - (i & 0x0007)));
}
}
}

View File

@@ -1,39 +0,0 @@
#include "../../lib/parity/parity.h"
#include <lib/nfc/protocols/mifare_classic.h>
#include <lib/nfc/protocols/crypto1.h>
#include "stddef.h"
#define LF_POLY_ODD (0x29CE5C)
#define LF_POLY_EVEN (0x870804)
#define SWAPENDIAN(x) \
((x) = ((x) >> 8 & 0xff00ff) | ((x)&0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16)
#define BEBIT(x, n) FURI_BIT(x, (n) ^ 24)
void crypto1_reset(Crypto1* crypto1);
void crypto1_init(Crypto1* crypto1, uint64_t key);
uint32_t crypto1_filter(uint32_t in);
uint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted);
uint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted);
uint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted);
uint32_t prng_successor(uint32_t x, uint32_t n);
void crypto1_decrypt(
Crypto1* crypto,
uint8_t* encrypted_data,
uint16_t encrypted_data_bits,
uint8_t* decrypted_data);
void crypto1_encrypt(
Crypto1* crypto,
uint8_t* keystream,
uint8_t* plain_data,
uint16_t plain_data_bits,
uint8_t* encrypted_data,
uint8_t* encrypted_parity);

View File

@@ -1,718 +0,0 @@
#include "nested.h"
#include <furi_hal_nfc.h>
#include "../../lib/parity/parity.h"
#include "../../lib/crypto1/crypto1.h"
#define TAG "Nested"
uint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) {
uint16_t crc = 0x6363; // NFCA_CRC_INIT
uint8_t byte = 0;
for(uint8_t i = 0; i < len; i++) {
byte = buff[i];
byte ^= (uint8_t)(crc & 0xff);
byte ^= byte << 4;
crc = (crc >> 8) ^ (((uint16_t)byte) << 8) ^ (((uint16_t)byte) << 3) ^
(((uint16_t)byte) >> 4);
}
return crc;
}
void nfca_append_crc16(uint8_t* buff, uint16_t len) {
uint16_t crc = nfca_get_crc16(buff, len);
buff[len] = (uint8_t)crc;
buff[len + 1] = (uint8_t)(crc >> 8);
}
bool mifare_sendcmd_short(
Crypto1* crypto,
FuriHalNfcTxRxContext* tx_rx,
bool crypted,
uint32_t cmd,
uint32_t data) {
uint16_t pos;
uint8_t dcmd[4] = {cmd, data, 0x00, 0x00};
nfca_append_crc16(dcmd, 2);
memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data));
memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity));
if(crypted) {
for(pos = 0; pos < 4; pos++) {
uint8_t res = crypto1_byte(crypto, 0x00, 0) ^ dcmd[pos];
tx_rx->tx_data[pos] = res;
tx_rx->tx_parity[0] |=
(((crypto1_filter(crypto->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7 - pos));
}
tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw;
tx_rx->tx_bits = 4 * 8;
} else {
for(pos = 0; pos < 2; pos++) {
tx_rx->tx_data[pos] = dcmd[pos];
}
tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRxNoCrc;
tx_rx->tx_bits = 2 * 8;
}
if(!furi_hal_nfc_tx_rx(tx_rx, 6)) return false;
return true;
}
bool mifare_classic_authex(
Crypto1* crypto,
FuriHalNfcTxRxContext* tx_rx,
uint32_t uid,
uint32_t blockNo,
uint32_t keyType,
uint64_t ui64Key,
bool isNested,
uint32_t* ntptr) {
uint32_t nt, ntpp; // Supplied tag nonce
uint8_t nr[4];
// "random" reader nonce:
nfc_util_num2bytes(prng_successor(0, 32), 4, nr); // DWT->CYCCNT
// Transmit MIFARE_CLASSIC_AUTH
if(!mifare_sendcmd_short(crypto, tx_rx, isNested, 0x60 + (keyType & 0x01), blockNo)) {
return false;
};
memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data));
memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity));
nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
if(isNested) crypto1_reset(crypto); // deinit
crypto1_init(crypto, ui64Key);
if(isNested) {
nt = crypto1_word(crypto, nt ^ uid, 1) ^ nt;
} else {
crypto1_word(crypto, nt ^ uid, 0);
}
// save Nt
if(ntptr) *ntptr = nt;
// Generate (encrypted) nr+parity by loading it into the cipher (Nr)
tx_rx->tx_parity[0] = 0;
for(uint8_t i = 0; i < 4; i++) {
tx_rx->tx_data[i] = crypto1_byte(crypto, nr[i], 0) ^ nr[i];
tx_rx->tx_parity[0] |=
(((crypto1_filter(crypto->odd) ^ oddparity8(nr[i])) & 0x01) << (7 - i));
}
nt = prng_successor(nt, 32);
for(uint8_t i = 4; i < 8; i++) {
nt = prng_successor(nt, 8);
tx_rx->tx_data[i] = crypto1_byte(crypto, 0x00, 0) ^ (nt & 0xff);
tx_rx->tx_parity[0] |=
(((crypto1_filter(crypto->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7 - i));
}
tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw;
tx_rx->tx_bits = 8 * 8;
if(!furi_hal_nfc_tx_rx(tx_rx, 25)) {
return false;
};
uint32_t answer = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
ntpp = prng_successor(nt, 32) ^ crypto1_word(crypto, 0, 0);
if(answer != ntpp) {
return false;
}
return true;
}
static int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, const uint8_t* parity) {
return ((oddparity8((Nt >> 24) & 0xFF) ==
((parity[0]) ^ oddparity8((NtEnc >> 24) & 0xFF) ^ FURI_BIT(Ks1, 16))) &&
(oddparity8((Nt >> 16) & 0xFF) ==
((parity[1]) ^ oddparity8((NtEnc >> 16) & 0xFF) ^ FURI_BIT(Ks1, 8))) &&
(oddparity8((Nt >> 8) & 0xFF) ==
((parity[2]) ^ oddparity8((NtEnc >> 8) & 0xFF) ^ FURI_BIT(Ks1, 0)))) ?
1 :
0;
}
void nonce_distance(uint32_t* msb, uint32_t* lsb) {
uint16_t x = 1, pos;
uint8_t calc_ok = 0;
for(uint16_t i = 1; i; ++i) {
pos = (x & 0xff) << 8 | x >> 8;
if((pos == *msb) & !(calc_ok >> 0 & 0x01)) {
*msb = i;
calc_ok |= 0x01;
}
if((pos == *lsb) & !(calc_ok >> 1 & 0x01)) {
*lsb = i;
calc_ok |= 0x02;
}
if(calc_ok == 0x03) {
return;
}
x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;
}
}
bool validate_prng_nonce(uint32_t nonce) {
uint32_t msb = nonce >> 16;
uint32_t lsb = nonce & 0xffff;
nonce_distance(&msb, &lsb);
return ((65535 - msb + lsb) % 65535) == 16;
}
MifareNestedNonceType nested_check_nonce_type(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo) {
uint32_t nonces[5] = {};
uint8_t sameNonces = 0;
uint8_t hardNonces = 0;
Crypto1 crypt;
Crypto1* crypto = {&crypt};
for(int32_t i = 0; i < 5; i++) {
// Setup nfc poller
nfc_activate();
furi_hal_nfc_activate_nfca(100, NULL);
// Start communication
bool success = mifare_sendcmd_short(crypto, tx_rx, false, 0x60, blockNo);
if(!success) {
continue;
};
uint32_t nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
if(nt == 0) continue;
if(!validate_prng_nonce(nt)) hardNonces++;
nonces[i] = nt;
nfc_deactivate();
}
for(int32_t i = 0; i < 5; i++) {
for(int32_t j = 0; j < 5; j++) {
if(i != j && nonces[j] && nonces[i] == nonces[j]) {
sameNonces++;
}
}
}
if(!nonces[4]) {
return MifareNestedNonceNoTag;
}
if(sameNonces > 3) {
return MifareNestedNonceStatic;
}
if(hardNonces > 3) {
return MifareNestedNonceHard;
}
return MifareNestedNonceWeak;
}
struct nonce_info_static nested_static_nonce_attack(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint8_t targetBlockNo,
uint8_t targetKeyType,
uint64_t ui64Key) {
uint32_t cuid = 0;
Crypto1* crypto = malloc(sizeof(Crypto1));
struct nonce_info_static r;
r.full = false;
// Setup nfc poller
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
free(crypto);
return r;
}
r.cuid = cuid;
uint32_t nt1;
uint32_t nt_unused;
crypto1_reset(crypto);
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
if(targetKeyType == 1 && nt1 == 0x009080A2) {
r.target_nt[0] = prng_successor(nt1, 161);
r.target_nt[1] = prng_successor(nt1, 321);
} else {
r.target_nt[0] = prng_successor(nt1, 160);
r.target_nt[1] = prng_successor(nt1, 320);
}
bool success =
mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);
if(!success) {
free(crypto);
return r;
};
uint32_t nt2 = nfc_util_bytes2num(tx_rx->rx_data, 4);
r.target_ks[0] = nt2 ^ r.target_nt[0];
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
free(crypto);
return r;
}
crypto1_reset(crypto);
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt_unused);
success =
mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);
free(crypto);
if(!success) {
return r;
};
uint32_t nt3 = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);
r.target_ks[1] = nt3 ^ r.target_nt[1];
r.full = true;
nfc_deactivate();
return r;
}
uint32_t nested_calibrate_distance(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint64_t ui64Key,
uint32_t delay,
bool full) {
uint32_t cuid = 0;
Crypto1* crypto = malloc(sizeof(Crypto1));
uint32_t nt1, nt2, i = 0, davg = 0, dmin = 0, dmax = 0, rtr = 0, unsuccessful_tries = 0;
uint32_t max_prng_value = full ? 65565 : 1200;
uint32_t rounds = full ? 5 : 17; // full does not require precision
uint32_t collected = 0;
for(rtr = 0; rtr < rounds; rtr++) {
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1)) {
continue;
}
furi_delay_us(delay);
if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2)) {
continue;
}
// NXP Mifare is typical around 840, but for some unlicensed/compatible mifare tag this can be 160
uint32_t nttmp = prng_successor(nt1, 100);
for(i = 101; i < max_prng_value; i++) {
nttmp = prng_successor(nttmp, 1);
if(nttmp == nt2) break;
}
if(i != max_prng_value) {
if(rtr != 0) {
davg += i;
dmin = MIN(dmin, i);
dmax = MAX(dmax, i);
} else {
dmin = dmax = i;
}
FURI_LOG_D(TAG, "Calibrating: ntdist=%lu", i);
collected++;
} else {
unsuccessful_tries++;
if(unsuccessful_tries > 12) {
free(crypto);
FURI_LOG_E(
TAG,
"Tag isn't vulnerable to nested attack (random numbers are not predictable)");
return 0;
}
}
}
if(collected > 1) davg = (davg + (collected - 1) / 2) / (collected - 1);
davg = MIN(MAX(dmin, davg), dmax);
FURI_LOG_I(
TAG,
"Calibration completed: rtr=%lu min=%lu max=%lu avg=%lu collected=%lu",
rtr,
dmin,
dmax,
davg,
collected);
free(crypto);
nfc_deactivate();
return davg;
}
struct distance_info nested_calibrate_distance_info(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint64_t ui64Key) {
uint32_t cuid = 0;
Crypto1* crypto = malloc(sizeof(Crypto1));
uint32_t nt1, nt2, i = 0, davg = 0, dmin = 0, dmax = 0, rtr = 0, unsuccessful_tries = 0;
struct distance_info r;
r.min_prng = 0;
r.max_prng = 0;
r.mid_prng = 0;
for(rtr = 0; rtr < 10; rtr++) {
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);
// NXP Mifare is typical around 840, but for some unlicensed/compatible mifare tag this can be 160
uint32_t nttmp = prng_successor(nt1, 1);
for(i = 2; i < 65565; i++) {
nttmp = prng_successor(nttmp, 1);
if(nttmp == nt2) break;
}
if(i != 65565) {
if(rtr != 0) {
davg += i;
if(dmin == 0) {
dmin = i;
} else {
dmin = MIN(dmin, i);
}
dmax = MAX(dmax, i);
}
FURI_LOG_D(TAG, "Calibrating: ntdist=%lu", i);
} else {
unsuccessful_tries++;
if(unsuccessful_tries > 12) {
free(crypto);
FURI_LOG_E(
TAG,
"Tag isn't vulnerable to nested attack (random numbers are not predictable)");
return r;
}
}
}
if(rtr > 1) davg = (davg + (rtr - 1) / 2) / (rtr - 1);
FURI_LOG_I(
TAG, "Calibration completed: rtr=%lu min=%lu max=%lu avg=%lu", rtr, dmin, dmax, davg);
r.min_prng = dmin;
r.max_prng = dmax;
r.mid_prng = davg;
free(crypto);
nfc_deactivate();
return r;
}
struct nonce_info nested_attack(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint8_t targetBlockNo,
uint8_t targetKeyType,
uint64_t ui64Key,
uint32_t distance,
uint32_t delay) {
uint32_t cuid = 0;
Crypto1* crypto = malloc(sizeof(Crypto1));
uint8_t par_array[4] = {0x00};
uint32_t nt1, nt2, ks1, i = 0, j = 0;
struct nonce_info r;
uint32_t dmin = distance - 2;
uint32_t dmax = distance + 2;
r.full = false;
for(i = 0; i < 2; i++) { // look for exactly two different nonces
r.target_nt[i] = 0;
while(r.target_nt[i] == 0) { // continue until we have an unambiguous nonce
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
free(crypto);
return r;
}
r.cuid = cuid;
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);
furi_delay_us(delay);
bool success = mifare_sendcmd_short(
crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);
if(!success) continue;
nt2 = nfc_util_bytes2num(tx_rx->rx_data, 4);
// Parity validity check
for(j = 0; j < 4; j++) {
par_array[j] =
(oddparity8(tx_rx->rx_data[j]) != ((tx_rx->rx_parity[0] >> (7 - j)) & 0x01));
}
uint32_t ncount = 0;
uint32_t nttest = prng_successor(nt1, dmin - 1);
for(j = dmin; j < dmax + 1; j++) {
nttest = prng_successor(nttest, 1);
ks1 = nt2 ^ nttest;
if(valid_nonce(nttest, nt2, ks1, par_array)) {
if(ncount > 0) { // we are only interested in disambiguous nonces, try again
FURI_LOG_D(TAG, "Nonce#%lu: dismissed (ambiguous), ntdist=%lu", i + 1, j);
r.target_nt[i] = 0;
break;
}
if(delay) {
// will predict later
r.target_nt[i] = nt1;
r.target_ks[i] = nt2;
} else {
r.target_nt[i] = nttest;
r.target_ks[i] = ks1;
}
memcpy(&r.parity[i], par_array, 4);
ncount++;
if(i == 1 &&
(r.target_nt[0] == r.target_nt[1] ||
r.target_ks[0] == r.target_ks[1])) { // we need two different nonces
r.target_nt[i] = 0;
FURI_LOG_D(TAG, "Nonce#2: dismissed (= nonce#1), ntdist=%lu", j);
break;
}
FURI_LOG_D(TAG, "Nonce#%lu: valid, ntdist=%lu", i + 1, j);
}
}
if(r.target_nt[i] == 0 && j == dmax + 1) {
FURI_LOG_D(TAG, "Nonce#%lu: dismissed (all invalid)", i + 1);
}
}
}
if(r.target_nt[0] && r.target_nt[1]) {
r.full = true;
}
free(crypto);
nfc_deactivate();
return r;
}
struct nonce_info_hard nested_hard_nonce_attack(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint8_t targetBlockNo,
uint8_t targetKeyType,
uint64_t ui64Key,
uint32_t* found,
uint32_t* first_byte_sum,
Stream* file_stream) {
uint32_t cuid = 0;
uint8_t same = 0;
uint64_t previous = 0;
Crypto1* crypto = malloc(sizeof(Crypto1));
uint8_t par_array[4] = {0x00};
struct nonce_info_hard r;
r.full = false;
r.static_encrypted = false;
for(uint32_t i = 0; i < 8; i++) {
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) {
free(crypto);
return r;
}
r.cuid = cuid;
if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, NULL))
continue;
if(!mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo))
continue;
uint64_t nt = nfc_util_bytes2num(tx_rx->rx_data, 4);
for(uint32_t j = 0; j < 4; j++) {
par_array[j] =
(oddparity8(tx_rx->rx_data[j]) != ((tx_rx->rx_parity[0] >> (7 - j)) & 0x01));
}
uint8_t pbits = 0;
for(uint8_t j = 0; j < 4; j++) {
uint8_t p = oddparity8(tx_rx->rx_data[j]);
if(par_array[j]) {
p ^= 1;
}
pbits <<= 1;
pbits |= p;
}
// update unique nonces
if(!found[tx_rx->rx_data[0]]) {
*first_byte_sum += evenparity32(pbits & 0x08);
found[tx_rx->rx_data[0]]++;
}
if(nt == previous) {
same++;
}
previous = nt;
FuriString* row = furi_string_alloc_printf("%llu|%u\n", nt, pbits);
stream_write_string(file_stream, row);
FURI_LOG_D(TAG, "Accured %lu/8 nonces", i + 1);
furi_string_free(row);
}
if(same > 4) {
r.static_encrypted = true;
}
r.full = true;
free(crypto);
nfc_deactivate();
return r;
}
NestedCheckKeyResult nested_check_key(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint64_t ui64Key) {
uint32_t cuid = 0;
uint32_t nt;
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) return NestedCheckKeyNoTag;
FURI_LOG_D(
TAG, "Checking %c key %012llX for block %u", !keyType ? 'A' : 'B', ui64Key, blockNo);
Crypto1* crypto = malloc(sizeof(Crypto1));
bool success =
mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt);
free(crypto);
nfc_deactivate();
return success ? NestedCheckKeyValid : NestedCheckKeyInvalid;
}
bool nested_check_block(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo, uint8_t keyType) {
uint32_t cuid = 0;
nfc_activate();
if(!furi_hal_nfc_activate_nfca(200, &cuid)) return false;
Crypto1* crypto = malloc(sizeof(Crypto1));
bool success = mifare_sendcmd_short(crypto, tx_rx, false, 0x60 + (keyType & 0x01), blockNo);
free(crypto);
nfc_deactivate();
return success;
}
void nested_get_data(FuriHalNfcDevData* dev_data) {
nfc_activate();
furi_hal_nfc_detect(dev_data, 400);
nfc_deactivate();
}
void nfc_activate() {
nfc_deactivate();
// Setup nfc poller
furi_hal_nfc_exit_sleep();
furi_hal_nfc_ll_txrx_on();
furi_hal_nfc_ll_poll();
if(furi_hal_nfc_ll_set_mode(
FuriHalNfcModePollNfca, FuriHalNfcBitrate106, FuriHalNfcBitrate106) !=
FuriHalNfcReturnOk)
return;
furi_hal_nfc_ll_set_fdt_listen(FURI_HAL_NFC_LL_FDT_LISTEN_NFCA_POLLER);
furi_hal_nfc_ll_set_fdt_poll(FURI_HAL_NFC_LL_FDT_POLL_NFCA_POLLER);
furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandlingNfc);
furi_hal_nfc_ll_set_guard_time(FURI_HAL_NFC_LL_GT_NFCA);
}
void nfc_deactivate() {
furi_hal_nfc_ll_txrx_off();
furi_hal_nfc_start_sleep();
furi_hal_nfc_sleep();
}

View File

@@ -1,118 +0,0 @@
#pragma once
#include <lib/nfc/protocols/nfc_util.h>
#include <lib/nfc/protocols/mifare_classic.h>
#include <lib/nfc/protocols/crypto1.h>
#include <storage/storage.h>
#include <stream/stream.h>
#include <stream/buffered_file_stream.h>
typedef enum {
MifareNestedNonceNoTag,
MifareNestedNonceWeak,
MifareNestedNonceStatic,
MifareNestedNonceHard,
} MifareNestedNonceType;
MifareNestedNonceType nested_check_nonce_type(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo);
struct nonce_info_static {
uint32_t cuid;
uint32_t target_nt[2];
uint32_t target_ks[2];
bool full;
};
struct nonce_info_hard {
uint32_t cuid;
bool static_encrypted;
bool full;
};
struct nonce_info {
uint32_t cuid;
uint32_t target_nt[2];
uint32_t target_ks[2];
uint8_t parity[2][4];
bool full;
};
struct distance_info {
uint32_t min_prng;
uint32_t max_prng;
uint32_t mid_prng;
};
struct nonce_info_static nested_static_nonce_attack(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint8_t targetBlockNo,
uint8_t targetKeyType,
uint64_t ui64Key);
struct nonce_info nested_attack(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint8_t targetBlockNo,
uint8_t targetKeyType,
uint64_t ui64Key,
uint32_t distance,
uint32_t delay);
struct nonce_info_hard nested_hard_nonce_attack(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint8_t targetBlockNo,
uint8_t targetKeyType,
uint64_t ui64Key,
uint32_t* found,
uint32_t* first_byte_sum,
Stream* file_stream);
uint32_t nested_calibrate_distance(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint64_t ui64Key,
uint32_t delay,
bool full);
struct distance_info nested_calibrate_distance_info(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint64_t ui64Key);
typedef enum {
NestedCheckKeyNoTag,
NestedCheckKeyValid,
NestedCheckKeyInvalid,
} NestedCheckKeyResult;
NestedCheckKeyResult nested_check_key(
FuriHalNfcTxRxContext* tx_rx,
uint8_t blockNo,
uint8_t keyType,
uint64_t ui64Key);
bool nested_check_block(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo, uint8_t keyType);
void nested_get_data();
bool mifare_classic_authex(
Crypto1* crypto,
FuriHalNfcTxRxContext* tx_rx,
uint32_t uid,
uint32_t blockNo,
uint32_t keyType,
uint64_t ui64Key,
bool isNested,
uint32_t* ntptr);
void nfc_activate();
void nfc_deactivate();

View File

@@ -1,71 +0,0 @@
#include "parity.h"
uint32_t __paritysi2(uint32_t a) {
uint32_t x = (uint32_t)a;
x ^= x >> 16;
x ^= x >> 8;
x ^= x >> 4;
return (0x6996 >> (x & 0xF)) & 1;
}
static const uint8_t g_odd_byte_parity[256] = {
1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,
1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1,
1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,
0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0,
1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1,
0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0,
0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1,
0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};
#define ODD_PARITY8(x) \
{ g_odd_byte_parity[x] }
#define EVEN_PARITY8(x) \
{ !g_odd_byte_parity[x] }
uint8_t oddparity8(const uint8_t x) {
return g_odd_byte_parity[x];
}
uint8_t evenparity8(const uint8_t x) {
return !g_odd_byte_parity[x];
}
uint8_t evenparity16(uint16_t x) {
#if !defined __GNUC__
x ^= x >> 8;
return EVEN_PARITY8(x);
#else
return (__builtin_parity(x) & 0xFF);
#endif
}
uint8_t oddparity16(uint16_t x) {
#if !defined __GNUC__
x ^= x >> 8;
return ODD_PARITY8(x);
#else
return !__builtin_parity(x);
#endif
}
uint8_t evenparity32(uint32_t x) {
#if !defined __GNUC__
x ^= x >> 16;
x ^= x >> 8;
return EVEN_PARITY8(x);
#else
return (__builtin_parity(x) & 0xFF);
#endif
}
uint8_t oddparity32(uint32_t x) {
#if !defined __GNUC__
x ^= x >> 16;
x ^= x >> 8;
return ODD_PARITY8(x);
#else
return !__builtin_parity(x);
#endif
}

View File

@@ -1,10 +0,0 @@
#include "stdint.h"
uint8_t oddparity8(const uint8_t x);
uint8_t evenparity8(const uint8_t x);
uint8_t evenparity16(uint16_t x);
uint8_t oddparity16(uint16_t x);
uint8_t evenparity32(uint32_t x);
uint8_t oddparity32(uint32_t x);

View File

@@ -1,409 +0,0 @@
#include "mifare_nested_i.h"
#include <gui/elements.h>
bool mifare_nested_custom_event_callback(void* context, uint32_t event) {
furi_assert(context);
MifareNested* mifare_nested = context;
return scene_manager_handle_custom_event(mifare_nested->scene_manager, event);
}
bool mifare_nested_back_event_callback(void* context) {
furi_assert(context);
MifareNested* mifare_nested = context;
return scene_manager_handle_back_event(mifare_nested->scene_manager);
}
void mifare_nested_tick_event_callback(void* context) {
furi_assert(context);
MifareNested* mifare_nested = context;
scene_manager_handle_tick_event(mifare_nested->scene_manager);
}
void mifare_nested_show_loading_popup(void* context, bool show) {
MifareNested* mifare_nested = context;
TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME);
if(show) {
// Raise timer priority so that animations can play
vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1);
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewLoading);
} else {
// Restore default timer priority
vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY);
}
}
NestedState* collection_alloc() {
NestedState* nested = malloc(sizeof(NestedState));
nested->view = view_alloc();
view_allocate_model(nested->view, ViewModelTypeLocking, sizeof(NestedAttackViewModel));
with_view_model(
nested->view,
NestedAttackViewModel * model,
{
model->header = furi_string_alloc();
furi_string_set(model->header, "Collecting nonces");
model->keys_count = 0;
model->hardnested_states = 0;
model->lost_tag = false;
model->calibrating = false;
model->need_prediction = false;
model->hardnested = false;
},
false);
return nested;
}
CheckKeysState* check_keys_alloc() {
CheckKeysState* state = malloc(sizeof(CheckKeysState));
state->view = view_alloc();
view_allocate_model(state->view, ViewModelTypeLocking, sizeof(CheckKeysViewModel));
with_view_model(
state->view,
CheckKeysViewModel * model,
{
model->header = furi_string_alloc();
furi_string_set(model->header, "Checking keys");
model->lost_tag = false;
},
false);
return state;
}
static void nested_draw_callback(Canvas* canvas, void* model) {
NestedAttackViewModel* m = model;
if(m->lost_tag) {
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Lost the tag!");
canvas_set_font(canvas, FontSecondary);
elements_multiline_text_aligned(
canvas, 64, 23, AlignCenter, AlignTop, "Make sure the tag is\npositioned correctly.");
} else if(m->calibrating) {
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Calibrating...");
canvas_set_font(canvas, FontSecondary);
if(!m->need_prediction) {
elements_multiline_text_aligned(
canvas, 64, 23, AlignCenter, AlignTop, "Don't touch or move\nFlipper/Tag!");
} else {
elements_multiline_text_aligned(
canvas, 64, 18, AlignCenter, AlignTop, "Don't touch or move tag!");
canvas_set_font(canvas, FontPrimary);
elements_multiline_text_aligned(
canvas, 64, 30, AlignCenter, AlignTop, "Calibration will take\nmore time");
}
} else if(m->hardnested) {
char draw_str[32] = {};
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(
canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));
canvas_set_font(canvas, FontSecondary);
float progress =
m->keys_count == 0 ? 0 : (float)(m->nonces_collected) / (float)(m->keys_count);
if(progress > 1.0) {
progress = 1.0;
}
elements_progress_bar(canvas, 5, 15, 120, progress);
canvas_set_font(canvas, FontSecondary);
snprintf(
draw_str,
sizeof(draw_str),
"Nonces collected: %lu/%lu",
m->nonces_collected,
m->keys_count);
canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);
snprintf(draw_str, sizeof(draw_str), "States found: %lu/256", m->hardnested_states);
canvas_draw_str_aligned(canvas, 1, 40, AlignLeft, AlignTop, draw_str);
} else {
char draw_str[32] = {};
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(
canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));
canvas_set_font(canvas, FontSecondary);
float progress =
m->keys_count == 0 ? 0 : (float)(m->nonces_collected) / (float)(m->keys_count);
if(progress > 1.0) {
progress = 1.0;
}
elements_progress_bar(canvas, 5, 15, 120, progress);
canvas_set_font(canvas, FontSecondary);
snprintf(
draw_str,
sizeof(draw_str),
"Nonces collected: %lu/%lu",
m->nonces_collected,
m->keys_count);
canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);
}
elements_button_center(canvas, "Stop");
}
static void check_keys_draw_callback(Canvas* canvas, void* model) {
CheckKeysViewModel* m = model;
if(m->lost_tag) {
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Lost the tag!");
canvas_set_font(canvas, FontSecondary);
elements_multiline_text_aligned(
canvas, 64, 23, AlignCenter, AlignTop, "Make sure the tag is\npositioned correctly.");
} else if(m->processing_keys) {
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, "Processing keys...");
canvas_set_font(canvas, FontSecondary);
elements_multiline_text_aligned(
canvas, 64, 23, AlignCenter, AlignTop, "Checking which keys you\nalready have...");
} else {
char draw_str[32] = {};
char draw_sub_str[32] = {};
canvas_set_font(canvas, FontPrimary);
canvas_draw_str_aligned(
canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));
canvas_set_font(canvas, FontSecondary);
float progress = m->keys_count == 0 ? 0 :
(float)(m->keys_checked) / (float)(m->keys_count);
if(progress > 1.0) {
progress = 1.0;
}
elements_progress_bar(canvas, 5, 15, 120, progress);
canvas_set_font(canvas, FontSecondary);
snprintf(
draw_str, sizeof(draw_str), "Keys checked: %lu/%lu", m->keys_checked, m->keys_count);
canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);
snprintf(
draw_sub_str,
sizeof(draw_sub_str),
"Keys found: %lu/%lu",
m->keys_found,
m->keys_total);
canvas_draw_str_aligned(canvas, 1, 40, AlignLeft, AlignTop, draw_sub_str);
}
elements_button_center(canvas, "Stop");
}
static bool nested_input_callback(InputEvent* event, void* context) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event->type == InputTypeShort && (event->key == InputKeyBack || event->key == InputKeyOk)) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
MifareNested* mifare_nested_alloc() {
MifareNested* mifare_nested = malloc(sizeof(MifareNested));
mifare_nested->worker = mifare_nested_worker_alloc();
mifare_nested->view_dispatcher = view_dispatcher_alloc();
mifare_nested->scene_manager =
scene_manager_alloc(&mifare_nested_scene_handlers, mifare_nested);
view_dispatcher_enable_queue(mifare_nested->view_dispatcher);
view_dispatcher_set_event_callback_context(mifare_nested->view_dispatcher, mifare_nested);
view_dispatcher_set_custom_event_callback(
mifare_nested->view_dispatcher, mifare_nested_custom_event_callback);
view_dispatcher_set_navigation_event_callback(
mifare_nested->view_dispatcher, mifare_nested_back_event_callback);
view_dispatcher_set_tick_event_callback(
mifare_nested->view_dispatcher, mifare_nested_tick_event_callback, 100);
// Nfc device
mifare_nested->nfc_dev = nfc_device_alloc();
// Open GUI record
mifare_nested->gui = furi_record_open(RECORD_GUI);
view_dispatcher_attach_to_gui(
mifare_nested->view_dispatcher, mifare_nested->gui, ViewDispatcherTypeFullscreen);
// Open Notification record
mifare_nested->notifications = furi_record_open(RECORD_NOTIFICATION);
// Submenu
mifare_nested->submenu = submenu_alloc();
view_dispatcher_add_view(
mifare_nested->view_dispatcher,
MifareNestedViewMenu,
submenu_get_view(mifare_nested->submenu));
// Popup
mifare_nested->popup = popup_alloc();
view_dispatcher_add_view(
mifare_nested->view_dispatcher,
MifareNestedViewPopup,
popup_get_view(mifare_nested->popup));
// Loading
mifare_nested->loading = loading_alloc();
view_dispatcher_add_view(
mifare_nested->view_dispatcher,
MifareNestedViewLoading,
loading_get_view(mifare_nested->loading));
// Text Input
mifare_nested->text_input = text_input_alloc();
view_dispatcher_add_view(
mifare_nested->view_dispatcher,
MifareNestedViewTextInput,
text_input_get_view(mifare_nested->text_input));
// Custom Widget
mifare_nested->widget = widget_alloc();
view_dispatcher_add_view(
mifare_nested->view_dispatcher,
MifareNestedViewWidget,
widget_get_view(mifare_nested->widget));
// Variable Item List
mifare_nested->variable_item_list = variable_item_list_alloc();
view_dispatcher_add_view(
mifare_nested->view_dispatcher,
MifareNestedViewVariableList,
variable_item_list_get_view(mifare_nested->variable_item_list));
// Nested attack state
NestedState* plugin_state = collection_alloc();
view_set_context(plugin_state->view, mifare_nested);
mifare_nested->nested_state = plugin_state;
view_dispatcher_add_view(
mifare_nested->view_dispatcher, MifareNestedViewCollecting, plugin_state->view);
// Check keys attack state
CheckKeysState* keys_state = check_keys_alloc();
view_set_context(keys_state->view, mifare_nested);
mifare_nested->keys_state = keys_state;
view_dispatcher_add_view(
mifare_nested->view_dispatcher, MifareNestedViewCheckKeys, keys_state->view);
KeyInfo_t* key_info = malloc(sizeof(KeyInfo_t));
mifare_nested->keys = key_info;
MifareNestedSettings* settings = malloc(sizeof(MifareNestedSettings));
settings->only_hardnested = false;
mifare_nested->settings = settings;
view_set_draw_callback(plugin_state->view, nested_draw_callback);
view_set_input_callback(plugin_state->view, nested_input_callback);
view_set_draw_callback(keys_state->view, check_keys_draw_callback);
view_set_input_callback(keys_state->view, nested_input_callback);
mifare_nested->collecting_type = MifareNestedWorkerStateReady;
mifare_nested->run = NestedRunIdle;
return mifare_nested;
}
void mifare_nested_free(MifareNested* mifare_nested) {
furi_assert(mifare_nested);
// Nfc device
nfc_device_free(mifare_nested->nfc_dev);
// Submenu
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewMenu);
submenu_free(mifare_nested->submenu);
// Popup
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewPopup);
popup_free(mifare_nested->popup);
// Loading
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewLoading);
loading_free(mifare_nested->loading);
// TextInput
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewTextInput);
text_input_free(mifare_nested->text_input);
// Custom Widget
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
widget_free(mifare_nested->widget);
// Variable Item List
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewVariableList);
variable_item_list_free(mifare_nested->variable_item_list);
// Nested
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewCollecting);
// Check keys
view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewCheckKeys);
// Nonces states
free(mifare_nested->nonces);
free(mifare_nested->nested_state);
// Keys
free(mifare_nested->keys);
// Settings
free(mifare_nested->settings);
// Worker
mifare_nested_worker_stop(mifare_nested->worker);
mifare_nested_worker_free(mifare_nested->worker);
// View Dispatcher
view_dispatcher_free(mifare_nested->view_dispatcher);
// Scene Manager
scene_manager_free(mifare_nested->scene_manager);
// GUI
furi_record_close(RECORD_GUI);
mifare_nested->gui = NULL;
// Notifications
furi_record_close(RECORD_NOTIFICATION);
mifare_nested->notifications = NULL;
free(mifare_nested);
}
void mifare_nested_blink_start(MifareNested* mifare_nested) {
notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_start_blue);
}
void mifare_nested_blink_calibration_start(MifareNested* mifare_nested) {
notification_message(
mifare_nested->notifications, &mifare_nested_sequence_blink_start_magenta);
}
void mifare_nested_blink_nonce_collection_start(MifareNested* mifare_nested) {
notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_start_yellow);
}
void mifare_nested_blink_stop(MifareNested* mifare_nested) {
notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_stop);
}
int32_t mifare_nested_app(void* p) {
UNUSED(p);
MifareNested* mifare_nested = mifare_nested_alloc();
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneStart);
view_dispatcher_run(mifare_nested->view_dispatcher);
mifare_nested_free(mifare_nested);
return 0;
}

View File

@@ -1,3 +0,0 @@
#pragma once
typedef struct MifareNested MifareNested;

View File

@@ -1,182 +0,0 @@
#pragma once
#include "mifare_nested.h"
#include "mifare_nested_worker.h"
#include "lib/nested/nested.h"
#include <furi.h>
#include <gui/gui.h>
#include <gui/view_dispatcher.h>
#include <gui/scene_manager.h>
#include <notification/notification_messages.h>
#include <gui/modules/submenu.h>
#include <gui/modules/popup.h>
#include <gui/modules/loading.h>
#include <gui/modules/text_input.h>
#include <gui/modules/widget.h>
#include <input/input.h>
#include "scenes/mifare_nested_scene.h"
#include <storage/storage.h>
#include <lib/toolbox/path.h>
#include <lib/nfc/nfc_device.h>
#include <lib/toolbox/value_index.h>
#include <gui/modules/variable_item_list.h>
#include "mifare_nested_icons.h"
#include <assets_icons.h>
#define NESTED_VERSION_APP "1.5.2"
#define NESTED_GITHUB_LINK "https://github.com/AloneLiberty/FlipperNested"
#define NESTED_RECOVER_KEYS_GITHUB_LINK "https://github.com/AloneLiberty/FlipperNestedRecovery"
#define NESTED_NONCE_FORMAT_VERSION "3"
#define NESTED_AUTHOR "@AloneLiberty (t.me/libertydev)"
enum MifareNestedCustomEvent {
// Reserve first 100 events for button types and indexes, starting from 0
MifareNestedCustomEventReserved = 100,
MifareNestedCustomEventViewExit,
MifareNestedCustomEventWorkerExit,
MifareNestedCustomEventByteInputDone,
MifareNestedCustomEventTextInputDone,
MifareNestedCustomEventSceneSettingLock
};
typedef void (*NestedCallback)(void* context);
typedef struct {
FuriMutex* mutex;
FuriMessageQueue* event_queue;
ViewPort* view_port;
View* view;
NestedCallback callback;
void* context;
} NestedState;
typedef void (*CheckKeysCallback)(void* context);
typedef struct {
FuriMutex* mutex;
FuriMessageQueue* event_queue;
ViewPort* view_port;
View* view;
CheckKeysCallback callback;
void* context;
} CheckKeysState;
typedef enum {
EventTypeTick,
EventTypeKey,
} EventType;
typedef struct {
EventType type;
InputEvent input;
} PluginEvent;
typedef struct {
bool only_hardnested;
} MifareNestedSettings;
typedef enum { NestedRunIdle, NestedRunCheckKeys, NestedRunAttack } NestedRunNext;
struct MifareNested {
MifareNestedWorker* worker;
ViewDispatcher* view_dispatcher;
Gui* gui;
NotificationApp* notifications;
SceneManager* scene_manager;
NfcDevice* nfc_dev;
VariableItemList* variable_item_list;
MifareNestedSettings* settings;
FuriString* text_box_store;
// Common Views
Submenu* submenu;
Popup* popup;
Loading* loading;
TextInput* text_input;
Widget* widget;
NonceList_t* nonces;
KeyInfo_t* keys;
NestedState* nested_state;
CheckKeysState* keys_state;
SaveNoncesResult_t* save_state;
MifareNestedWorkerState collecting_type;
NestedRunNext run;
};
typedef enum {
MifareNestedViewMenu,
MifareNestedViewPopup,
MifareNestedViewLoading,
MifareNestedViewTextInput,
MifareNestedViewWidget,
MifareNestedViewVariableList,
MifareNestedViewCollecting,
MifareNestedViewCheckKeys,
} MifareNestedView;
typedef struct {
FuriString* header;
uint32_t keys_count;
uint32_t nonces_collected;
uint32_t hardnested_states;
bool lost_tag;
bool calibrating;
bool need_prediction;
bool hardnested;
} NestedAttackViewModel;
typedef struct {
FuriString* header;
uint32_t keys_count;
uint32_t keys_checked;
uint32_t keys_found;
uint32_t keys_total;
bool lost_tag;
bool processing_keys;
} CheckKeysViewModel;
static const NotificationSequence mifare_nested_sequence_blink_start_blue = {
&message_blink_start_10,
&message_blink_set_color_blue,
&message_do_not_reset,
NULL,
};
static const NotificationSequence mifare_nested_sequence_blink_start_magenta = {
&message_blink_start_10,
&message_blink_set_color_magenta,
&message_do_not_reset,
NULL,
};
static const NotificationSequence mifare_nested_sequence_blink_start_yellow = {
&message_blink_start_10,
&message_blink_set_color_yellow,
&message_do_not_reset,
NULL,
};
static const NotificationSequence mifare_nested_sequence_blink_stop = {
&message_blink_stop,
NULL,
};
MifareNested* mifare_nested_alloc();
void mifare_nested_text_store_set(MifareNested* mifare_nested, const char* text, ...);
void mifare_nested_text_store_clear(MifareNested* mifare_nested);
void mifare_nested_blink_start(MifareNested* mifare_nested);
void mifare_nested_blink_calibration_start(MifareNested* mifare_nested);
void mifare_nested_blink_nonce_collection_start(MifareNested* mifare_nested);
void mifare_nested_blink_stop(MifareNested* mifare_nested);
void mifare_nested_show_loading_popup(void* context, bool show);

File diff suppressed because it is too large Load Diff

View File

@@ -1,98 +0,0 @@
#pragma once
#include <lib/nfc/nfc_device.h>
#define NESTED_FOLDER EXT_PATH("nfc/.nested")
typedef struct MifareNestedWorker MifareNestedWorker;
typedef enum {
MifareNestedWorkerStateReady,
MifareNestedWorkerStateCheck,
MifareNestedWorkerStateCollecting,
MifareNestedWorkerStateCollectingStatic,
MifareNestedWorkerStateCollectingHard,
MifareNestedWorkerStateValidating,
MifareNestedWorkerStateStop,
} MifareNestedWorkerState;
typedef enum {
MifareNestedWorkerEventReserved = 1000,
MifareNestedWorkerEventNoTagDetected,
MifareNestedWorkerEventNoNoncesCollected,
MifareNestedWorkerEventNoncesCollected,
MifareNestedWorkerEventCollecting,
MifareNestedWorkerEventNewNonce,
MifareNestedWorkerEventKeyChecked,
MifareNestedWorkerEventKeysFound,
MifareNestedWorkerEventNeedKey,
MifareNestedWorkerEventAttackFailed,
MifareNestedWorkerEventCalibrating,
MifareNestedWorkerEventStaticEncryptedNonce,
MifareNestedWorkerEventNeedPrediction,
MifareNestedWorkerEventProcessingKeys,
MifareNestedWorkerEventNeedKeyRecovery,
MifareNestedWorkerEventNeedCollection,
MifareNestedWorkerEventHardnestedStatesFound
} MifareNestedWorkerEvent;
typedef bool (*MifareNestedWorkerCallback)(MifareNestedWorkerEvent event, void* context);
MifareNestedWorker* mifare_nested_worker_alloc();
void mifare_nested_worker_change_state(
MifareNestedWorker* mifare_nested_worker,
MifareNestedWorkerState state);
void mifare_nested_worker_free(MifareNestedWorker* mifare_nested_worker);
void mifare_nested_worker_stop(MifareNestedWorker* mifare_nested_worker);
void mifare_nested_worker_start(
MifareNestedWorker* mifare_nested_worker,
MifareNestedWorkerState state,
NfcDeviceData* dev_data,
MifareNestedWorkerCallback callback,
void* context);
typedef struct {
uint32_t key_type;
uint32_t block;
uint32_t target_nt[2];
uint32_t target_ks[2];
uint8_t parity[2][4];
bool skipped;
bool from_start;
bool invalid;
bool collected;
bool hardnested;
} Nonces;
typedef struct {
uint32_t cuid;
uint32_t sector_count;
// 40 (or 16/5) sectors, 2 keys (A/B), 3 tries
Nonces* nonces[40][2][3];
uint32_t tries;
// unique first bytes
uint32_t hardnested_states;
} NonceList_t;
typedef struct {
uint32_t total_keys;
uint32_t checked_keys;
uint32_t found_keys;
uint32_t added_keys;
uint32_t sector_keys;
bool tag_lost;
} KeyInfo_t;
typedef struct {
uint32_t saved;
uint32_t invalid;
uint32_t skipped;
} SaveNoncesResult_t;

View File

@@ -1,28 +0,0 @@
#pragma once
#include <furi.h>
#include "mifare_nested_i.h"
#include "mifare_nested_worker.h"
struct MifareNestedWorker {
FuriThread* thread;
NfcDeviceData* dev_data;
MifareNestedWorkerCallback callback;
MifareNested* context;
MifareNestedWorkerState state;
};
int32_t mifare_nested_worker_task(void* context);
void mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker);
void mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker);
void mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker);
void mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker);
void mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker);

View File

@@ -1,30 +0,0 @@
#include "mifare_nested_scene.h"
// Generate scene on_enter handlers array
#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,
void (*const mifare_nested_on_enter_handlers[])(void*) = {
#include "mifare_nested_scene_config.h"
};
#undef ADD_SCENE
// Generate scene on_event handlers array
#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,
bool (*const mifare_nested_on_event_handlers[])(void* context, SceneManagerEvent event) = {
#include "mifare_nested_scene_config.h"
};
#undef ADD_SCENE
// Generate scene on_exit handlers array
#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,
void (*const mifare_nested_on_exit_handlers[])(void* context) = {
#include "mifare_nested_scene_config.h"
};
#undef ADD_SCENE
// Initialize scene handlers configuration structure
const SceneManagerHandlers mifare_nested_scene_handlers = {
.on_enter_handlers = mifare_nested_on_enter_handlers,
.on_event_handlers = mifare_nested_on_event_handlers,
.on_exit_handlers = mifare_nested_on_exit_handlers,
.scene_num = MifareNestedSceneNum,
};

View File

@@ -1,29 +0,0 @@
#pragma once
#include <gui/scene_manager.h>
// Generate scene id and total number
#define ADD_SCENE(prefix, name, id) MifareNestedScene##id,
typedef enum {
#include "mifare_nested_scene_config.h"
MifareNestedSceneNum,
} MifareNestedScene;
#undef ADD_SCENE
extern const SceneManagerHandlers mifare_nested_scene_handlers;
// Generate scene on_enter handlers declaration
#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);
#include "mifare_nested_scene_config.h"
#undef ADD_SCENE
// Generate scene on_event handlers declaration
#define ADD_SCENE(prefix, name, id) \
bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);
#include "mifare_nested_scene_config.h"
#undef ADD_SCENE
// Generate scene on_exit handlers declaration
#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);
#include "mifare_nested_scene_config.h"
#undef ADD_SCENE

View File

@@ -1,77 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_about_on_enter(void* context) {
MifareNested* mifare_nested = context;
FuriString* temp_str;
temp_str = furi_string_alloc();
furi_string_printf(temp_str, "\e#%s\n", "Information");
furi_string_cat_printf(temp_str, "Version: %s\n", NESTED_VERSION_APP);
furi_string_cat_printf(temp_str, "Developed by:\n%s\n\n", NESTED_AUTHOR);
furi_string_cat_printf(temp_str, "Github: %s\n\n", NESTED_GITHUB_LINK);
furi_string_cat_printf(temp_str, "\e#%s\n", "Description");
furi_string_cat_printf(
temp_str,
"Ported Nested attacks\nfrom Proxmark3 (Iceman fork)\nCurrently supported attacks:\n - nested attack\n - static nested attack\n - hard nested attack\n\n");
furi_string_cat_printf(
temp_str,
"You will need desktop app to recover keys from collected nonces: %s\n\n",
NESTED_RECOVER_KEYS_GITHUB_LINK);
furi_string_cat_printf(temp_str, "\e#%s\n", "Quick guide");
furi_string_cat_printf(temp_str, "1. Install key recovery script on PC:\n");
furi_string_cat_printf(temp_str, "pip install FlipperNested\n");
furi_string_cat_printf(temp_str, "2. Connect Flipper Zero to PC\n");
furi_string_cat_printf(temp_str, "3. Run key recovery:\n");
furi_string_cat_printf(temp_str, "FlipperNested");
widget_add_text_box_element(
mifare_nested->widget,
0,
0,
128,
14,
AlignCenter,
AlignBottom,
"\e#\e! \e!\n",
false);
widget_add_text_box_element(
mifare_nested->widget,
0,
2,
128,
14,
AlignCenter,
AlignBottom,
"\e#\e! Flipper Nested \e!\n",
false);
widget_add_text_scroll_element(
mifare_nested->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str));
furi_string_free(temp_str);
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_about_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
UNUSED(mifare_nested);
UNUSED(event);
return consumed;
}
void mifare_nested_scene_about_on_exit(void* context) {
MifareNested* mifare_nested = context;
// Clear views
widget_reset(mifare_nested->widget);
}

View File

@@ -1,76 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_added_keys_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_added_keys_on_enter(void* context) {
MifareNested* mifare_nested = context;
KeyInfo_t* key_info = mifare_nested->keys;
Widget* widget = mifare_nested->widget;
char draw_str[32] = {};
char append[5] = {'k', 'e', 'y', ' ', '\0'};
if(key_info->added_keys != 1) {
append[3] = 's';
}
widget_add_string_element(
widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Results of key recovery");
if(key_info->added_keys != 0) {
snprintf(draw_str, sizeof(draw_str), "Added: %lu %s", key_info->added_keys, append);
notification_message(mifare_nested->notifications, &sequence_success);
widget_add_icon_element(widget, 52, 17, &I_DolphinSuccess);
} else {
snprintf(draw_str, sizeof(draw_str), "No new keys were added");
widget_add_string_element(
widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "Try running \"Nested attack\"");
widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "again");
notification_message(mifare_nested->notifications, &sequence_error);
}
widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, draw_str);
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_added_keys_widget_callback,
mifare_nested);
free(key_info);
KeyInfo_t* new_key_info = malloc(sizeof(KeyInfo_t));
mifare_nested->keys = new_key_info;
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_added_keys_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_added_keys_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,95 +0,0 @@
#include "../mifare_nested_i.h"
enum {
MifareNestedSceneCheckStateTagSearch,
MifareNestedSceneCheckStateTagFound,
};
bool mifare_nested_check_worker_callback(MifareNestedWorkerEvent event, void* context) {
furi_assert(context);
MifareNested* mifare_nested = context;
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);
return true;
}
static void mifare_nested_scene_check_setup_view(MifareNested* mifare_nested) {
Popup* popup = mifare_nested->popup;
popup_reset(popup);
uint32_t state =
scene_manager_get_scene_state(mifare_nested->scene_manager, MifareNestedSceneCheck);
if(state == MifareNestedSceneCheckStateTagSearch) {
popup_set_icon(mifare_nested->popup, 0, 8, &I_ApplyTag);
popup_set_text(
mifare_nested->popup, "Apply tag to\nthe back", 128, 32, AlignRight, AlignCenter);
} else {
popup_set_icon(popup, 12, 23, &I_Loading);
popup_set_header(popup, "Checking\nDon't move...", 52, 32, AlignLeft, AlignCenter);
}
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewPopup);
}
void mifare_nested_scene_check_on_enter(void* context) {
MifareNested* mifare_nested = context;
scene_manager_set_scene_state(
mifare_nested->scene_manager,
MifareNestedSceneCheck,
MifareNestedSceneCheckStateTagSearch);
mifare_nested_scene_check_setup_view(mifare_nested);
// Setup and start worker
mifare_nested_worker_start(
mifare_nested->worker,
MifareNestedWorkerStateCheck,
&mifare_nested->nfc_dev->dev_data,
mifare_nested_check_worker_callback,
mifare_nested);
mifare_nested_blink_start(mifare_nested);
}
bool mifare_nested_scene_check_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == MifareNestedWorkerEventCollecting) {
if(mifare_nested->run == NestedRunAttack) {
if(mifare_nested->settings->only_hardnested) {
FURI_LOG_I("MifareNested", "Using Hard Nested because user settings");
mifare_nested->collecting_type = MifareNestedWorkerStateCollectingHard;
}
scene_manager_next_scene(
mifare_nested->scene_manager, MifareNestedSceneCollecting);
} else {
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheckKeys);
}
consumed = true;
} else if(event.event == MifareNestedWorkerEventNoTagDetected) {
scene_manager_set_scene_state(
mifare_nested->scene_manager,
MifareNestedSceneCheck,
MifareNestedSceneCheckStateTagSearch);
mifare_nested_scene_check_setup_view(mifare_nested);
consumed = true;
}
}
return consumed;
}
void mifare_nested_scene_check_on_exit(void* context) {
MifareNested* mifare_nested = context;
mifare_nested_worker_stop(mifare_nested->worker);
scene_manager_set_scene_state(
mifare_nested->scene_manager,
MifareNestedSceneCheck,
MifareNestedSceneCheckStateTagSearch);
// Clear view
popup_reset(mifare_nested->popup);
mifare_nested_blink_stop(mifare_nested);
}

View File

@@ -1,117 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_check_keys_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
bool mifare_nested_check_keys_worker_callback(MifareNestedWorkerEvent event, void* context) {
MifareNested* mifare_nested = context;
CheckKeysState* plugin_state = mifare_nested->keys_state;
if(event == MifareNestedWorkerEventKeyChecked) {
mifare_nested_blink_nonce_collection_start(mifare_nested);
KeyInfo_t* key_info = mifare_nested->keys;
with_view_model(
plugin_state->view,
CheckKeysViewModel * model,
{
model->lost_tag = false;
model->keys_checked = key_info->checked_keys;
model->keys_found = key_info->found_keys;
model->keys_total = key_info->sector_keys;
model->keys_count = key_info->total_keys;
},
true);
} else if(event == MifareNestedWorkerEventNoTagDetected) {
mifare_nested_blink_start(mifare_nested);
with_view_model(
plugin_state->view, CheckKeysViewModel * model, { model->lost_tag = true; }, true);
} else if(event == MifareNestedWorkerEventProcessingKeys) {
with_view_model(
plugin_state->view,
CheckKeysViewModel * model,
{ model->processing_keys = true; },
true);
}
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);
return true;
}
void mifare_nested_scene_check_keys_on_enter(void* context) {
MifareNested* mifare_nested = context;
CheckKeysState* plugin_state = mifare_nested->keys_state;
mifare_nested_worker_start(
mifare_nested->worker,
MifareNestedWorkerStateValidating,
&mifare_nested->nfc_dev->dev_data,
mifare_nested_check_keys_worker_callback,
mifare_nested);
mifare_nested_blink_start(mifare_nested);
with_view_model(
plugin_state->view,
CheckKeysViewModel * model,
{
model->lost_tag = false;
model->processing_keys = false;
model->keys_count = 0;
model->keys_checked = 0;
model->keys_found = 0;
},
false);
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewCheckKeys);
}
bool mifare_nested_scene_check_keys_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
} else if(event.event == MifareNestedWorkerEventKeysFound) {
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneAddedKeys);
consumed = true;
} else if(event.event == MifareNestedWorkerEventNeedKeyRecovery) {
scene_manager_next_scene(
mifare_nested->scene_manager, MifareNestedSceneNeedKeyRecovery);
consumed = true;
} else if(event.event == MifareNestedWorkerEventNeedCollection) {
scene_manager_next_scene(
mifare_nested->scene_manager, MifareNestedSceneNeedCollection);
consumed = true;
} else if(
event.event == MifareNestedWorkerEventKeyChecked ||
event.event == MifareNestedWorkerEventNoTagDetected ||
event.event == MifareNestedWorkerEventProcessingKeys) {
consumed = true;
}
}
return consumed;
}
void mifare_nested_scene_check_keys_on_exit(void* context) {
MifareNested* mifare_nested = context;
mifare_nested_worker_stop(mifare_nested->worker);
// Clear view
mifare_nested_blink_stop(mifare_nested);
popup_reset(mifare_nested->popup);
widget_reset(mifare_nested->widget);
}

View File

@@ -1,161 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_collecting_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
bool mifare_nested_collecting_worker_callback(MifareNestedWorkerEvent event, void* context) {
MifareNested* mifare_nested = context;
NestedState* plugin_state = mifare_nested->nested_state;
if(event == MifareNestedWorkerEventNewNonce) {
mifare_nested_blink_nonce_collection_start(mifare_nested);
uint8_t collected = 0;
uint8_t skip = 0;
NonceList_t* nonces = mifare_nested->nonces;
for(uint8_t tries = 0; tries < nonces->tries; tries++) {
for(uint8_t sector = 0; sector < nonces->sector_count; sector++) {
for(uint8_t keyType = 0; keyType < 2; keyType++) {
Nonces* info = nonces->nonces[sector][keyType][tries];
if(info->from_start) {
skip++;
} else if(info->collected) {
collected++;
}
}
}
}
with_view_model(
plugin_state->view,
NestedAttackViewModel * model,
{
model->calibrating = false;
model->lost_tag = false;
model->nonces_collected = collected;
model->keys_count = (nonces->sector_count * nonces->tries * 2) - skip;
},
true);
} else if(event == MifareNestedWorkerEventNoTagDetected) {
mifare_nested_blink_start(mifare_nested);
with_view_model(
plugin_state->view, NestedAttackViewModel * model, { model->lost_tag = true; }, true);
} else if(event == MifareNestedWorkerEventCalibrating) {
mifare_nested_blink_calibration_start(mifare_nested);
with_view_model(
plugin_state->view,
NestedAttackViewModel * model,
{
model->calibrating = true;
model->lost_tag = false;
model->need_prediction = false;
model->hardnested = false;
},
true);
} else if(event == MifareNestedWorkerEventNeedPrediction) {
with_view_model(
plugin_state->view,
NestedAttackViewModel * model,
{ model->need_prediction = true; },
true);
} else if(event == MifareNestedWorkerEventHardnestedStatesFound) {
NonceList_t* nonces = mifare_nested->nonces;
with_view_model(
plugin_state->view,
NestedAttackViewModel * model,
{
model->calibrating = false;
model->lost_tag = false;
model->hardnested = true;
model->hardnested_states = nonces->hardnested_states;
},
true);
}
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);
return true;
}
void mifare_nested_scene_collecting_on_enter(void* context) {
MifareNested* mifare_nested = context;
NestedState* nested = mifare_nested->nested_state;
mifare_nested_worker_start(
mifare_nested->worker,
mifare_nested->collecting_type,
&mifare_nested->nfc_dev->dev_data,
mifare_nested_collecting_worker_callback,
mifare_nested);
mifare_nested_blink_start(mifare_nested);
with_view_model(
nested->view,
NestedAttackViewModel * model,
{
model->lost_tag = false;
model->nonces_collected = 0;
},
false);
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewCollecting);
}
bool mifare_nested_scene_collecting_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
} else if(event.event == MifareNestedWorkerEventNoncesCollected) {
scene_manager_next_scene(
mifare_nested->scene_manager, MifareNestedSceneNoncesCollected);
consumed = true;
} else if(event.event == MifareNestedWorkerEventNoNoncesCollected) {
scene_manager_next_scene(
mifare_nested->scene_manager, MifareNestedSceneNoNoncesCollected);
consumed = true;
} else if(event.event == MifareNestedWorkerEventAttackFailed) {
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneFailed);
consumed = true;
} else if(event.event == MifareNestedWorkerEventNeedKey) {
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneNoKeys);
consumed = true;
} else if(event.event == MifareNestedWorkerEventStaticEncryptedNonce) {
scene_manager_next_scene(
mifare_nested->scene_manager, MifareNestedSceneStaticEncryptedNonce);
consumed = true;
} else if(
event.event == MifareNestedWorkerEventNewNonce ||
event.event == MifareNestedWorkerEventNoTagDetected ||
event.event == MifareNestedWorkerEventCalibrating ||
event.event == MifareNestedWorkerEventNeedPrediction ||
event.event == MifareNestedWorkerEventHardnestedStatesFound) {
consumed = true;
}
}
return consumed;
}
void mifare_nested_scene_collecting_on_exit(void* context) {
MifareNested* mifare_nested = context;
mifare_nested_worker_stop(mifare_nested->worker);
// Clear view
mifare_nested_blink_stop(mifare_nested);
popup_reset(mifare_nested->popup);
widget_reset(mifare_nested->widget);
}

View File

@@ -1,14 +0,0 @@
ADD_SCENE(mifare_nested, start, Start)
ADD_SCENE(mifare_nested, check, Check)
ADD_SCENE(mifare_nested, nonces_collected, NoncesCollected)
ADD_SCENE(mifare_nested, collecting, Collecting)
ADD_SCENE(mifare_nested, no_keys, NoKeys)
ADD_SCENE(mifare_nested, check_keys, CheckKeys)
ADD_SCENE(mifare_nested, added_keys, AddedKeys)
ADD_SCENE(mifare_nested, failed, Failed)
ADD_SCENE(mifare_nested, about, About)
ADD_SCENE(mifare_nested, static_encrypted_nonce, StaticEncryptedNonce)
ADD_SCENE(mifare_nested, need_key_recovery, NeedKeyRecovery)
ADD_SCENE(mifare_nested, need_collection, NeedCollection)
ADD_SCENE(mifare_nested, settings, Settings)
ADD_SCENE(mifare_nested, no_nonces_collected, NoNoncesCollected)

View File

@@ -1,59 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_failed_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_failed_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
notification_message(mifare_nested->notifications, &sequence_error);
widget_add_icon_element(widget, 73, 13, &I_DolphinCry);
widget_add_string_element(
widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Failed to preform attack");
widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Try running");
widget_add_string_element(
widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "\"Nested attack\"");
widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "again or check");
widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "logs");
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_failed_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_failed_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_failed_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,56 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_need_collection_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_need_collection_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
notification_message(mifare_nested->notifications, &sequence_error);
widget_add_icon_element(widget, 73, 13, &I_DolphinCry);
widget_add_string_element(
widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Missing collected nonces");
widget_add_string_element(
widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Run \"Nested attack\"");
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_need_collection_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_need_collection_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_need_collection_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,59 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_need_key_recovery_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_need_key_recovery_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
notification_message(mifare_nested->notifications, &sequence_error);
widget_add_icon_element(widget, 74, 13, &I_DolphinCry);
widget_add_string_element(
widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Missing found keys");
widget_add_string_element(
widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "First you need to");
widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "recover keys");
widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "Read \"About\"");
widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "for more info");
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_need_key_recovery_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_need_key_recovery_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_need_key_recovery_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,61 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_no_keys_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_no_keys_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
notification_message(mifare_nested->notifications, &sequence_success);
widget_add_icon_element(widget, 73, 13, &I_DolphinCry);
widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "No keys found");
widget_add_string_element(
widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Scan tag and find at");
widget_add_string_element(
widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "least one key to");
widget_add_string_element(
widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "start (save dump");
widget_add_string_element(
widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "after scanning!)");
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_no_keys_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_no_keys_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_no_keys_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,94 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_no_nonces_collected_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_no_nonces_collected_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
SaveNoncesResult_t* save_state = mifare_nested->save_state;
notification_message(mifare_nested->notifications, &sequence_error);
widget_add_icon_element(widget, 73, 12, &I_DolphinCry);
widget_add_string_element(
widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "No nonces collected");
uint32_t index = 12;
if(save_state->skipped) {
char append_skipped[8] = {'s', 'e', 'c', 't', 'o', 'r', ' ', '\0'};
if(save_state->skipped != 1) {
append_skipped[6] = 's';
}
char draw_str[32] = {};
snprintf(
draw_str, sizeof(draw_str), "Skipped: %lu %s", save_state->skipped, append_skipped);
widget_add_string_element(widget, 0, index, AlignLeft, AlignTop, FontSecondary, draw_str);
widget_add_string_element(
widget, 0, index + 10, AlignLeft, AlignTop, FontSecondary, "(already has keys)");
index += 20;
}
if(save_state->invalid) {
char append_invalid[8] = {'s', 'e', 'c', 't', 'o', 'r', ' ', '\0'};
if(save_state->invalid != 1) {
append_invalid[6] = 's';
}
char draw_str[32] = {};
snprintf(
draw_str, sizeof(draw_str), "Invalid: %lu %s", save_state->invalid, append_invalid);
widget_add_string_element(widget, 0, index, AlignLeft, AlignTop, FontSecondary, draw_str);
widget_add_string_element(
widget, 0, index + 10, AlignLeft, AlignTop, FontSecondary, "(can't auth)");
}
free(save_state);
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_no_nonces_collected_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_no_nonces_collected_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_no_nonces_collected_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,58 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_nonces_collected_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_nonces_collected_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
notification_message(mifare_nested->notifications, &sequence_success);
widget_add_icon_element(widget, 52, 17, &I_DolphinSuccess);
widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Nonces collected");
widget_add_string_element(
widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "Now you can run");
widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "script on your");
widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "PC to recover");
widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, "keys");
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_nonces_collected_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_nonces_collected_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_nonces_collected_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,65 +0,0 @@
#include "../mifare_nested_i.h"
#include <lib/toolbox/value_index.h>
enum MifareNestedSettingsIndex { MifareNestedIndexBlock, MifareNestedIndexHardNested };
#define HARD_NESTED_COUNT 2
const char* const hard_nested_text[HARD_NESTED_COUNT] = {
"No",
"Yes",
};
const bool hard_nested_value[HARD_NESTED_COUNT] = {
false,
true,
};
static void mifare_nested_scene_settings_set_hard_nested(VariableItem* item) {
MifareNested* mifare_nested = variable_item_get_context(item);
uint8_t index = variable_item_get_current_value_index(item);
variable_item_set_current_value_text(item, hard_nested_text[index]);
mifare_nested->settings->only_hardnested = hard_nested_value[index];
}
void mifare_nested_scene_settings_on_enter(void* context) {
MifareNested* mifare_nested = context;
VariableItem* item;
uint8_t value_index;
item = variable_item_list_add(
mifare_nested->variable_item_list,
"Hard Nested only:",
HARD_NESTED_COUNT,
mifare_nested_scene_settings_set_hard_nested,
mifare_nested);
value_index = value_index_bool(
mifare_nested->settings->only_hardnested, hard_nested_value, HARD_NESTED_COUNT);
variable_item_set_current_value_index(item, value_index);
variable_item_set_current_value_text(item, hard_nested_text[value_index]);
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewVariableList);
}
bool mifare_nested_scene_settings_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == MifareNestedCustomEventSceneSettingLock) {
scene_manager_previous_scene(mifare_nested->scene_manager);
consumed = true;
}
}
return consumed;
}
void mifare_nested_scene_settings_on_exit(void* context) {
MifareNested* mifare_nested = context;
variable_item_list_set_selected_item(mifare_nested->variable_item_list, 0);
variable_item_list_reset(mifare_nested->variable_item_list);
scene_manager_set_scene_state(mifare_nested->scene_manager, MifareNestedSceneStart, 0);
}

View File

@@ -1,84 +0,0 @@
#include "../mifare_nested_i.h"
enum SubmenuIndex {
SubmenuIndexCollect,
SubmenuIndexCheck,
SubmenuIndexSettings,
SubmenuIndexAbout
};
void mifare_nested_scene_start_submenu_callback(void* context, uint32_t index) {
MifareNested* mifare_nested = context;
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, index);
}
void mifare_nested_scene_start_on_enter(void* context) {
MifareNested* mifare_nested = context;
Submenu* submenu = mifare_nested->submenu;
submenu_add_item(
submenu,
"Nested attack",
SubmenuIndexCollect,
mifare_nested_scene_start_submenu_callback,
mifare_nested);
submenu_add_item(
submenu,
"Check found keys",
SubmenuIndexCheck,
mifare_nested_scene_start_submenu_callback,
mifare_nested);
submenu_add_item(
submenu,
"Settings",
SubmenuIndexSettings,
mifare_nested_scene_start_submenu_callback,
mifare_nested);
submenu_add_item(
submenu,
"About",
SubmenuIndexAbout,
mifare_nested_scene_start_submenu_callback,
mifare_nested);
submenu_set_selected_item(
submenu,
scene_manager_get_scene_state(mifare_nested->scene_manager, MifareNestedSceneStart));
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewMenu);
}
bool mifare_nested_scene_start_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == SubmenuIndexCollect) {
mifare_nested->run = NestedRunAttack;
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheck);
consumed = true;
} else if(event.event == SubmenuIndexCheck) {
mifare_nested->run = NestedRunCheckKeys;
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheck);
consumed = true;
} else if(event.event == SubmenuIndexSettings) {
mifare_nested->keys->found_keys = 123;
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneSettings);
consumed = true;
} else if(event.event == SubmenuIndexAbout) {
scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneAbout);
consumed = true;
}
scene_manager_set_scene_state(
mifare_nested->scene_manager, MifareNestedSceneStart, event.event);
}
return consumed;
}
void mifare_nested_scene_start_on_exit(void* context) {
MifareNested* mifare_nested = context;
submenu_reset(mifare_nested->submenu);
}

View File

@@ -1,58 +0,0 @@
#include "../mifare_nested_i.h"
void mifare_nested_scene_static_encrypted_nonce_widget_callback(
GuiButtonType result,
InputType type,
void* context) {
MifareNested* mifare_nested = context;
if(type == InputTypeShort) {
view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);
}
}
void mifare_nested_scene_static_encrypted_nonce_on_enter(void* context) {
MifareNested* mifare_nested = context;
Widget* widget = mifare_nested->widget;
notification_message(mifare_nested->notifications, &sequence_error);
widget_add_icon_element(widget, 73, 12, &I_DolphinCry);
widget_add_string_element(
widget, 0, 0, AlignLeft, AlignTop, FontPrimary, "Static encrypted nonce");
widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, "This tag isn't");
widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, "vulnerable to");
widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, "Nested attack");
widget_add_button_element(
widget,
GuiButtonTypeLeft,
"Back",
mifare_nested_scene_static_encrypted_nonce_widget_callback,
mifare_nested);
// Setup and start worker
view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);
}
bool mifare_nested_scene_static_encrypted_nonce_on_event(void* context, SceneManagerEvent event) {
MifareNested* mifare_nested = context;
bool consumed = false;
if(event.type == SceneManagerEventTypeCustom) {
if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
} else if(event.type == SceneManagerEventTypeBack) {
scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);
consumed = true;
}
return consumed;
}
void mifare_nested_scene_static_encrypted_nonce_on_exit(void* context) {
MifareNested* mifare_nested = context;
widget_reset(mifare_nested->widget);
}

View File

@@ -1,16 +0,0 @@
App(
appid="zero_tracker",
name="Zero Tracker",
apptype=FlipperAppType.EXTERNAL,
entry_point="zero_tracker_app",
requires=[
"gui",
],
stack_size=4 * 1024,
fap_icon="zero_tracker.png",
fap_category="Media",
fap_author="@DrZlo13",
fap_weburl="https://github.com/DrZlo13/flipper-zero-music-tracker",
fap_version="1.1",
fap_description="App plays hardcoded tracker song",
)

View File

@@ -1,109 +0,0 @@
#include "speaker_hal.h"
#define FURI_HAL_SPEAKER_TIMER TIM16
#define FURI_HAL_SPEAKER_CHANNEL LL_TIM_CHANNEL_CH1
#define FURI_HAL_SPEAKER_PRESCALER 500
void tracker_speaker_play(float frequency, float pwm) {
uint32_t autoreload = (SystemCoreClock / FURI_HAL_SPEAKER_PRESCALER / frequency) - 1;
if(autoreload < 2) {
autoreload = 2;
} else if(autoreload > UINT16_MAX) {
autoreload = UINT16_MAX;
}
if(pwm < 0) pwm = 0;
if(pwm > 1) pwm = 1;
uint32_t compare_value = pwm * autoreload;
if(compare_value == 0) {
compare_value = 1;
}
if(LL_TIM_OC_GetCompareCH1(FURI_HAL_SPEAKER_TIMER) != compare_value) {
LL_TIM_OC_SetCompareCH1(FURI_HAL_SPEAKER_TIMER, compare_value);
}
if(LL_TIM_GetAutoReload(FURI_HAL_SPEAKER_TIMER) != autoreload) {
LL_TIM_SetAutoReload(FURI_HAL_SPEAKER_TIMER, autoreload);
if(LL_TIM_GetCounter(FURI_HAL_SPEAKER_TIMER) > autoreload) {
LL_TIM_SetCounter(FURI_HAL_SPEAKER_TIMER, 0);
}
}
LL_TIM_EnableAllOutputs(FURI_HAL_SPEAKER_TIMER);
}
void tracker_speaker_stop() {
LL_TIM_DisableAllOutputs(FURI_HAL_SPEAKER_TIMER);
}
void tracker_speaker_init() {
if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(1000)) {
furi_hal_speaker_start(200.0f, 0.01f);
tracker_speaker_stop();
}
}
void tracker_speaker_deinit() {
if(furi_hal_speaker_is_mine()) {
furi_hal_speaker_stop();
furi_hal_speaker_release();
}
}
static FuriHalInterruptISR tracker_isr;
static void* tracker_isr_context;
static void tracker_interrupt_cb(void* context) {
UNUSED(context);
if(LL_TIM_IsActiveFlag_UPDATE(TIM2)) {
LL_TIM_ClearFlag_UPDATE(TIM2);
if(tracker_isr) {
tracker_isr(tracker_isr_context);
}
}
}
void tracker_interrupt_init(float freq, FuriHalInterruptISR isr, void* context) {
tracker_isr = isr;
tracker_isr_context = context;
furi_hal_bus_enable(FuriHalBusTIM2);
furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, tracker_interrupt_cb, NULL);
LL_TIM_InitTypeDef TIM_InitStruct = {0};
// Prescaler to get 1kHz clock
TIM_InitStruct.Prescaler = SystemCoreClock / 1000000 - 1;
TIM_InitStruct.CounterMode = LL_TIM_COUNTERMODE_UP;
// Auto reload to get freq Hz interrupt
TIM_InitStruct.Autoreload = (1000000 / freq) - 1;
TIM_InitStruct.ClockDivision = LL_TIM_CLOCKDIVISION_DIV1;
LL_TIM_Init(TIM2, &TIM_InitStruct);
LL_TIM_EnableIT_UPDATE(TIM2);
LL_TIM_EnableAllOutputs(TIM2);
LL_TIM_EnableCounter(TIM2);
}
void tracker_interrupt_deinit() {
FURI_CRITICAL_ENTER();
furi_hal_bus_disable(FuriHalBusTIM2);
FURI_CRITICAL_EXIT();
furi_hal_interrupt_set_isr(FuriHalInterruptIdTIM2, NULL, NULL);
}
void tracker_debug_init() {
furi_hal_gpio_init(&gpio_ext_pc3, GpioModeOutputPushPull, GpioPullNo, GpioSpeedLow);
}
void tracker_debug_set(bool value) {
furi_hal_gpio_write(&gpio_ext_pc3, value);
}
void tracker_debug_deinit() {
furi_hal_gpio_init(&gpio_ext_pc3, GpioModeAnalog, GpioPullNo, GpioSpeedLow);
}

View File

@@ -1,19 +0,0 @@
#include <furi_hal.h>
void tracker_speaker_init();
void tracker_speaker_deinit();
void tracker_speaker_play(float frequency, float pwm);
void tracker_speaker_stop();
void tracker_interrupt_init(float freq, FuriHalInterruptISR isr, void* context);
void tracker_interrupt_deinit();
void tracker_debug_init();
void tracker_debug_set(bool value);
void tracker_debug_deinit();

View File

@@ -1,441 +0,0 @@
#include "tracker.h"
#include <stdbool.h>
#include "speaker_hal.h"
// SongState song_state = {
// .tick = 0,
// .tick_limit = 2,
// .row = 0,
// };
typedef struct {
uint8_t speed;
uint8_t depth;
int8_t direction;
int8_t value;
} IntegerOscillator;
typedef struct {
float frequency;
float frequency_target;
float pwm;
bool play;
IntegerOscillator vibrato;
} ChannelState;
typedef struct {
ChannelState* channels;
uint8_t tick;
uint8_t tick_limit;
uint8_t pattern_index;
uint8_t row_index;
uint8_t order_list_index;
} SongState;
typedef struct {
uint8_t note;
uint8_t effect;
uint8_t data;
} UnpackedRow;
struct Tracker {
const Song* song;
bool playing;
TrackerMessageCallback callback;
void* context;
SongState song_state;
};
static void channels_state_init(ChannelState* channel) {
channel->frequency = 0;
channel->frequency_target = FREQUENCY_UNSET;
channel->pwm = PWM_DEFAULT;
channel->play = false;
channel->vibrato.speed = 0;
channel->vibrato.depth = 0;
channel->vibrato.direction = 0;
channel->vibrato.value = 0;
}
static void tracker_song_state_init(Tracker* tracker) {
tracker->song_state.tick = 0;
tracker->song_state.tick_limit = 2;
tracker->song_state.row_index = 0;
tracker->song_state.order_list_index = 0;
tracker->song_state.pattern_index = tracker->song->order_list[0];
if(tracker->song_state.channels != NULL) {
free(tracker->song_state.channels);
}
tracker->song_state.channels = malloc(sizeof(ChannelState) * tracker->song->channels_count);
for(uint8_t i = 0; i < tracker->song->channels_count; i++) {
channels_state_init(&tracker->song_state.channels[i]);
}
}
static void tracker_song_state_clear(Tracker* tracker) {
if(tracker->song_state.channels != NULL) {
free(tracker->song_state.channels);
tracker->song_state.channels = NULL;
}
}
static uint8_t record_get_note(Row note) {
return note & ROW_NOTE_MASK;
}
static uint8_t record_get_effect(Row note) {
return (note >> 6) & ROW_EFFECT_MASK;
}
static uint8_t record_get_effect_data(Row note) {
return (note >> 10) & ROW_EFFECT_DATA_MASK;
}
#define NOTES_PER_OCT 12
const float notes_oct[NOTES_PER_OCT] = {
130.813f,
138.591f,
146.832f,
155.563f,
164.814f,
174.614f,
184.997f,
195.998f,
207.652f,
220.00f,
233.082f,
246.942f,
};
static float note_to_freq(uint8_t note) {
if(note == NOTE_NONE) return 0.0f;
note = note - NOTE_C2;
uint8_t octave = note / NOTES_PER_OCT;
uint8_t note_in_oct = note % NOTES_PER_OCT;
return notes_oct[note_in_oct] * (1 << octave);
}
static float frequency_offset_semitones(float frequency, uint8_t semitones) {
return frequency * (1.0f + ((1.0f / 12.0f) * semitones));
}
static float frequency_get_seventh_of_a_semitone(float frequency) {
return frequency * ((1.0f / 12.0f) / 7.0f);
}
static UnpackedRow get_current_row(const Song* song, SongState* song_state, uint8_t channel) {
const Pattern* pattern = &song->patterns[song_state->pattern_index];
const Row row = pattern->channels[channel].rows[song_state->row_index];
return (UnpackedRow){
.note = record_get_note(row),
.effect = record_get_effect(row),
.data = record_get_effect_data(row),
};
}
static int16_t advance_order_and_get_next_pattern_index(const Song* song, SongState* song_state) {
song_state->order_list_index++;
if(song_state->order_list_index >= song->order_list_size) {
return -1;
} else {
return song->order_list[song_state->order_list_index];
}
}
typedef struct {
int16_t pattern;
int16_t row;
bool change_pattern;
bool change_row;
} Location;
static void tracker_send_position_message(Tracker* tracker) {
if(tracker->callback != NULL) {
tracker->callback(
(TrackerMessage){
.type = TrackerPositionChanged,
.data =
{
.position =
{
.order_list_index = tracker->song_state.order_list_index,
.row = tracker->song_state.row_index,
},
},
},
tracker->context);
}
}
static void tracker_send_end_message(Tracker* tracker) {
if(tracker->callback != NULL) {
tracker->callback((TrackerMessage){.type = TrackerEndOfSong}, tracker->context);
}
}
static void advance_to_pattern(Tracker* tracker, Location advance) {
if(advance.change_pattern) {
if(advance.pattern < 0 || advance.pattern >= tracker->song->patterns_count) {
tracker->playing = false;
tracker_send_end_message(tracker);
} else {
tracker->song_state.pattern_index = advance.pattern;
tracker->song_state.row_index = 0;
}
}
if(advance.change_row) {
if(advance.row < 0) advance.row = 0;
if(advance.row >= PATTERN_SIZE) advance.row = PATTERN_SIZE - 1;
tracker->song_state.row_index = advance.row;
}
tracker_send_position_message(tracker);
}
static void tracker_interrupt_body(Tracker* tracker) {
if(!tracker->playing) {
tracker_speaker_stop();
return;
}
const uint8_t channel_index = 0;
SongState* song_state = &tracker->song_state;
ChannelState* channel_state = &song_state->channels[channel_index];
const Song* song = tracker->song;
UnpackedRow row = get_current_row(song, song_state, channel_index);
// load frequency from note at tick 0
if(song_state->tick == 0) {
bool invalidate_row = false;
// handle "on first tick" effects
if(row.effect == EffectBreakPattern) {
int16_t next_row_index = row.data;
int16_t next_pattern_index =
advance_order_and_get_next_pattern_index(song, song_state);
advance_to_pattern(
tracker,
(Location){
.pattern = next_pattern_index,
.row = next_row_index,
.change_pattern = true,
.change_row = true,
});
invalidate_row = true;
}
if(row.effect == EffectJumpToOrder) {
song_state->order_list_index = row.data;
int16_t next_pattern_index = song->order_list[song_state->order_list_index];
advance_to_pattern(
tracker,
(Location){
.pattern = next_pattern_index,
.change_pattern = true,
});
invalidate_row = true;
}
// tracker state can be affected by effects
if(!tracker->playing) {
tracker_speaker_stop();
return;
}
if(invalidate_row) {
row = get_current_row(song, song_state, channel_index);
if(row.effect == EffectSetSpeed) {
song_state->tick_limit = row.data;
}
}
// handle note effects
if(row.note == NOTE_OFF) {
channel_state->play = false;
} else if((row.note > NOTE_NONE) && (row.note < NOTE_OFF)) {
channel_state->play = true;
// reset vibrato
channel_state->vibrato.speed = 0;
channel_state->vibrato.depth = 0;
channel_state->vibrato.value = 0;
channel_state->vibrato.direction = 0;
// reset pwm
channel_state->pwm = PWM_DEFAULT;
if(row.effect == EffectSlideToNote) {
channel_state->frequency_target = note_to_freq(row.note);
} else {
channel_state->frequency = note_to_freq(row.note);
channel_state->frequency_target = FREQUENCY_UNSET;
}
}
}
if(channel_state->play) {
float frequency, pwm;
if((row.effect == EffectSlideUp || row.effect == EffectSlideDown) &&
row.data != EFFECT_DATA_NONE) {
// apply slide effect
channel_state->frequency += (row.effect == EffectSlideUp ? 1 : -1) * row.data;
} else if(row.effect == EffectSlideToNote) {
// apply slide to note effect, if target frequency is set
if(channel_state->frequency_target > 0) {
if(channel_state->frequency_target > channel_state->frequency) {
channel_state->frequency += row.data;
if(channel_state->frequency > channel_state->frequency_target) {
channel_state->frequency = channel_state->frequency_target;
channel_state->frequency_target = FREQUENCY_UNSET;
}
} else if(channel_state->frequency_target < channel_state->frequency) {
channel_state->frequency -= row.data;
if(channel_state->frequency < channel_state->frequency_target) {
channel_state->frequency = channel_state->frequency_target;
channel_state->frequency_target = FREQUENCY_UNSET;
}
}
}
}
frequency = channel_state->frequency;
pwm = channel_state->pwm;
// apply arpeggio effect
if(row.effect == EffectArpeggio) {
if(row.data != EFFECT_DATA_NONE) {
if((song_state->tick % 3) == 1) {
uint8_t note_offset = EFFECT_DATA_GET_X(row.data);
frequency = frequency_offset_semitones(frequency, note_offset);
} else if((song_state->tick % 3) == 2) {
uint8_t note_offset = EFFECT_DATA_GET_Y(row.data);
frequency = frequency_offset_semitones(frequency, note_offset);
}
}
} else if(row.effect == EffectVibrato) {
// apply vibrato effect, data = speed, depth
uint8_t vibrato_speed = EFFECT_DATA_GET_X(row.data);
uint8_t vibrato_depth = EFFECT_DATA_GET_Y(row.data);
// update vibrato parameters if speed or depth is non-zero
if(vibrato_speed != 0) channel_state->vibrato.speed = vibrato_speed;
if(vibrato_depth != 0) channel_state->vibrato.depth = vibrato_depth;
// update vibrato value
channel_state->vibrato.value +=
channel_state->vibrato.direction * channel_state->vibrato.speed;
// change direction if value is at the limit
if(channel_state->vibrato.value > channel_state->vibrato.depth) {
channel_state->vibrato.direction = -1;
} else if(channel_state->vibrato.value < -channel_state->vibrato.depth) {
channel_state->vibrato.direction = 1;
} else if(channel_state->vibrato.direction == 0) {
// set initial direction, if it is not set
channel_state->vibrato.direction = 1;
}
frequency +=
(frequency_get_seventh_of_a_semitone(frequency) * channel_state->vibrato.value);
} else if(row.effect == EffectPWM) {
pwm = (pwm - PWM_MIN) / EFFECT_DATA_1_MAX * row.data + PWM_MIN;
}
tracker_speaker_play(frequency, pwm);
} else {
tracker_speaker_stop();
}
song_state->tick++;
if(song_state->tick >= song_state->tick_limit) {
song_state->tick = 0;
// next note
song_state->row_index = (song_state->row_index + 1);
if(song_state->row_index >= PATTERN_SIZE) {
int16_t next_pattern_index =
advance_order_and_get_next_pattern_index(song, song_state);
advance_to_pattern(
tracker,
(Location){
.pattern = next_pattern_index,
.change_pattern = true,
});
} else {
tracker_send_position_message(tracker);
}
}
}
static void tracker_interrupt_cb(void* context) {
Tracker* tracker = (Tracker*)context;
tracker_debug_set(true);
tracker_interrupt_body(tracker);
tracker_debug_set(false);
}
/*********************************************************************
* Tracker Interface
*********************************************************************/
Tracker* tracker_alloc() {
Tracker* tracker = malloc(sizeof(Tracker));
return tracker;
}
void tracker_free(Tracker* tracker) {
tracker_song_state_clear(tracker);
free(tracker);
}
void tracker_set_message_callback(Tracker* tracker, TrackerMessageCallback callback, void* context) {
furi_check(tracker->playing == false);
tracker->callback = callback;
tracker->context = context;
}
void tracker_set_song(Tracker* tracker, const Song* song) {
furi_check(tracker->playing == false);
tracker->song = song;
tracker_song_state_init(tracker);
}
void tracker_set_order_index(Tracker* tracker, uint8_t order_index) {
furi_check(tracker->playing == false);
furi_check(order_index < tracker->song->order_list_size);
tracker->song_state.order_list_index = order_index;
tracker->song_state.pattern_index = tracker->song->order_list[order_index];
}
void tracker_set_row(Tracker* tracker, uint8_t row) {
furi_check(tracker->playing == false);
furi_check(row < PATTERN_SIZE);
tracker->song_state.row_index = row;
}
void tracker_start(Tracker* tracker) {
furi_check(tracker->song != NULL);
tracker->playing = true;
tracker_send_position_message(tracker);
tracker_debug_init();
tracker_speaker_init();
tracker_interrupt_init(tracker->song->ticks_per_second, tracker_interrupt_cb, tracker);
}
void tracker_stop(Tracker* tracker) {
tracker_interrupt_deinit();
tracker_speaker_deinit();
tracker_debug_deinit();
tracker->playing = false;
}

View File

@@ -1,38 +0,0 @@
#pragma once
#include "tracker_notes.h"
#include "tracker_song.h"
typedef enum {
TrackerPositionChanged,
TrackerEndOfSong,
} TrackerMessageType;
typedef struct {
TrackerMessageType type;
union tracker_message_data {
struct {
uint8_t order_list_index;
uint8_t row;
} position;
} data;
} TrackerMessage;
typedef void (*TrackerMessageCallback)(TrackerMessage message, void* context);
typedef struct Tracker Tracker;
Tracker* tracker_alloc();
void tracker_free(Tracker* tracker);
void tracker_set_message_callback(Tracker* tracker, TrackerMessageCallback callback, void* context);
void tracker_set_song(Tracker* tracker, const Song* song);
void tracker_set_order_index(Tracker* tracker, uint8_t order_index);
void tracker_set_row(Tracker* tracker, uint8_t row);
void tracker_start(Tracker* tracker);
void tracker_stop(Tracker* tracker);

View File

@@ -1,64 +0,0 @@
#pragma once
#define NOTE_NONE 0
#define NOTE_C2 1
#define NOTE_Cs2 2
#define NOTE_D2 3
#define NOTE_Ds2 4
#define NOTE_E2 5
#define NOTE_F2 6
#define NOTE_Fs2 7
#define NOTE_G2 8
#define NOTE_Gs2 9
#define NOTE_A2 10
#define NOTE_As2 11
#define NOTE_B2 12
#define NOTE_C3 13
#define NOTE_Cs3 14
#define NOTE_D3 15
#define NOTE_Ds3 16
#define NOTE_E3 17
#define NOTE_F3 18
#define NOTE_Fs3 19
#define NOTE_G3 20
#define NOTE_Gs3 21
#define NOTE_A3 22
#define NOTE_As3 23
#define NOTE_B3 24
#define NOTE_C4 25
#define NOTE_Cs4 26
#define NOTE_D4 27
#define NOTE_Ds4 28
#define NOTE_E4 29
#define NOTE_F4 30
#define NOTE_Fs4 31
#define NOTE_G4 32
#define NOTE_Gs4 33
#define NOTE_A4 34
#define NOTE_As4 35
#define NOTE_B4 36
#define NOTE_C5 37
#define NOTE_Cs5 38
#define NOTE_D5 39
#define NOTE_Ds5 40
#define NOTE_E5 41
#define NOTE_F5 42
#define NOTE_Fs5 43
#define NOTE_G5 44
#define NOTE_Gs5 45
#define NOTE_A5 46
#define NOTE_As5 47
#define NOTE_B5 48
#define NOTE_C6 49
#define NOTE_Cs6 50
#define NOTE_D6 51
#define NOTE_Ds6 52
#define NOTE_E6 53
#define NOTE_F6 54
#define NOTE_Fs6 55
#define NOTE_G6 56
#define NOTE_Gs6 57
#define NOTE_A6 58
#define NOTE_As6 59
#define NOTE_B6 60
#define NOTE_OFF 63

View File

@@ -1,109 +0,0 @@
#pragma once
#include <stdint.h>
/**
* @brief Row
*
* AH AL
* FEDCBA98 76543210
* nnnnnnee eedddddd
* -------- --------
* nnnnnn = [0] do nothing, [1..60] note number, [61] note off, [62..63] not used
* ee ee = [0..F] effect
* 111222 = [0..63] or [0..7, 0..7] effect data
*/
typedef uint16_t Row;
#define ROW_NOTE_MASK 0x3F
#define ROW_EFFECT_MASK 0x0F
#define ROW_EFFECT_DATA_MASK 0x3F
typedef enum {
// 0xy, x - first semitones offset, y - second semitones offset. 0 - no offset .. 7 - +7 semitones...
// Play the arpeggio chord with three notes. The first note is the base note, the second and third are offset by x and y.
// Each note plays one tick.
EffectArpeggio = 0x00,
// 1xx, xx - effect speed, 0 - no effect, 1 - slowest, 0x3F - fastest.
// Slide the note pitch up by xx Hz every tick.
EffectSlideUp = 0x01,
// 2xx, xx - effect speed, 0 - no effect, 1 - slowest, 0x3F - fastest.
// Slide the note pitch down by xx Hz every tick.
EffectSlideDown = 0x02,
// 3xx, xx - effect speed, 0 - no effect, 1 - slowest, 0x3F - fastest.
// Slide the already playing note pitch towards another one by xx Hz every tick.
// The note value is saved until the note is playing, so you don't have to repeat the note value to continue sliding.
EffectSlideToNote = 0x03,
// 4xy, x - vibrato speed (0..7), y - vibrato depth (0..7).
// Vibrato effect. The pitch of the note increases by x Hz each tick to a positive vibrato depth, then decreases to a negative depth.
// Value 1 of depth means 1/7 of a semitone (about 14.28 ct), so value 7 means full semitone.
// Note will play without vibrato on the first tick at the beginning of the effect.
// Vibrato speed and depth are saved until the note is playing, and will be updated only if they are not zero, so you doesn't have to repeat them every tick.
EffectVibrato = 0x04,
// Effect05 = 0x05,
// Effect06 = 0x06,
// Effect07 = 0x07,
// Effect08 = 0x08,
// Effect09 = 0x09,
// Effect0A = 0x0A,
// Bxx, xx - pattern number
// Jump to the order xx in the pattern order table at first tick of current row.
// So if you want to jump to the pattern after note 4, you should put this effect on the 5th note.
EffectJumpToOrder = 0x0B,
// Cxx, xx - pwm value
// Set the PWM value to xx for current row.
EffectPWM = 0x0C,
// Bxx, xx - row number
// Jump to the row xx in next pattern at first tick of current row.
// So if you want to jump to the pattern after note 4, you should put this effect on the 5th note.
EffectBreakPattern = 0x0D,
// Effect0E = 0x0E,
// Fxx, xx - song speed, 0 - 1 tick per note, 1 - 2 ticks per note, 0x3F - 64 ticks per note.
// Set the speed of the song in terms of ticks per note.
// Will be applied at the first tick of current row.
EffectSetSpeed = 0x0F,
} Effect;
#define EFFECT_DATA_2(x, y) ((x) | ((y) << 3))
#define EFFECT_DATA_GET_X(data) ((data)&0x07)
#define EFFECT_DATA_GET_Y(data) (((data) >> 3) & 0x07)
#define EFFECT_DATA_NONE 0
#define EFFECT_DATA_1_MAX 0x3F
#define EFFECT_DATA_2_MAX 0x07
#define FREQUENCY_UNSET -1.0f
#define PWM_MIN 0.01f
#define PWM_MAX 0.5f
#define PWM_DEFAULT PWM_MAX
#define PATTERN_SIZE 64
#define ROW_MAKE(note, effect, data) \
((Row)(((note)&0x3F) | (((effect)&0xF) << 6) | (((data)&0x3F) << 10)))
typedef struct {
Row rows[PATTERN_SIZE];
} Channel;
typedef struct {
Channel* channels;
} Pattern;
typedef struct {
uint8_t channels_count;
uint8_t patterns_count;
Pattern* patterns;
uint8_t order_list_size;
uint8_t* order_list;
uint16_t ticks_per_second;
} Song;

View File

@@ -1,182 +0,0 @@
#include "tracker_view.h"
#include <gui/elements.h>
#include <furi.h>
typedef struct {
const Song* song;
uint8_t order_list_index;
uint8_t row;
} TrackerViewModel;
struct TrackerView {
View* view;
void* back_context;
TrackerViewCallback back_callback;
};
static Channel* get_current_channel(TrackerViewModel* model) {
uint8_t channel_id = 0;
uint8_t pattern_id = model->song->order_list[model->order_list_index];
Pattern* pattern = &model->song->patterns[pattern_id];
return &pattern->channels[channel_id];
}
static const char* get_note_from_id(uint8_t note) {
#define NOTE_COUNT 12
const char* notes[NOTE_COUNT] = {
"C ",
"C#",
"D ",
"D#",
"E ",
"F ",
"F#",
"G ",
"G#",
"A ",
"A#",
"B ",
};
return notes[(note) % NOTE_COUNT];
#undef NOTE_COUNT
}
static uint8_t get_octave_from_id(uint8_t note) {
return ((note) / 12) + 2;
}
static uint8_t get_first_row_id(uint8_t row) {
return (row / 10) * 10;
}
static void
draw_row(Canvas* canvas, uint8_t i, Channel* channel, uint8_t row, FuriString* buffer) {
uint8_t x = 12 * (i + 1);
uint8_t first_row_id = get_first_row_id(row);
uint8_t current_row_id = first_row_id + i;
if((current_row_id) >= 64) {
return;
}
Row current_row = channel->rows[current_row_id];
uint8_t note = current_row & ROW_NOTE_MASK;
uint8_t effect = (current_row >> 6) & ROW_EFFECT_MASK;
uint8_t data = (current_row >> 10) & ROW_EFFECT_DATA_MASK;
if(current_row_id == row) {
canvas_set_color(canvas, ColorBlack);
canvas_draw_line(canvas, x - 9, 1, x - 9, 62);
canvas_draw_box(canvas, x - 8, 0, 9, 64);
canvas_draw_line(canvas, x + 1, 1, x + 1, 62);
canvas_set_color(canvas, ColorWhite);
}
furi_string_printf(buffer, "%02X", current_row_id);
canvas_draw_str(canvas, x, 61, furi_string_get_cstr(buffer));
if(note > 0 && note < NOTE_OFF) {
furi_string_printf(
buffer, "%s%d", get_note_from_id(note - 1), get_octave_from_id(note - 1));
canvas_draw_str(canvas, x, 44, furi_string_get_cstr(buffer));
} else if(note == NOTE_OFF) {
canvas_draw_str(canvas, x, 44, "OFF");
} else {
canvas_draw_str(canvas, x, 44, "---");
}
if(effect == 0 && data == 0) {
canvas_draw_str(canvas, x, 21, "-");
canvas_draw_str(canvas, x, 12, "--");
} else {
furi_string_printf(buffer, "%X", effect);
canvas_draw_str(canvas, x, 21, furi_string_get_cstr(buffer));
if(effect == EffectArpeggio || effect == EffectVibrato) {
uint8_t data_x = EFFECT_DATA_GET_X(data);
uint8_t data_y = EFFECT_DATA_GET_Y(data);
furi_string_printf(buffer, "%d%d", data_x, data_y);
canvas_draw_str(canvas, x, 12, furi_string_get_cstr(buffer));
} else {
furi_string_printf(buffer, "%02X", data);
canvas_draw_str(canvas, x, 12, furi_string_get_cstr(buffer));
}
}
if(current_row_id == row) {
canvas_set_color(canvas, ColorBlack);
}
}
static void tracker_view_draw_callback(Canvas* canvas, void* _model) {
TrackerViewModel* model = _model;
if(model->song == NULL) {
return;
}
canvas_set_font_direction(canvas, CanvasDirectionBottomToTop);
canvas_set_font(canvas, FontKeyboard);
Channel* channel = get_current_channel(model);
FuriString* buffer = furi_string_alloc();
for(uint8_t i = 0; i < 10; i++) {
draw_row(canvas, i, channel, model->row, buffer);
}
furi_string_free(buffer);
}
static bool tracker_view_input_callback(InputEvent* event, void* context) {
TrackerView* tracker_view = context;
if(tracker_view->back_callback) {
if(event->type == InputTypeShort && event->key == InputKeyBack) {
tracker_view->back_callback(tracker_view->back_context);
return true;
}
}
return false;
}
TrackerView* tracker_view_alloc() {
TrackerView* tracker_view = malloc(sizeof(TrackerView));
tracker_view->view = view_alloc();
view_allocate_model(tracker_view->view, ViewModelTypeLocking, sizeof(TrackerViewModel));
view_set_context(tracker_view->view, tracker_view);
view_set_draw_callback(tracker_view->view, (ViewDrawCallback)tracker_view_draw_callback);
view_set_input_callback(tracker_view->view, (ViewInputCallback)tracker_view_input_callback);
return tracker_view;
}
void tracker_view_free(TrackerView* tracker_view) {
view_free(tracker_view->view);
free(tracker_view);
}
View* tracker_view_get_view(TrackerView* tracker_view) {
return tracker_view->view;
}
void tracker_view_set_back_callback(
TrackerView* tracker_view,
TrackerViewCallback callback,
void* context) {
tracker_view->back_callback = callback;
tracker_view->back_context = context;
}
void tracker_view_set_song(TrackerView* tracker_view, const Song* song) {
with_view_model(
tracker_view->view, TrackerViewModel * model, { model->song = song; }, true);
}
void tracker_view_set_position(TrackerView* tracker_view, uint8_t order_list_index, uint8_t row) {
with_view_model(
tracker_view->view,
TrackerViewModel * model,
{
model->order_list_index = order_list_index;
model->row = row;
},
true);
}

View File

@@ -1,29 +0,0 @@
#include <gui/view.h>
#include "../tracker_engine/tracker.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct TrackerView TrackerView;
TrackerView* tracker_view_alloc();
void tracker_view_free(TrackerView* tracker_view);
View* tracker_view_get_view(TrackerView* tracker_view);
typedef void (*TrackerViewCallback)(void* context);
void tracker_view_set_back_callback(
TrackerView* tracker_view,
TrackerViewCallback callback,
void* context);
void tracker_view_set_song(TrackerView* tracker_view, const Song* song);
void tracker_view_set_position(TrackerView* tracker_view, uint8_t order_list_index, uint8_t row);
#ifdef __cplusplus
}
#endif

View File

@@ -1,536 +0,0 @@
#include <furi.h>
#include <gui/gui.h>
#include <gui/view_dispatcher.h>
#include <notification/notification_messages.h>
#include "zero_tracker.h"
#include "tracker_engine/tracker.h"
#include "view/tracker_view.h"
// Channel p_0_channels[] = {
// {
// .rows =
// {
// // 1/4
// ROW_MAKE(NOTE_C3, EffectArpeggio, EFFECT_DATA_2(4, 7)),
// ROW_MAKE(0, EffectArpeggio, EFFECT_DATA_2(4, 7)),
// ROW_MAKE(NOTE_C4, EffectSlideToNote, 0x20),
// ROW_MAKE(0, EffectSlideToNote, 0x20),
// //
// ROW_MAKE(0, EffectSlideToNote, 0x20),
// ROW_MAKE(0, EffectSlideToNote, 0x20),
// ROW_MAKE(0, EffectSlideToNote, 0x20),
// ROW_MAKE(0, EffectSlideToNote, 0x20),
// //
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
// //
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
// // 2/4
// ROW_MAKE(NOTE_C3, EffectSlideDown, 0x20),
// ROW_MAKE(0, EffectSlideDown, 0x20),
// ROW_MAKE(NOTE_C4, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// //
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// //
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// //
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(3, 3)),
// ROW_MAKE(NOTE_OFF, EffectVibrato, EFFECT_DATA_2(3, 3)),
// // 3/4
// ROW_MAKE(NOTE_C3, EffectArpeggio, EFFECT_DATA_2(4, 7)),
// ROW_MAKE(0, EffectArpeggio, EFFECT_DATA_2(4, 7)),
// ROW_MAKE(NOTE_OFF, 0, 0),
// ROW_MAKE(0, 0, 0),
// //
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// //
// ROW_MAKE(NOTE_C2, EffectPWM, 60),
// ROW_MAKE(0, EffectPWM, 32),
// ROW_MAKE(0, EffectPWM, 12),
// ROW_MAKE(NOTE_OFF, 0, 0),
// //
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// // 4/4
// ROW_MAKE(NOTE_C3, EffectSlideDown, 0x20),
// ROW_MAKE(0, EffectSlideDown, 0x20),
// ROW_MAKE(0, EffectSlideDown, 0x20),
// ROW_MAKE(NOTE_OFF, 0, 0),
// //
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// //
// ROW_MAKE(NOTE_C2, EffectPWM, 60),
// ROW_MAKE(0, EffectPWM, 32),
// ROW_MAKE(0, EffectPWM, 12),
// ROW_MAKE(NOTE_OFF, 0, 0),
// //
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// ROW_MAKE(0, 0, 0),
// },
// },
// };
Channel p_0_channels[] = {
{
.rows =
{
//
ROW_MAKE(NOTE_A4, EffectArpeggio, EFFECT_DATA_2(4, 7)),
ROW_MAKE(NOTE_C3, 0, 0),
ROW_MAKE(NOTE_F2, 0, 0),
ROW_MAKE(NOTE_C3, 0, 0),
//
ROW_MAKE(NOTE_E4, 0, 0),
ROW_MAKE(NOTE_C3, 0, 0),
ROW_MAKE(NOTE_E4, EffectPWM, 50),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_E5, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_C3, EffectSlideDown, 0x30),
ROW_MAKE(NOTE_F2, 0, 0),
ROW_MAKE(NOTE_C3, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_C3, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
//
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_B4, EffectArpeggio, EFFECT_DATA_2(4, 7)),
ROW_MAKE(NOTE_D3, 0, 0),
ROW_MAKE(NOTE_G2, 0, 0),
ROW_MAKE(NOTE_D3, 0, 0),
//
ROW_MAKE(NOTE_E4, 0, 0),
ROW_MAKE(NOTE_D3, 0, 0),
ROW_MAKE(NOTE_E4, EffectPWM, 50),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_E5, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_D3, EffectSlideDown, 0x3F),
ROW_MAKE(NOTE_G2, 0, 0),
ROW_MAKE(NOTE_D3, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_D3, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
//
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(NOTE_OFF, 0, 0),
},
},
};
Channel p_1_channels[] = {
{
.rows =
{
//
ROW_MAKE(NOTE_C5, EffectArpeggio, EFFECT_DATA_2(4, 7)),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 50),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_G4, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C6, 0, 0),
ROW_MAKE(NOTE_E3, EffectSlideDown, 0x30),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 50),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_G4, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
//
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C5, EffectArpeggio, EFFECT_DATA_2(4, 7)),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 50),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_G4, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(0, EffectPWM, 55),
ROW_MAKE(0, EffectPWM, 45),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C6, 0, 0),
ROW_MAKE(NOTE_E3, EffectSlideDown, 0x30),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 50),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_G4, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, 0, 0),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
//
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(1, 1)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(0, EffectVibrato, EFFECT_DATA_2(2, 2)),
ROW_MAKE(NOTE_OFF, 0, 0),
},
},
};
Channel p_2_channels[] = {
{
.rows =
{
//
ROW_MAKE(NOTE_C5, EffectArpeggio, EFFECT_DATA_2(4, 7)),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, 0, 0),
//
ROW_MAKE(NOTE_C5, EffectPWM, 55),
ROW_MAKE(NOTE_A4, EffectPWM, 45),
ROW_MAKE(NOTE_C5, EffectPWM, 35),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(NOTE_C5, EffectPWM, 55),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_E3, EffectSlideDown, 0x30),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_OFF, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 55),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_D5, EffectPWM, 55),
ROW_MAKE(NOTE_B4, EffectPWM, 55),
//
ROW_MAKE(NOTE_D5, EffectPWM, 45),
ROW_MAKE(NOTE_B4, EffectPWM, 45),
ROW_MAKE(NOTE_D5, EffectPWM, 35),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, EffectArpeggio, EFFECT_DATA_2(4, 7)),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_E5, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_E5, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
//
ROW_MAKE(NOTE_E5, EffectPWM, 55),
ROW_MAKE(NOTE_C5, EffectPWM, 45),
ROW_MAKE(NOTE_E5, EffectPWM, 35),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_E5, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_E5, EffectPWM, 55),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_E3, EffectSlideDown, 0x30),
ROW_MAKE(NOTE_A2, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
//
ROW_MAKE(NOTE_OFF, 0, 0),
ROW_MAKE(NOTE_E3, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 55),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_D5, EffectPWM, 55),
ROW_MAKE(NOTE_B4, EffectPWM, 55),
//
ROW_MAKE(NOTE_D5, EffectPWM, 45),
ROW_MAKE(NOTE_B4, EffectPWM, 45),
ROW_MAKE(NOTE_D5, EffectPWM, 35),
ROW_MAKE(NOTE_OFF, 0, 0),
},
},
};
Channel p_3_channels[] = {
{
.rows =
{
//
ROW_MAKE(NOTE_Ds5, EffectArpeggio, EFFECT_DATA_2(4, 6)),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_Ds5, 0, 0),
ROW_MAKE(NOTE_C5, EffectPWM, 55),
//
ROW_MAKE(NOTE_Ds5, EffectPWM, 45),
ROW_MAKE(NOTE_C5, EffectPWM, 35),
ROW_MAKE(NOTE_Ds5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 55),
//
ROW_MAKE(NOTE_D5, EffectPWM, 45),
ROW_MAKE(NOTE_B4, EffectPWM, 35),
ROW_MAKE(NOTE_D5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_Cs5, EffectArpeggio, EFFECT_DATA_2(4, 6)),
ROW_MAKE(NOTE_As4, 0, 0),
ROW_MAKE(NOTE_Cs5, 0, 0),
ROW_MAKE(NOTE_As4, EffectPWM, 55),
//
ROW_MAKE(NOTE_Cs5, EffectPWM, 45),
ROW_MAKE(NOTE_As4, EffectPWM, 35),
ROW_MAKE(NOTE_Cs5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, EffectPWM, 55),
//
ROW_MAKE(NOTE_C5, EffectPWM, 45),
ROW_MAKE(NOTE_A4, EffectPWM, 35),
ROW_MAKE(NOTE_C5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_B4, EffectArpeggio, EFFECT_DATA_2(4, 6)),
ROW_MAKE(NOTE_Gs4, 0, 0),
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_Gs4, EffectPWM, 55),
//
ROW_MAKE(NOTE_B4, EffectPWM, 45),
ROW_MAKE(NOTE_Gs4, EffectPWM, 35),
ROW_MAKE(NOTE_B4, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, 0, 0),
ROW_MAKE(NOTE_C5, 0, 0),
ROW_MAKE(NOTE_A4, EffectPWM, 55),
//
ROW_MAKE(NOTE_C5, EffectPWM, 45),
ROW_MAKE(NOTE_A4, EffectPWM, 35),
ROW_MAKE(NOTE_C5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_Cs5, EffectArpeggio, EFFECT_DATA_2(4, 6)),
ROW_MAKE(NOTE_As4, 0, 0),
ROW_MAKE(NOTE_Cs5, 0, 0),
ROW_MAKE(NOTE_As4, EffectPWM, 55),
//
ROW_MAKE(NOTE_Cs5, EffectPWM, 45),
ROW_MAKE(NOTE_As4, EffectPWM, 35),
ROW_MAKE(NOTE_Cs5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
//
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_B4, 0, 0),
ROW_MAKE(NOTE_D5, 0, 0),
ROW_MAKE(NOTE_B4, EffectPWM, 55),
//
ROW_MAKE(NOTE_D5, EffectPWM, 45),
ROW_MAKE(NOTE_B4, EffectPWM, 35),
ROW_MAKE(NOTE_D5, EffectPWM, 30),
ROW_MAKE(NOTE_OFF, 0, 0),
},
},
};
Pattern patterns[] = {
{.channels = p_0_channels},
{.channels = p_1_channels},
{.channels = p_2_channels},
{.channels = p_3_channels},
};
uint8_t order_list[] = {
0,
1,
0,
2,
0,
1,
0,
3,
};
Song song = {
.channels_count = 1,
.patterns_count = sizeof(patterns) / sizeof(patterns[0]),
.patterns = patterns,
.order_list_size = sizeof(order_list) / sizeof(order_list[0]),
.order_list = order_list,
.ticks_per_second = 60,
};
void tracker_message(TrackerMessage message, void* context) {
FuriMessageQueue* queue = context;
furi_assert(queue);
furi_message_queue_put(queue, &message, 0);
}
int32_t zero_tracker_app(void* p) {
UNUSED(p);
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
notification_message(notification, &sequence_display_backlight_enforce_on);
Gui* gui = furi_record_open(RECORD_GUI);
ViewDispatcher* view_dispatcher = view_dispatcher_alloc();
TrackerView* tracker_view = tracker_view_alloc();
tracker_view_set_song(tracker_view, &song);
view_dispatcher_add_view(view_dispatcher, 0, tracker_view_get_view(tracker_view));
view_dispatcher_attach_to_gui(view_dispatcher, gui, ViewDispatcherTypeFullscreen);
view_dispatcher_switch_to_view(view_dispatcher, 0);
FuriMessageQueue* queue = furi_message_queue_alloc(8, sizeof(TrackerMessage));
Tracker* tracker = tracker_alloc();
tracker_set_message_callback(tracker, tracker_message, queue);
tracker_set_song(tracker, &song);
tracker_start(tracker);
while(1) {
TrackerMessage message;
FuriStatus status = furi_message_queue_get(queue, &message, portMAX_DELAY);
if(status == FuriStatusOk) {
if(message.type == TrackerPositionChanged) {
uint8_t order_list_index = message.data.position.order_list_index;
uint8_t row = message.data.position.row;
uint8_t pattern = song.order_list[order_list_index];
tracker_view_set_position(tracker_view, order_list_index, row);
FURI_LOG_I("Tracker", "O:%d P:%d R:%d", order_list_index, pattern, row);
} else if(message.type == TrackerEndOfSong) {
FURI_LOG_I("Tracker", "End of song");
break;
}
}
}
tracker_stop(tracker);
tracker_free(tracker);
furi_message_queue_free(queue);
furi_delay_ms(500);
view_dispatcher_remove_view(view_dispatcher, 0);
tracker_view_free(tracker_view);
view_dispatcher_free(view_dispatcher);
notification_message(notification, &sequence_display_backlight_enforce_auto);
furi_record_close(RECORD_NOTIFICATION);
furi_record_close(RECORD_GUI);
return 0;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 B

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2022 RaZe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,24 +0,0 @@
# COMPILE ISTRUCTIONS:
# Clean the code and remove old binaries/compilation artefact
# ./fbt -c fap_rubiks_cube_scrambler
# Compile FAP
# ./fbt fap_rubiks_cube_scrambler
# Run application directly inside the Flip.x0
# ./fbt launch_app APPSRC=rubiks_cube_scrambler
App(
appid="rubiks_cube_scrambler",
name="Rubik's Cube Scrambler",
apptype=FlipperAppType.EXTERNAL,
entry_point="rubiks_cube_scrambler_main",
stack_size=1 * 1024,
fap_category="Games",
fap_icon="cube.png",
fap_author="@RaZeSloth",
fap_weburl="https://github.com/RaZeSloth/flipperzero-rubiks-cube-scrambler",
fap_version="1.1",
fap_description="App generates random moves to scramble a Rubik's cube.",
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 96 B

View File

@@ -1,113 +0,0 @@
#include <stdio.h>
#include <furi.h>
#include <gui/gui.h>
#include <input/input.h>
#include <gui/elements.h>
#include <furi_hal.h>
#include "scrambler.h"
#include "furi_hal_random.h"
bool scrambleStarted = false;
char scramble_str[100] = {0};
char scramble_start[100] = {0};
char scramble_end[100] = {0};
bool notifications_enabled = false;
static void success_vibration() {
furi_hal_vibro_on(false);
furi_hal_vibro_on(true);
furi_delay_ms(50);
furi_hal_vibro_on(false);
return;
}
void split_array(char original[], int size, char first[], char second[]) {
int32_t mid = size / 2;
if(size % 2 != 0) {
mid++;
}
int32_t first_index = 0, second_index = 0;
for(int32_t i = 0; i < size; i++) {
if(i < mid) {
first[first_index++] = original[i];
} else {
if(i == mid && (original[i] == '2' || original[i] == '\'')) {
continue;
}
second[second_index++] = original[i];
}
}
first[first_index] = '\0';
second[second_index] = '\0';
}
void genScramble() {
scrambleReplace();
strcpy(scramble_str, printData());
split_array(scramble_str, strlen(scramble_str), scramble_start, scramble_end);
}
static void draw_callback(Canvas* canvas, void* ctx) {
UNUSED(ctx);
canvas_clear(canvas);
canvas_set_font(canvas, FontPrimary);
canvas_draw_str(canvas, 4, 13, "Rubik's Cube Scrambler");
canvas_set_font(canvas, FontSecondary);
canvas_draw_str_aligned(canvas, 64, 28, AlignCenter, AlignCenter, scramble_start);
canvas_draw_str_aligned(canvas, 64, 38, AlignCenter, AlignCenter, scramble_end);
elements_button_center(canvas, "New");
elements_button_left(canvas, notifications_enabled ? "On" : "Off");
}
static void input_callback(InputEvent* input_event, void* ctx) {
furi_assert(ctx);
FuriMessageQueue* event_queue = ctx;
furi_message_queue_put(event_queue, input_event, FuriWaitForever);
}
int32_t rubiks_cube_scrambler_main(void* p) {
UNUSED(p);
InputEvent event;
FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(InputEvent));
ViewPort* view_port = view_port_alloc();
view_port_draw_callback_set(view_port, draw_callback, NULL);
view_port_input_callback_set(view_port, input_callback, event_queue);
Gui* gui = furi_record_open(RECORD_GUI);
gui_add_view_port(gui, view_port, GuiLayerFullscreen);
while(true) {
furi_check(furi_message_queue_get(event_queue, &event, FuriWaitForever) == FuriStatusOk);
if(event.key == InputKeyOk && event.type == InputTypeShort) {
genScramble();
if(notifications_enabled) {
success_vibration();
}
}
if(event.key == InputKeyLeft && event.type == InputTypeShort) {
if(notifications_enabled) {
notifications_enabled = false;
} else {
notifications_enabled = true;
success_vibration();
}
}
if(event.key == InputKeyBack) {
break;
}
view_port_update(view_port);
}
furi_message_queue_free(event_queue);
gui_remove_view_port(gui, view_port);
view_port_free(view_port);
furi_record_close(RECORD_GUI);
return 0;
}

View File

@@ -1,60 +0,0 @@
/*
Authors: Tanish Bhongade and RaZe
*/
#include <stdio.h>
#include <furi.h>
#include <gui/gui.h>
#include "furi_hal_random.h"
#include <input/input.h>
#include <gui/elements.h>
#include "scrambler.h"
// 6 moves along with direction
char moves[6] = {'R', 'U', 'F', 'B', 'L', 'D'};
char dir[4] = {'\'', '2'};
const int32_t SLEN = 20;
#define RESULT_SIZE 100
struct GetScramble {
char mainScramble[25][3];
};
struct GetScramble a;
void scrambleReplace() {
// Initialize the mainScramble array with all the possible moves
for(int32_t i = 0; i < SLEN; i++) {
a.mainScramble[i][0] = moves[furi_hal_random_get() % 6];
a.mainScramble[i][1] = dir[furi_hal_random_get() % 3];
}
/* // Perform the Fisher-Yates shuffle
for (int32_t i = 6 - 1; i > 0; i--)
{
int32_t j = rand() % (i + 1);
char temp[3];
strcpy(temp, a.mainScramble[i]);
strcpy(a.mainScramble[i], a.mainScramble[j]);
strcpy(a.mainScramble[j], temp);
} */
// Select the first 10 elements as the scramble, using only the first two elements of the dir array
for(int32_t i = 0; i < SLEN; i++) {
a.mainScramble[i][1] = dir[furi_hal_random_get() % 3];
}
for(int32_t i = 1; i < SLEN; i++) {
while(a.mainScramble[i][0] == a.mainScramble[i - 2][0] ||
a.mainScramble[i][0] == a.mainScramble[i - 1][0]) {
a.mainScramble[i][0] = moves[furi_hal_random_get() % 5];
}
}
}
char* printData() {
static char result[RESULT_SIZE];
int32_t offset = 0;
for(int32_t loop = 0; loop < SLEN; loop++) {
offset += snprintf(result + offset, RESULT_SIZE - offset, "%s ", a.mainScramble[loop]);
}
return result;
}

View File

@@ -1,2 +0,0 @@
void scrambleReplace();
char* printData();

View File

@@ -1,15 +0,0 @@
App(
appid="snake20",
name="Snake 2.0",
apptype=FlipperAppType.EXTERNAL,
entry_point="snake_20_app",
cdefines=["APP_SNAKE_20"],
requires=["gui"],
stack_size=1 * 1024,
fap_icon="snake_10px.png",
fap_category="Games",
fap_author="@Willzvul",
fap_weburl="https://github.com/Willzvul/Snake_2.0",
fap_version="2.0",
fap_description="Advanced Snake Game (Remake of original Snake)",
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 178 B

View File

@@ -1,528 +0,0 @@
#include <furi.h>
#include <gui/gui.h>
#include <input/input.h>
#include <stdlib.h>
#include <dolphin/dolphin.h>
#include <notification/notification.h>
#include <notification/notification_messages.h>
typedef struct {
// +-----x
// |
// |
// y
uint8_t x;
uint8_t y;
} Point;
typedef enum {
GameStateLife,
GameStatePause,
// https://melmagazine.com/en-us/story/snake-nokia-6110-oral-history-taneli-armanto
// Armanto: While testing the early versions of the game, I noticed it was hard
// to control the snake upon getting close to and edge but not crashing — especially
// in the highest speed levels. I wanted the highest level to be as fast as I could
// possibly make the device "run," but on the other hand, I wanted to be friendly
// and help the player manage that level. Otherwise it might not be fun to play. So
// I implemented a little delay. A few milliseconds of extra time right before
// the player crashes, during which she can still change the directions. And if
// she does, the game continues.
GameStateLastChance,
GameStateGameOver,
} GameState;
// Note: do not change without purpose. Current values are used in smart
// orthogonality calculation in `snake_game_get_turn_snake`.
typedef enum {
DirectionUp,
DirectionRight,
DirectionDown,
DirectionLeft,
} Direction;
#define MAX_SNAKE_LEN 15 * 31 //128 * 64 / 4
#define x_back_symbol 50
#define y_back_symbol 9
typedef struct {
FuriMutex* mutex;
Point points[MAX_SNAKE_LEN];
uint16_t len;
Direction currentMovement;
Direction nextMovement; // if backward of currentMovement, ignore
Point fruit;
GameState state;
} SnakeState;
typedef enum {
EventTypeTick,
EventTypeKey,
} EventType;
typedef struct {
EventType type;
InputEvent input;
} SnakeEvent;
const NotificationSequence sequence_fail = {
&message_vibro_on,
&message_note_ds4,
&message_delay_10,
&message_sound_off,
&message_delay_10,
&message_note_ds4,
&message_delay_10,
&message_sound_off,
&message_delay_10,
&message_note_ds4,
&message_delay_10,
&message_sound_off,
&message_delay_10,
&message_vibro_off,
NULL,
};
const NotificationSequence sequence_eat = {
&message_vibro_on,
&message_note_c7,
&message_delay_50,
&message_sound_off,
&message_vibro_off,
NULL,
};
static void snake_game_render_callback(Canvas* const canvas, void* ctx) {
furi_assert(ctx);
const SnakeState* snake_state = ctx;
furi_mutex_acquire(snake_state->mutex, FuriWaitForever);
// Before the function is called, the state is set with the canvas_reset(canvas)
// Frame
canvas_draw_frame(canvas, 0, 0, 128, 64);
// Fruit
Point f = snake_state->fruit;
f.x = f.x * 4 + 1;
f.y = f.y * 4 + 1;
canvas_draw_rframe(canvas, f.x, f.y, 6, 6, 2);
canvas_draw_dot(canvas, f.x + 3, f.y - 1);
canvas_draw_dot(canvas, f.x + 4, f.y - 2);
//canvas_draw_dot(canvas,f.x+4,f.y-3);
// Snake
for(uint16_t i = 0; i < snake_state->len; i++) {
Point p = snake_state->points[i];
p.x = p.x * 4 + 2;
p.y = p.y * 4 + 2;
canvas_draw_box(canvas, p.x, p.y, 4, 4);
if(i == 0) {
canvas_set_color(canvas, ColorWhite);
canvas_draw_box(canvas, p.x + 1, p.y + 1, 2, 2);
canvas_set_color(canvas, ColorBlack);
}
}
// Pause and GameOver banner
if(snake_state->state == GameStatePause || snake_state->state == GameStateGameOver) {
// Screen is 128x64 px
canvas_set_color(canvas, ColorWhite);
canvas_draw_box(canvas, 33, 19, 64, 26);
canvas_set_color(canvas, ColorBlack);
canvas_draw_frame(canvas, 34, 20, 62, 24);
canvas_set_font(canvas, FontPrimary);
if(snake_state->state == GameStateGameOver) {
canvas_draw_str_aligned(canvas, 65, 31, AlignCenter, AlignBottom, "Game Over");
}
if(snake_state->state == GameStatePause) {
canvas_draw_str_aligned(canvas, 65, 31, AlignCenter, AlignBottom, "Pause");
}
canvas_set_font(canvas, FontSecondary);
char buffer[20];
snprintf(buffer, sizeof(buffer), "Score: %u", snake_state->len - 7U);
canvas_draw_str_aligned(canvas, 65, 41, AlignCenter, AlignBottom, buffer);
// Painting "back"-symbol, Help message for Exit App, ProgressBar
canvas_set_color(canvas, ColorWhite);
canvas_draw_box(canvas, 25, 2, 81, 11);
canvas_draw_box(canvas, 28, 54, 73, 9);
canvas_set_color(canvas, ColorBlack);
canvas_draw_str_aligned(
canvas, 65, 10, AlignCenter, AlignBottom, "Hold to Exit App");
snprintf(
buffer, sizeof(buffer), "Complete: %-5.1f%%", (double)((snake_state->len - 7U) / 4.58));
canvas_draw_str_aligned(canvas, 65, 62, AlignCenter, AlignBottom, buffer);
{
canvas_draw_dot(canvas, x_back_symbol + 0, y_back_symbol);
canvas_draw_dot(canvas, x_back_symbol + 1, y_back_symbol);
canvas_draw_dot(canvas, x_back_symbol + 2, y_back_symbol);
canvas_draw_dot(canvas, x_back_symbol + 3, y_back_symbol);
canvas_draw_dot(canvas, x_back_symbol + 4, y_back_symbol);
canvas_draw_dot(canvas, x_back_symbol + 5, y_back_symbol - 1);
canvas_draw_dot(canvas, x_back_symbol + 6, y_back_symbol - 2);
canvas_draw_dot(canvas, x_back_symbol + 6, y_back_symbol - 3);
canvas_draw_dot(canvas, x_back_symbol + 5, y_back_symbol - 4);
canvas_draw_dot(canvas, x_back_symbol + 4, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol + 3, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol + 2, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol + 1, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol + 0, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol - 1, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol - 2, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol - 3, y_back_symbol - 5);
canvas_draw_dot(canvas, x_back_symbol - 2, y_back_symbol - 6);
canvas_draw_dot(canvas, x_back_symbol - 2, y_back_symbol - 4);
canvas_draw_dot(canvas, x_back_symbol - 1, y_back_symbol - 6);
canvas_draw_dot(canvas, x_back_symbol - 1, y_back_symbol - 4);
canvas_draw_dot(canvas, x_back_symbol - 1, y_back_symbol - 7);
canvas_draw_dot(canvas, x_back_symbol - 1, y_back_symbol - 3);
}
}
furi_mutex_release(snake_state->mutex);
}
static void snake_game_input_callback(InputEvent* input_event, FuriMessageQueue* event_queue) {
furi_assert(event_queue);
SnakeEvent event = {.type = EventTypeKey, .input = *input_event};
furi_message_queue_put(event_queue, &event, FuriWaitForever);
}
static void snake_game_update_timer_callback(FuriMessageQueue* event_queue) {
furi_assert(event_queue);
SnakeEvent event = {.type = EventTypeTick};
furi_message_queue_put(event_queue, &event, 0);
}
static void snake_game_init_game(SnakeState* const snake_state) {
Point p[] = {{8, 6}, {7, 6}, {6, 6}, {5, 6}, {4, 6}, {3, 6}, {2, 6}};
memcpy(snake_state->points, p, sizeof(p)); //-V1086
snake_state->len = 7;
snake_state->currentMovement = DirectionRight;
snake_state->nextMovement = DirectionRight;
Point f = {18, 6};
snake_state->fruit = f;
snake_state->state = GameStateLife;
}
static Point snake_game_get_new_fruit(SnakeState const* const snake_state) {
// 1 bit for each point on the playing field where the snake can turn
// and where the fruit can appear
uint16_t buffer[8];
memset(buffer, 0, sizeof(buffer));
uint8_t empty = 8 * 16;
for(uint16_t i = 0; i < snake_state->len; i++) {
Point p = snake_state->points[i];
if(p.x % 2 != 0 || p.y % 2 != 0) {
continue;
}
p.x /= 2;
p.y /= 2;
buffer[p.y] |= 1 << p.x;
empty--;
}
// Bit set if snake use that playing field
uint16_t newFruit = rand() % empty;
// Skip random number of _empty_ fields
for(uint8_t y = 0; y < 8; y++) {
for(uint16_t x = 0, mask = 1; x < 16; x += 1, mask <<= 1) {
if((buffer[y] & mask) == 0) {
if(newFruit == 0) {
Point p = {
.x = x * 2,
.y = y * 2,
};
return p;
}
newFruit--;
}
}
}
// We will never be here
Point p = {0, 0};
return p;
}
static bool snake_game_collision_with_frame(Point const next_step) {
// if x == 0 && currentMovement == left then x - 1 == 255 ,
// so check only x > right border
return next_step.x > 30 || next_step.y > 14;
}
static bool
snake_game_collision_with_tail(SnakeState const* const snake_state, Point const next_step) {
for(uint16_t i = 0; i < snake_state->len; i++) {
Point p = snake_state->points[i];
if(p.x == next_step.x && p.y == next_step.y) {
return true;
}
}
return false;
}
static Direction snake_game_get_turn_snake(SnakeState const* const snake_state) {
// Sum of two `Direction` lies between 0 and 6, odd values indicate orthogonality.
bool is_orthogonal = (snake_state->currentMovement + snake_state->nextMovement) % 2 == 1;
return is_orthogonal ? snake_state->nextMovement : snake_state->currentMovement;
}
static Point snake_game_get_next_step(SnakeState const* const snake_state) {
Point next_step = snake_state->points[0];
switch(snake_state->currentMovement) {
// +-----x
// |
// |
// y
case DirectionUp:
next_step.y--;
break;
case DirectionRight:
next_step.x++;
break;
case DirectionDown:
next_step.y++;
break;
case DirectionLeft:
next_step.x--;
break;
}
return next_step;
}
static void snake_game_move_snake(SnakeState* const snake_state, Point const next_step) {
memmove(snake_state->points + 1, snake_state->points, snake_state->len * sizeof(Point));
snake_state->points[0] = next_step;
}
static void
snake_game_process_game_step(SnakeState* const snake_state, NotificationApp* notification) {
if(snake_state->state == GameStateGameOver) {
return;
}
snake_state->currentMovement = snake_game_get_turn_snake(snake_state);
Point next_step = snake_game_get_next_step(snake_state);
bool crush = snake_game_collision_with_frame(next_step);
if(crush) {
if(snake_state->state == GameStateLife) {
snake_state->state = GameStateLastChance;
return;
} else if(snake_state->state == GameStateLastChance) {
snake_state->state = GameStateGameOver;
notification_message_block(notification, &sequence_fail);
return;
}
} else {
if(snake_state->state == GameStateLastChance) {
snake_state->state = GameStateLife;
}
}
crush = snake_game_collision_with_tail(snake_state, next_step);
if(crush) {
snake_state->state = GameStateGameOver;
notification_message_block(notification, &sequence_fail);
return;
}
bool eatFruit = (next_step.x == snake_state->fruit.x) && (next_step.y == snake_state->fruit.y);
if(eatFruit) {
snake_state->len++;
if(snake_state->len >= MAX_SNAKE_LEN) {
//You win!!!
snake_state->state = GameStateGameOver;
notification_message_block(notification, &sequence_fail);
return;
}
}
snake_game_move_snake(snake_state, next_step);
if(eatFruit) {
snake_state->fruit = snake_game_get_new_fruit(snake_state);
notification_message(notification, &sequence_eat);
notification_message(notification, &sequence_blink_red_100);
}
}
int32_t snake_20_app(void* p) {
UNUSED(p);
FuriMessageQueue* event_queue = furi_message_queue_alloc(8, sizeof(SnakeEvent));
SnakeState* snake_state = malloc(sizeof(SnakeState));
snake_game_init_game(snake_state);
snake_state->mutex = furi_mutex_alloc(FuriMutexTypeNormal);
if(!snake_state->mutex) {
FURI_LOG_E("SnakeGame", "cannot create mutex\r\n");
furi_message_queue_free(event_queue);
free(snake_state);
return 255;
}
ViewPort* view_port = view_port_alloc();
view_port_draw_callback_set(view_port, snake_game_render_callback, snake_state);
view_port_input_callback_set(view_port, snake_game_input_callback, event_queue);
FuriTimer* timer =
furi_timer_alloc(snake_game_update_timer_callback, FuriTimerTypePeriodic, event_queue);
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 4);
// Open GUI and register view_port
Gui* gui = furi_record_open(RECORD_GUI);
gui_add_view_port(gui, view_port, GuiLayerFullscreen);
NotificationApp* notification = furi_record_open(RECORD_NOTIFICATION);
notification_message_block(notification, &sequence_display_backlight_enforce_on);
dolphin_deed(DolphinDeedPluginGameStart);
SnakeEvent event;
for(bool processing = true; processing;) {
FuriStatus event_status = furi_message_queue_get(event_queue, &event, 100);
furi_mutex_acquire(snake_state->mutex, FuriWaitForever);
if(event_status == FuriStatusOk) {
if(event.type == EventTypeKey) {
// press events
if(event.input.type == InputTypePress) {
switch(event.input.key) {
case InputKeyUp:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionUp;
}
break;
case InputKeyDown:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionDown;
}
break;
case InputKeyRight:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionRight;
}
break;
case InputKeyLeft:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionLeft;
}
break;
case InputKeyOk:
if(snake_state->state == GameStateGameOver) {
snake_game_init_game(snake_state);
}
if(snake_state->state == GameStatePause) {
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 4);
snake_state->state = GameStateLife;
}
break;
case InputKeyBack:
if(snake_state->state == GameStateLife) {
furi_timer_stop(timer);
snake_state->state = GameStatePause;
break;
}
if(snake_state->state == GameStatePause) {
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 4);
snake_state->state = GameStateLife;
break;
}
if(snake_state->state == GameStateGameOver) {
snake_game_init_game(snake_state);
}
default:
break;
}
}
//LongPress Events
if(event.input.type == InputTypeLong) {
switch(event.input.key) {
case InputKeyUp:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionUp;
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 8);
}
break;
case InputKeyDown:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionDown;
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 8);
}
break;
case InputKeyRight:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionRight;
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 8);
}
break;
case InputKeyLeft:
if(snake_state->state != GameStatePause) {
snake_state->nextMovement = DirectionLeft;
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 8);
}
break;
case InputKeyBack:
processing = false;
break;
default:
break;
}
}
//ReleaseKey Event
if(event.input.type == InputTypeRelease) {
if(snake_state->state != GameStatePause) {
furi_timer_start(timer, furi_kernel_get_tick_frequency() / 4);
}
}
} else if(event.type == EventTypeTick) {
snake_game_process_game_step(snake_state, notification);
}
} else {
// event timeout
}
view_port_update(view_port);
furi_mutex_release(snake_state->mutex);
}
// Wait for all notifications to be played and return backlight to normal state
notification_message_block(notification, &sequence_display_backlight_enforce_auto);
furi_timer_free(timer);
view_port_enabled_set(view_port, false);
gui_remove_view_port(gui, view_port);
furi_record_close(RECORD_GUI);
furi_record_close(RECORD_NOTIFICATION);
view_port_free(view_port);
furi_message_queue_free(event_queue);
furi_mutex_free(snake_state->mutex);
free(snake_state);
return 0;
}

View File

@@ -1,11 +0,0 @@
App(
appid="tama_p1",
name="Tamagotchi",
apptype=FlipperAppType.EXTERNAL,
entry_point="tama_p1_app",
cdefines=["APP_TAMA_P1"],
requires=["gui", "storage"],
stack_size=2 * 1024,
fap_icon="tamaIcon.png",
fap_category="Games",
)

View File

@@ -1,66 +0,0 @@
#include <gui/icon_i.h>
const uint8_t _I_icon_0_0[] = {
0x01, 0x00, 0x1a, 0x00, 0x00, 0x0d, 0xaa, 0x1d, 0x7e, 0x00, 0x9c, 0x3e, 0xf9, 0x0f, 0x9e,
0x43, 0xe3, 0x00, 0x12, 0x9c, 0x43, 0xa7, 0x10, 0xc9, 0xe4, 0x30, 0x0a, 0x31, 0x08, 0x60,
};
const uint8_t* const _I_icon_0[] = {_I_icon_0_0};
const uint8_t _I_icon_1_0[] = {
0x00, 0x00, 0x00, 0x40, 0x04, 0x04, 0x04, 0xf0, 0x11, 0xf9, 0x1b, 0xf8, 0x07, 0x8c, 0x06,
0xed, 0x36, 0xac, 0x26, 0xe8, 0x02, 0x52, 0x0b, 0x02, 0x18, 0xe0, 0x01, 0xe0, 0x01,
};
const uint8_t* const _I_icon_1[] = {_I_icon_1_0};
const uint8_t _I_icon_2_0[] = {
0x00, 0x00, 0x00, 0x0e, 0x00, 0x13, 0x00, 0x21, 0x3c, 0x21, 0x3e, 0x23, 0x3f, 0x9f, 0x1f,
0xc0, 0x0f, 0xe0, 0x07, 0xf0, 0x01, 0x7c, 0x00, 0x1f, 0x00, 0x06, 0x00, 0x06, 0x00,
};
const uint8_t* const _I_icon_2[] = {_I_icon_2_0};
const uint8_t _I_icon_3_0[] = {
0x00, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x1c, 0x40, 0x3a, 0xc0, 0x36, 0xf0, 0x37, 0x18, 0x2d,
0x0c, 0x2b, 0x0e, 0x02, 0x1f, 0x06, 0x3e, 0x07, 0xfe, 0x00, 0x7f, 0x00, 0x18, 0x00,
};
const uint8_t* const _I_icon_3[] = {_I_icon_3_0};
const uint8_t _I_icon_4_0[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x7c, 0x00, 0xc7, 0x3c, 0x82, 0x2f, 0xf2, 0x26, 0xc7, 0x2c,
0x69, 0x28, 0x2f, 0x2c, 0xe7, 0x27, 0x02, 0x20, 0x02, 0x30, 0x06, 0x1c, 0xfc, 0x0f,
};
const uint8_t* const _I_icon_4[] = {_I_icon_4_0};
const uint8_t _I_icon_5_0[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x01, 0xfe, 0x0f, 0x03, 0x38, 0xc9, 0x22, 0x9a, 0x32,
0xa2, 0x28, 0x24, 0x2c, 0x21, 0x20, 0x61, 0x30, 0x21, 0x10, 0xf3, 0x11, 0x1e, 0x0f,
};
const uint8_t* const _I_icon_5[] = {_I_icon_5_0};
const uint8_t _I_icon_6_0[] = {
0x01, 0x00, 0x17, 0x00, 0x00, 0x44, 0x62, 0xfd, 0x38, 0xbf, 0xcf, 0xb7, 0xf3, 0xf8,
0xfc, 0x6e, 0x3f, 0x1a, 0xff, 0xc0, 0x3f, 0xf0, 0x1f, 0xf4, 0x02, 0x71, 0x00,
};
const uint8_t* const _I_icon_6[] = {_I_icon_6_0};
const uint8_t _I_icon_7_0[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x00, 0x41, 0x0e, 0xc4, 0x1f, 0x94, 0x20,
0x00, 0x21, 0x22, 0x1f, 0x1d, 0x0a, 0x63, 0x20, 0xde, 0x20, 0x80, 0x1f, 0x00, 0x0e,
};
const uint8_t* const _I_icon_7[] = {_I_icon_7_0};
const Icon I_icon_0 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_0};
const Icon I_icon_1 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_1};
const Icon I_icon_2 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_2};
const Icon I_icon_3 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_3};
const Icon I_icon_4 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_4};
const Icon I_icon_5 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_5};
const Icon I_icon_6 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_6};
const Icon I_icon_7 =
{.width = 14, .height = 14, .frame_count = 1, .frame_rate = 0, .frames = _I_icon_7};

View File

@@ -1,146 +0,0 @@
#include <furi.h>
#include <furi_hal.h>
#include <stdlib.h>
#include <stm32wbxx_ll_tim.h>
#include "tama.h"
#define TAG_HAL "TamaLIB"
static void* tama_p1_hal_malloc(u32_t size) {
return malloc(size);
}
static void tama_p1_hal_free(void* ptr) {
free(ptr);
}
static void tama_p1_hal_halt(void) {
g_ctx->halted = true;
}
static bool_t tama_p1_hal_is_log_enabled(log_level_t level) {
switch(level) {
case LOG_ERROR:
return true;
case LOG_INFO:
return true;
case LOG_MEMORY:
return false;
case LOG_CPU:
return false;
default:
return false;
}
}
static void tama_p1_hal_log(log_level_t level, char* buff, ...) {
if(!tama_p1_hal_is_log_enabled(level)) return;
FuriString* string = furi_string_alloc();
va_list args;
va_start(args, buff);
furi_string_cat_vprintf(string, buff, args);
va_end(args);
switch(level) {
case LOG_ERROR:
FURI_LOG_E(TAG_HAL, "%s", furi_string_get_cstr(string));
break;
case LOG_INFO:
FURI_LOG_I(TAG_HAL, "%s", furi_string_get_cstr(string));
break;
case LOG_MEMORY:
break;
case LOG_CPU:
FURI_LOG_D(TAG_HAL, "%s", furi_string_get_cstr(string));
break;
default:
FURI_LOG_D(TAG_HAL, "%s", furi_string_get_cstr(string));
break;
}
furi_string_free(string);
}
static void tama_p1_hal_sleep_until(timestamp_t ts) {
while(true) {
uint32_t count = LL_TIM_GetCounter(TIM2);
uint32_t delay = ts - count;
// FURI_LOG_D(TAG, "delay: %x", delay);
// Stolen from furi_delay_until_tick
if(delay != 0 && 0 == (delay >> (8 * sizeof(uint32_t) - 1))) {
// Not the best place to release mutex, but this is the only place we know whether
// we're ahead or behind, otherwise around the step call we'll always have to
// delay a tick and run more and more behind.
furi_mutex_release(g_state_mutex);
furi_delay_tick(1);
while(furi_mutex_acquire(g_state_mutex, FuriWaitForever) != FuriStatusOk)
furi_delay_tick(1);
} else {
break;
}
}
}
static timestamp_t tama_p1_hal_get_timestamp(void) {
return LL_TIM_GetCounter(TIM2);
}
static void tama_p1_hal_update_screen(void) {
// Do nothing, covered by main loop
}
static void tama_p1_hal_set_lcd_matrix(u8_t x, u8_t y, bool_t val) {
if(val)
g_ctx->framebuffer[y] |= 1 << x;
else
g_ctx->framebuffer[y] &= ~(1 << x);
}
static void tama_p1_hal_set_lcd_icon(u8_t icon, bool_t val) {
if(val)
g_ctx->icons |= 1 << icon;
else
g_ctx->icons &= ~(1 << icon);
}
static void tama_p1_hal_play_frequency(bool_t en) {
if(en) {
if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(30)) {
furi_hal_speaker_start(g_ctx->frequency, 0.5f);
}
} else {
if(furi_hal_speaker_is_mine()) {
furi_hal_speaker_stop();
furi_hal_speaker_release();
}
}
g_ctx->buzzer_on = en;
}
static void tama_p1_hal_set_frequency(u32_t freq) {
g_ctx->frequency = freq / 10.0F;
if(g_ctx->buzzer_on) tama_p1_hal_play_frequency(true);
}
static int tama_p1_hal_handler(void) {
// Do nothing
return 0;
}
void tama_p1_hal_init(hal_t* hal) {
hal->malloc = tama_p1_hal_malloc;
hal->free = tama_p1_hal_free;
hal->halt = tama_p1_hal_halt;
hal->is_log_enabled = tama_p1_hal_is_log_enabled;
hal->log = tama_p1_hal_log;
hal->sleep_until = tama_p1_hal_sleep_until;
hal->get_timestamp = tama_p1_hal_get_timestamp;
hal->update_screen = tama_p1_hal_update_screen;
hal->set_lcd_matrix = tama_p1_hal_set_lcd_matrix;
hal->set_lcd_icon = tama_p1_hal_set_lcd_icon;
hal->set_frequency = tama_p1_hal_set_frequency;
hal->play_frequency = tama_p1_hal_play_frequency;
hal->handler = tama_p1_hal_handler;
}

View File

@@ -1,35 +0,0 @@
/*
* TamaLIB - A hardware agnostic tama P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _HAL_TYPES_H_
#define _HAL_TYPES_H_
#include <furi.h>
typedef bool bool_t;
typedef uint8_t u4_t;
typedef uint8_t u5_t;
typedef uint8_t u8_t;
typedef uint16_t u12_t;
typedef uint16_t u13_t;
typedef uint32_t u32_t;
typedef uint32_t
timestamp_t; // WARNING: Must be an unsigned type to properly handle wrapping (u32 wraps in around 1h11m when expressed in us)
#endif /* _HAL_TYPES_H_ */

Binary file not shown.

Before

Width:  |  Height:  |  Size: 641 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 658 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 656 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 661 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 664 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 640 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 664 B

View File

@@ -1,42 +0,0 @@
#pragma once
#include <input/input.h>
#include "tamalib/tamalib.h"
#define TAG "TamaP1"
#define TAMA_ROM_PATH APP_DATA_PATH("rom.bin")
#define TAMA_SCREEN_SCALE_FACTOR 2
#define TAMA_LCD_ICON_SIZE 14
#define TAMA_LCD_ICON_MARGIN 1
#define STATE_FILE_MAGIC "TLST"
#define STATE_FILE_VERSION 2
#define TAMA_SAVE_PATH APP_DATA_PATH("save.bin")
typedef struct {
FuriThread* thread;
hal_t hal;
uint8_t* rom;
// 32x16 screen, perfectly represented through uint32_t
uint32_t framebuffer[16];
uint8_t icons;
bool halted;
bool fast_forward_done;
bool buzzer_on;
float frequency;
} TamaApp;
typedef enum {
EventTypeInput,
EventTypeTick,
} EventType;
typedef struct {
EventType type;
InputEvent input;
} TamaEvent;
extern TamaApp* g_ctx;
extern FuriMutex* g_state_mutex;
void tama_p1_hal_init(hal_t* hal);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

File diff suppressed because it is too large Load Diff

View File

@@ -1,339 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

File diff suppressed because it is too large Load Diff

View File

@@ -1,215 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _CPU_H_
#define _CPU_H_
#include "hal.h"
#define MEMORY_SIZE 4096 // 4096 x 4 bits (640 x 4 bits of RAM)
#define MEM_RAM_ADDR 0x000
#define MEM_RAM_SIZE 0x280
#define MEM_DISPLAY1_ADDR 0xE00
#define MEM_DISPLAY1_SIZE 0x050
#define MEM_DISPLAY2_ADDR 0xE80
#define MEM_DISPLAY2_SIZE 0x050
#define MEM_IO_ADDR 0xF00
#define MEM_IO_SIZE 0x080
/* Define this if you want to reduce the footprint of the memory buffer from 4096 u4_t (most likely bytes)
* to 464 u8_t (bytes for sure), while increasing slightly the number of operations needed to read/write from/to it.
*/
#define LOW_FOOTPRINT
#ifdef LOW_FOOTPRINT
/* Invalid memory areas are not buffered to reduce the footprint of the library in memory */
#define MEM_BUFFER_SIZE (MEM_RAM_SIZE + MEM_DISPLAY1_SIZE + MEM_DISPLAY2_SIZE + MEM_IO_SIZE) / 2
/* Maps the CPU memory to the memory buffer */
#define RAM_TO_MEMORY(n) ((n - MEM_RAM_ADDR) / 2)
#define DISP1_TO_MEMORY(n) ((n - MEM_DISPLAY1_ADDR + MEM_RAM_SIZE) / 2)
#define DISP2_TO_MEMORY(n) ((n - MEM_DISPLAY2_ADDR + MEM_RAM_SIZE + MEM_DISPLAY1_SIZE) / 2)
#define IO_TO_MEMORY(n) \
((n - MEM_IO_ADDR + MEM_RAM_SIZE + MEM_DISPLAY1_SIZE + MEM_DISPLAY2_SIZE) / 2)
#define SET_RAM_MEMORY(buffer, n, v) \
{ \
buffer[RAM_TO_MEMORY(n)] = (buffer[RAM_TO_MEMORY(n)] & ~(0xF << (((n) % 2) << 2))) | \
((v)&0xF) << (((n) % 2) << 2); \
}
#define SET_DISP1_MEMORY(buffer, n, v) \
{ \
buffer[DISP1_TO_MEMORY(n)] = (buffer[DISP1_TO_MEMORY(n)] & ~(0xF << (((n) % 2) << 2))) | \
((v)&0xF) << (((n) % 2) << 2); \
}
#define SET_DISP2_MEMORY(buffer, n, v) \
{ \
buffer[DISP2_TO_MEMORY(n)] = (buffer[DISP2_TO_MEMORY(n)] & ~(0xF << (((n) % 2) << 2))) | \
((v)&0xF) << (((n) % 2) << 2); \
}
#define SET_IO_MEMORY(buffer, n, v) \
{ \
buffer[IO_TO_MEMORY(n)] = (buffer[IO_TO_MEMORY(n)] & ~(0xF << (((n) % 2) << 2))) | \
((v)&0xF) << (((n) % 2) << 2); \
}
#define SET_MEMORY(buffer, n, v) \
{ \
if((n) < (MEM_RAM_ADDR + MEM_RAM_SIZE)) { \
SET_RAM_MEMORY(buffer, n, v); \
} else if((n) < MEM_DISPLAY1_ADDR) { \
/* INVALID_MEMORY */ \
} else if((n) < (MEM_DISPLAY1_ADDR + MEM_DISPLAY1_SIZE)) { \
SET_DISP1_MEMORY(buffer, n, v); \
} else if((n) < MEM_DISPLAY2_ADDR) { \
/* INVALID_MEMORY */ \
} else if((n) < (MEM_DISPLAY2_ADDR + MEM_DISPLAY2_SIZE)) { \
SET_DISP2_MEMORY(buffer, n, v); \
} else if((n) < MEM_IO_ADDR) { \
/* INVALID_MEMORY */ \
} else if((n) < (MEM_IO_ADDR + MEM_IO_SIZE)) { \
SET_IO_MEMORY(buffer, n, v); \
} else { \
/* INVALID_MEMORY */ \
} \
}
#define GET_RAM_MEMORY(buffer, n) ((buffer[RAM_TO_MEMORY(n)] >> (((n) % 2) << 2)) & 0xF)
#define GET_DISP1_MEMORY(buffer, n) ((buffer[DISP1_TO_MEMORY(n)] >> (((n) % 2) << 2)) & 0xF)
#define GET_DISP2_MEMORY(buffer, n) ((buffer[DISP2_TO_MEMORY(n)] >> (((n) % 2) << 2)) & 0xF)
#define GET_IO_MEMORY(buffer, n) ((buffer[IO_TO_MEMORY(n)] >> (((n) % 2) << 2)) & 0xF)
#define GET_MEMORY(buffer, n) \
((buffer \
[((n) < (MEM_RAM_ADDR + MEM_RAM_SIZE)) ? RAM_TO_MEMORY(n) : \
((n) < MEM_DISPLAY1_ADDR) ? 0 : \
((n) < (MEM_DISPLAY1_ADDR + MEM_DISPLAY1_SIZE)) ? DISP1_TO_MEMORY(n) : \
((n) < MEM_DISPLAY2_ADDR) ? 0 : \
((n) < (MEM_DISPLAY2_ADDR + MEM_DISPLAY2_SIZE)) ? DISP2_TO_MEMORY(n) : \
((n) < MEM_IO_ADDR) ? 0 : \
((n) < (MEM_IO_ADDR + MEM_IO_SIZE)) ? IO_TO_MEMORY(n) : \
0] >> \
(((n) % 2) << 2)) & \
0xF)
#define MEM_BUFFER_TYPE u8_t
#else
#define MEM_BUFFER_SIZE MEMORY_SIZE
#define SET_MEMORY(buffer, n, v) \
{ buffer[n] = v; }
#define SET_RAM_MEMORY(buffer, n, v) SET_MEMORY(buffer, n, v)
#define SET_DISP1_MEMORY(buffer, n, v) SET_MEMORY(buffer, n, v)
#define SET_DISP2_MEMORY(buffer, n, v) SET_MEMORY(buffer, n, v)
#define SET_IO_MEMORY(buffer, n, v) SET_MEMORY(buffer, n, v)
#define GET_MEMORY(buffer, n) (buffer[n])
#define GET_RAM_MEMORY(buffer, n) GET_MEMORY(buffer, n)
#define GET_DISP1_MEMORY(buffer, n) GET_MEMORY(buffer, n)
#define GET_DISP2_MEMORY(buffer, n) GET_MEMORY(buffer, n)
#define GET_IO_MEMORY(buffer, n) GET_MEMORY(buffer, n)
#define MEM_BUFFER_TYPE u4_t
#endif
typedef struct breakpoint {
u13_t addr;
struct breakpoint* next;
} breakpoint_t;
/* Pins (TODO: add other pins) */
typedef enum {
PIN_K00 = 0x0,
PIN_K01 = 0x1,
PIN_K02 = 0x2,
PIN_K03 = 0x3,
PIN_K10 = 0X4,
PIN_K11 = 0X5,
PIN_K12 = 0X6,
PIN_K13 = 0X7,
} pin_t;
typedef enum {
PIN_STATE_LOW = 0,
PIN_STATE_HIGH = 1,
} pin_state_t;
typedef enum {
INT_PROG_TIMER_SLOT = 0,
INT_SERIAL_SLOT = 1,
INT_K10_K13_SLOT = 2,
INT_K00_K03_SLOT = 3,
INT_STOPWATCH_SLOT = 4,
INT_CLOCK_TIMER_SLOT = 5,
INT_SLOT_NUM,
} int_slot_t;
typedef struct {
u4_t factor_flag_reg;
u4_t mask_reg;
bool_t triggered; /* 1 if triggered, 0 otherwise */
u8_t vector;
} interrupt_t;
typedef struct {
u13_t* pc;
u12_t* x;
u12_t* y;
u4_t* a;
u4_t* b;
u5_t* np;
u8_t* sp;
u4_t* flags;
u32_t* tick_counter;
u32_t* clk_timer_timestamp;
u32_t* prog_timer_timestamp;
bool_t* prog_timer_enabled;
u8_t* prog_timer_data;
u8_t* prog_timer_rld;
u32_t* call_depth;
interrupt_t* interrupts;
MEM_BUFFER_TYPE* memory;
} state_t;
void cpu_add_bp(breakpoint_t** list, u13_t addr);
void cpu_free_bp(breakpoint_t** list);
void cpu_set_speed(u8_t speed);
state_t* cpu_get_state(void);
u32_t cpu_get_depth(void);
void cpu_set_input_pin(pin_t pin, pin_state_t state);
void cpu_sync_ref_timestamp(void);
void cpu_refresh_hw(void);
void cpu_reset(void);
bool_t cpu_init(const u12_t* program, breakpoint_t* breakpoints, u32_t freq);
void cpu_release(void);
int cpu_step(void);
#endif /* _CPU_H_ */

View File

@@ -1,89 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _HAL_H_
#define _HAL_H_
#include "../hal_types.h"
#ifndef NULL
#define NULL 0
#endif
typedef enum {
LOG_ERROR = 0x1,
LOG_INFO = (0x1 << 1),
LOG_MEMORY = (0x1 << 2),
LOG_CPU = (0x1 << 3),
} log_level_t;
/* The Hardware Abstraction Layer
* NOTE: This structure acts as an abstraction layer between TamaLIB and the OS/SDK.
* All pointers MUST be implemented, but some implementations can be left empty.
*/
typedef struct {
/* Memory allocation functions
* NOTE: Needed only if breakpoints support is required.
*/
void* (*malloc)(u32_t size);
void (*free)(void* ptr);
/* What to do if the CPU has halted
*/
void (*halt)(void);
/* Log related function
* NOTE: Needed only if log messages are required.
*/
bool_t (*is_log_enabled)(log_level_t level);
void (*log)(log_level_t level, char* buff, ...);
/* Clock related functions
* NOTE: Timestamps granularity is configured with tamalib_init(), an accuracy
* of ~30 us (1/32768) is required for a cycle accurate emulation.
*/
void (*sleep_until)(timestamp_t ts);
timestamp_t (*get_timestamp)(void);
/* Screen related functions
* NOTE: In case of direct hardware access to pixels, the set_XXXX() functions
* (called for each pixel/icon update) can directly drive them, otherwise they
* should just store the data in a buffer and let update_screen() do the actual
* rendering (at 30 fps).
*/
void (*update_screen)(void);
void (*set_lcd_matrix)(u8_t x, u8_t y, bool_t val);
void (*set_lcd_icon)(u8_t icon, bool_t val);
/* Sound related functions
* NOTE: set_frequency() changes the output frequency of the sound, while
* play_frequency() decides whether the sound should be heard or not.
*/
void (*set_frequency)(u32_t freq);
void (*play_frequency)(bool_t en);
/* Event handler from the main app (if any)
* NOTE: This function usually handles button related events, states loading/saving ...
*/
int (*handler)(void);
} hal_t;
extern hal_t* g_hal;
#endif /* _HAL_H_ */

View File

@@ -1,32 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _HAL_TYPES_H_
#define _HAL_TYPES_H_
typedef unsigned char bool_t;
typedef unsigned char u4_t;
typedef unsigned char u5_t;
typedef unsigned char u8_t;
typedef unsigned short u12_t;
typedef unsigned short u13_t;
typedef unsigned int u32_t;
typedef unsigned int timestamp_t; // WARNING: Must be an unsigned type to properly handle wrapping (u32 wraps in around 1h11m when expressed in us)
#endif /* _HAL_TYPES_H_ */

View File

@@ -1,134 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "hw.h"
#include "cpu.h"
#include "hal.h"
/* SEG -> LCD mapping */
static u8_t seg_pos[40] = {0, 1, 2, 3, 4, 5, 6, 7, 32, 8, 9, 10, 11, 12,
13, 14, 15, 33, 34, 35, 31, 30, 29, 28, 27, 26, 25, 24,
36, 23, 22, 21, 20, 19, 18, 17, 16, 37, 38, 39};
bool_t hw_init(void) {
/* Buttons are active LOW */
cpu_set_input_pin(PIN_K00, PIN_STATE_HIGH);
cpu_set_input_pin(PIN_K01, PIN_STATE_HIGH);
cpu_set_input_pin(PIN_K02, PIN_STATE_HIGH);
return 0;
}
void hw_release(void) {
}
void hw_set_lcd_pin(u8_t seg, u8_t com, u8_t val) {
if(seg_pos[seg] < LCD_WIDTH) {
g_hal->set_lcd_matrix(seg_pos[seg], com, val);
} else {
/*
* IC n -> seg-com|...
* IC 0 -> 8-0 |18-3 |19-2
* IC 1 -> 8-1 |17-0 |19-3
* IC 2 -> 8-2 |17-1 |37-12|38-13|39-14
* IC 3 -> 8-3 |17-2 |18-1 |19-0
* IC 4 -> 28-12|37-13|38-14|39-15
* IC 5 -> 28-13|37-14|38-15
* IC 6 -> 28-14|37-15|39-12
* IC 7 -> 28-15|38-12|39-13
*/
if(seg == 8 && com < 4) {
g_hal->set_lcd_icon(com, val);
} else if(seg == 28 && com >= 12) {
g_hal->set_lcd_icon(com - 8, val);
}
}
}
void hw_set_button(button_t btn, btn_state_t state) {
pin_state_t pin_state = (state == BTN_STATE_PRESSED) ? PIN_STATE_LOW : PIN_STATE_HIGH;
switch(btn) {
case BTN_LEFT:
cpu_set_input_pin(PIN_K02, pin_state);
break;
case BTN_MIDDLE:
cpu_set_input_pin(PIN_K01, pin_state);
break;
case BTN_RIGHT:
cpu_set_input_pin(PIN_K00, pin_state);
break;
}
}
void hw_set_buzzer_freq(u4_t freq) {
u32_t snd_freq = 0;
switch(freq) {
case 0:
/* 4096.0 Hz */
snd_freq = 40960;
break;
case 1:
/* 3276.8 Hz */
snd_freq = 32768;
break;
case 2:
/* 2730.7 Hz */
snd_freq = 27307;
break;
case 3:
/* 2340.6 Hz */
snd_freq = 23406;
break;
case 4:
/* 2048.0 Hz */
snd_freq = 20480;
break;
case 5:
/* 1638.4 Hz */
snd_freq = 16384;
break;
case 6:
/* 1365.3 Hz */
snd_freq = 13653;
break;
case 7:
/* 1170.3 Hz */
snd_freq = 11703;
break;
}
if(snd_freq != 0) {
g_hal->set_frequency(snd_freq);
}
}
void hw_enable_buzzer(bool_t en) {
g_hal->play_frequency(en);
}

View File

@@ -1,50 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _HW_H_
#define _HW_H_
#include "hal.h"
#define LCD_WIDTH 32
#define LCD_HEIGHT 16
#define ICON_NUM 8
typedef enum {
BTN_STATE_RELEASED = 0,
BTN_STATE_PRESSED,
} btn_state_t;
typedef enum {
BTN_LEFT = 0,
BTN_MIDDLE,
BTN_RIGHT,
} button_t;
bool_t hw_init(void);
void hw_release(void);
void hw_set_lcd_pin(u8_t seg, u8_t com, u8_t val);
void hw_set_button(button_t btn, btn_state_t state);
void hw_set_buzzer_freq(u4_t freq);
void hw_enable_buzzer(bool_t en);
#endif /* _HW_H_ */

View File

@@ -1,128 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "tamalib.h"
#include "hw.h"
#include "cpu.h"
#include "hal.h"
#define DEFAULT_FRAMERATE 30 // fps
static exec_mode_t exec_mode = EXEC_MODE_RUN;
static u32_t step_depth = 0;
static timestamp_t screen_ts = 0;
static u32_t ts_freq;
static u8_t g_framerate = DEFAULT_FRAMERATE;
hal_t* g_hal;
bool_t tamalib_init(const u12_t* program, breakpoint_t* breakpoints, u32_t freq) {
bool_t res = 0;
res |= cpu_init(program, breakpoints, freq);
res |= hw_init();
ts_freq = freq;
return res;
}
void tamalib_release(void) {
hw_release();
cpu_release();
}
void tamalib_set_framerate(u8_t framerate) {
g_framerate = framerate;
}
u8_t tamalib_get_framerate(void) {
return g_framerate;
}
void tamalib_register_hal(hal_t* hal) {
g_hal = hal;
}
void tamalib_set_exec_mode(exec_mode_t mode) {
exec_mode = mode;
step_depth = cpu_get_depth();
cpu_sync_ref_timestamp();
}
void tamalib_step(void) {
if(exec_mode == EXEC_MODE_PAUSE) {
return;
}
if(cpu_step()) {
exec_mode = EXEC_MODE_PAUSE;
step_depth = cpu_get_depth();
} else {
switch(exec_mode) {
case EXEC_MODE_PAUSE:
case EXEC_MODE_RUN:
break;
case EXEC_MODE_STEP:
exec_mode = EXEC_MODE_PAUSE;
break;
case EXEC_MODE_NEXT:
if(cpu_get_depth() <= step_depth) {
exec_mode = EXEC_MODE_PAUSE;
step_depth = cpu_get_depth();
}
break;
case EXEC_MODE_TO_CALL:
if(cpu_get_depth() > step_depth) {
exec_mode = EXEC_MODE_PAUSE;
step_depth = cpu_get_depth();
}
break;
case EXEC_MODE_TO_RET:
if(cpu_get_depth() < step_depth) {
exec_mode = EXEC_MODE_PAUSE;
step_depth = cpu_get_depth();
}
break;
}
}
}
void tamalib_mainloop(void) {
timestamp_t ts;
while(!g_hal->handler()) {
tamalib_step();
/* Update the screen @ g_framerate fps */
ts = g_hal->get_timestamp();
if(ts - screen_ts >= ts_freq / g_framerate) {
screen_ts = ts;
g_hal->update_screen();
}
}
}

View File

@@ -1,65 +0,0 @@
/*
* TamaLIB - A hardware agnostic Tamagotchi P1 emulation library
*
* Copyright (C) 2021 Jean-Christophe Rona <jc@rona.fr>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _TAMALIB_H_
#define _TAMALIB_H_
#include "cpu.h"
#include "hw.h"
#include "hal.h"
#define tamalib_set_button(btn, state) hw_set_button(btn, state)
#define tamalib_set_speed(speed) cpu_set_speed(speed)
#define tamalib_get_state() cpu_get_state()
#define tamalib_refresh_hw() cpu_refresh_hw()
#define tamalib_reset() cpu_reset()
#define tamalib_add_bp(list, addr) cpu_add_bp(list, addr)
#define tamalib_free_bp(list) cpu_free_bp(list)
typedef enum {
EXEC_MODE_PAUSE,
EXEC_MODE_RUN,
EXEC_MODE_STEP,
EXEC_MODE_NEXT,
EXEC_MODE_TO_CALL,
EXEC_MODE_TO_RET,
} exec_mode_t;
void tamalib_release(void);
bool_t tamalib_init(const u12_t* program, breakpoint_t* breakpoints, u32_t freq);
void tamalib_set_framerate(u8_t framerate);
u8_t tamalib_get_framerate(void);
void tamalib_register_hal(hal_t* hal);
void tamalib_set_exec_mode(exec_mode_t mode);
/* NOTE: Only one of these two functions must be used in the main application
* (tamalib_step() should be used only if tamalib_mainloop() does not fit the
* main application execution flow).
*/
void tamalib_step(void);
void tamalib_mainloop(void);
#endif /* _TAMALIB_H_ */

View File

@@ -1,20 +0,0 @@
App(
appid="text2sam",
name="Text to SAM",
apptype=FlipperAppType.EXTERNAL,
entry_point="sam_app",
cdefines=["APP_SAM"],
# requires=["gui",],
requires=[
"gui",
"dialogs",
],
stack_size=4 * 1024,
# stack_size=2 * 1024,
fap_icon="icon.png",
fap_category="Media",
fap_author="@Round-Pi & (Fixes by @Willy-JL)",
fap_weburl="https://github.com/Round-Pi/flipperzero-text2sam",
fap_version="1.1",
fap_description="Convert text to speech on your Flipper Zero with SAM (Software Automatic Mouth).",
)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -1,145 +0,0 @@
#include <furi.h>
#include <furi_hal_speaker.h>
#include <stdlib.h>
#include <input/input.h>
#include <dialogs/dialogs.h>
#include <flipper_format/flipper_format.h>
#include <gui/gui.h>
#include <gui/view.h>
#include <gui/view_dispatcher.h>
#include <gui/modules/text_input.h>
#include "stm32_sam.h"
#define TAG "SAM"
#define SAM_SAVE_PATH APP_DATA_PATH("message.txt")
#define TEXT_BUFFER_SIZE 256
STM32SAM voice;
typedef enum {
EventTypeTick,
EventTypeKey,
} EventType;
typedef struct {
EventType type;
InputEvent input;
} PluginEvent;
typedef struct {
ViewDispatcher* view_dispatcher;
TextInput* text_input;
char input[TEXT_BUFFER_SIZE];
} AppState;
AppState* app_state;
static void say_something(char* something) {
if(furi_hal_speaker_is_mine() || furi_hal_speaker_acquire(1000)) {
voice.begin();
voice.say(something);
furi_hal_speaker_release();
}
}
static void text_input_callback(void* ctx) {
AppState* app_state = (AppState*)ctx;
//FURI_LOG_D(TAG, "Input text: %s", app_state->input);
// underscore_to_space(app_state->input);
for(int i = 0; app_state->input[i] != '\0'; i++) {
if(app_state->input[i] == '_') {
app_state->input[i] = ' ';
}
}
say_something(app_state->input);
}
static bool back_event_callback(void* ctx) {
const AppState* app_state = (AppState*)ctx;
view_dispatcher_stop(app_state->view_dispatcher);
return true;
}
static void sam_state_init(AppState* const app_state) {
app_state->view_dispatcher = view_dispatcher_alloc();
app_state->text_input = text_input_alloc();
}
static void sam_state_free(AppState* const app_state) {
text_input_free(app_state->text_input);
view_dispatcher_remove_view(app_state->view_dispatcher, 0);
view_dispatcher_free(app_state->view_dispatcher);
free(app_state);
}
static void save_message(FuriString* save_string) {
Storage* storage = (Storage*)furi_record_open(RECORD_STORAGE);
File* file = storage_file_alloc(storage);
if(storage_file_open(file, SAM_SAVE_PATH, FSAM_WRITE, FSOM_CREATE_ALWAYS)) {
storage_file_write(file, save_string, TEXT_BUFFER_SIZE);
}
storage_file_close(file);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
}
static bool load_messages() {
Storage* storage = (Storage*)furi_record_open(RECORD_STORAGE);
storage_common_migrate(storage, EXT_PATH("sam.txt"), SAM_SAVE_PATH);
File* file = storage_file_alloc(storage);
uint16_t bytes_read = 0;
if(storage_file_open(file, SAM_SAVE_PATH, FSAM_READ, FSOM_OPEN_EXISTING)) {
bytes_read = storage_file_read(file, app_state->input, TEXT_BUFFER_SIZE);
}
storage_file_close(file);
storage_file_free(file);
furi_record_close(RECORD_STORAGE);
return bytes_read == TEXT_BUFFER_SIZE;
}
extern "C" int32_t sam_app(void* p) {
UNUSED(p);
app_state = (AppState*)malloc(sizeof(AppState));
FURI_LOG_D(TAG, "Running sam_state_init");
sam_state_init(app_state);
FURI_LOG_D(TAG, "Assigning text input callback");
load_messages();
text_input_set_result_callback(
app_state->text_input,
text_input_callback,
app_state,
app_state->input,
TEXT_BUFFER_SIZE,
false); //clear default text
text_input_set_header_text(app_state->text_input, "Input");
Gui* gui = (Gui*)furi_record_open(RECORD_GUI);
view_dispatcher_enable_queue(app_state->view_dispatcher);
FURI_LOG_D(TAG, "Adding text input view to dispatcher");
view_dispatcher_add_view(
app_state->view_dispatcher, 0, text_input_get_view(app_state->text_input));
FURI_LOG_D(TAG, "Attaching view dispatcher to GUI");
view_dispatcher_attach_to_gui(app_state->view_dispatcher, gui, ViewDispatcherTypeFullscreen);
FURI_LOG_D(TAG, "starting view dispatcher");
view_dispatcher_set_navigation_event_callback(app_state->view_dispatcher, back_event_callback);
view_dispatcher_set_event_callback_context(app_state->view_dispatcher, app_state);
view_dispatcher_switch_to_view(app_state->view_dispatcher, 0);
view_dispatcher_run(app_state->view_dispatcher);
save_message((FuriString*)app_state->input);
furi_record_close(RECORD_GUI);
sam_state_free(app_state);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More