repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_playing_game
static void rps_render_playing_game(Canvas* canvas, void* ctx) { furi_assert(ctx); GameContext* game_context = ctx; // Attempt to aquire context, so we can read the data. if(furi_mutex_acquire(game_context->mutex, 200) != FuriStatusOk) { return; } GameData* data = game_context->data; GameState local_player = data->local_player; GameState remote_player = data->remote_player; canvas_set_font(canvas, FontSecondary); switch(remote_player) { case StateReady: canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteReady]); break; case StateCount1: canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteCount]); canvas_draw_str_aligned(canvas, 70, 15, AlignLeft, AlignTop, "1"); break; case StateCount2: canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteCount]); canvas_draw_str_aligned(canvas, 70, 15, AlignLeft, AlignTop, "2"); break; case StateRock: case StateTieRock: case StateWonRock: case StateLostRock: if(StateCount2 != local_player) { canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteRock]); canvas_draw_str_aligned(canvas, 70, 55, AlignLeft, AlignTop, "Rock"); } else { canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteCount]); } break; case StatePaper: case StateTiePaper: case StateWonPaper: case StateLostPaper: if(StateCount2 != local_player) { canvas_draw_icon(canvas, 64, 0, images[DolphinRemotePaper]); canvas_draw_str_aligned(canvas, 70, 55, AlignLeft, AlignTop, "Paper"); } else { canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteCount]); } break; case StateScissors: case StateTieScissors: case StateWonScissors: case StateLostScissors: if(StateCount2 != local_player) { canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteScissors]); canvas_draw_str_aligned(canvas, 70, 55, AlignLeft, AlignTop, "Scissors"); } else { canvas_draw_icon(canvas, 64, 0, images[DolphinRemoteCount]); } break; default: break; } switch(local_player) { case StateReady: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalReady]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Press OK for 1."); break; case StateCount1: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalCount]); canvas_draw_str_aligned(canvas, 50, 15, AlignLeft, AlignTop, "1"); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Press OK for 2."); break; case StateCount2: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalCount]); canvas_draw_str_aligned(canvas, 50, 15, AlignLeft, AlignTop, "2"); canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "^Rock >Paper vScissor"); break; case StateRock: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalRock]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Rock"); break; case StatePaper: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalPaper]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Paper"); break; case StateScissors: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalScissors]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Scissors"); break; case StateWonRock: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalRock]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Rock"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You won!!!"); break; case StateWonPaper: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalPaper]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Paper"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You won!!!"); break; case StateWonScissors: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalScissors]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Scissors"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You won!!!"); break; case StateTieRock: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalRock]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Rock"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You tied!"); break; case StateTiePaper: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalPaper]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Paper"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You tied!"); break; case StateTieScissors: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalScissors]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Scissors"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You tied!"); break; case StateLostRock: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalRock]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Rock"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You lost."); break; case StateLostPaper: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalPaper]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Paper"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You lost."); break; case StateLostScissors: canvas_draw_icon(canvas, 0, 0, images[DolphinLocalScissors]); canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Scissors"); canvas_draw_str_aligned(canvas, 38, 5, AlignLeft, AlignTop, "You lost."); break; default: canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Unexpected. 2"); break; } furi_mutex_release(game_context->mutex); }
// Render UI when we are playing the game. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L508-L666
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_error
static void rps_render_error(Canvas* canvas, void* ctx) { furi_assert(ctx); GameContext* game_context = ctx; // Attempt to aquire context, so we can read the data. if(furi_mutex_acquire(game_context->mutex, 200) != FuriStatusOk) { return; } GameData* data = game_context->data; GameState local_player = data->local_player; canvas_set_font(canvas, FontPrimary); switch(local_player) { case StateErrorRemoteTimeout: canvas_draw_str_aligned(canvas, 15, 5, AlignLeft, AlignTop, "Remote timeout."); canvas_set_font(canvas, FontSecondary); canvas_draw_str_aligned(canvas, 5, 20, AlignLeft, AlignTop, "It appears the remote"); canvas_draw_str_aligned(canvas, 5, 30, AlignLeft, AlignTop, "user has left the game?"); break; default: canvas_draw_str_aligned(canvas, 5, 55, AlignLeft, AlignTop, "Unexpected. 3"); break; } furi_mutex_release(game_context->mutex); }
// Render UI when we encounter an error in the game. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L671-L700
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_main_menu
static void rps_render_main_menu(Canvas* canvas, void* ctx) { GameContext* game_context = ctx; canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 2, 0, AlignLeft, AlignTop, "ROCK PAPER SCISSORS"); canvas_draw_str_aligned(canvas, 30, 15, AlignLeft, AlignTop, "Edit contact info"); canvas_draw_str_aligned(canvas, 30, 27, AlignLeft, AlignTop, "Host game"); canvas_draw_str_aligned(canvas, 30, 39, AlignLeft, AlignTop, "Join game"); canvas_draw_str_aligned(canvas, 30, 51, AlignLeft, AlignTop, "Past games"); if(game_context->data->local_player == StateMainMenuMessage) { canvas_draw_str_aligned(canvas, 20, 15, AlignLeft, AlignTop, ">"); } else if(game_context->data->local_player == StateMainMenuHost) { canvas_draw_str_aligned(canvas, 20, 27, AlignLeft, AlignTop, ">"); } else if(game_context->data->local_player == StateMainMenuJoin) { canvas_draw_str_aligned(canvas, 20, 39, AlignLeft, AlignTop, ">"); } else if(game_context->data->local_player == StateMainMenuPastGames) { canvas_draw_str_aligned(canvas, 20, 51, AlignLeft, AlignTop, ">"); } }
// Render UI when we are hosting the game. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L705-L724
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_past_games
static void rps_render_past_games(Canvas* canvas, void* ctx) { GameContext* game_context = ctx; canvas_set_font(canvas, FontPrimary); PlayerStats* stats = game_context->data->viewing_player_stats; if(!stats) { canvas_draw_str_aligned(canvas, 10, 30, AlignLeft, AlignTop, "NO GAMES PLAYED."); } else { canvas_draw_str_aligned( canvas, 0, 0, AlignLeft, AlignTop, furi_string_get_cstr(stats->last_played)); furi_string_printf( game_context->data->buffer, "Win:%d Lost:%d Tied:%d", stats->win_count, stats->loss_count, stats->tie_count); canvas_draw_str_aligned( canvas, 0, 12, AlignLeft, AlignTop, furi_string_get_cstr(game_context->data->buffer)); canvas_draw_str_aligned( canvas, 0, 24, AlignLeft, AlignTop, furi_string_get_cstr(stats->flipper_name)); canvas_set_font(canvas, FontSecondary); char ch = furi_string_get_char(stats->contact, 0); for(unsigned int i = 0; i < sizeof(contact_list) / sizeof(contact_list[0]); i++) { if(contact_list[i][0] == ch) { canvas_draw_str_aligned(canvas, 0, 36, AlignLeft, AlignTop, contact_list[i] + 1); ch = 0; break; } } if(ch) { char id[2] = {ch, 0}; canvas_draw_str_aligned(canvas, 0, 36, AlignLeft, AlignTop, id); } canvas_draw_str_aligned( canvas, 0, 48, AlignLeft, AlignTop, furi_string_get_cstr(stats->contact) + 1); } }
// Render UI when we are showing previous games. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L729-L770
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_choose_social
static void rps_render_choose_social(Canvas* canvas, void* ctx) { GameContext* game_context = ctx; UNUSED(game_context); int line = game_context->data->social_line; int index = line - 2; if(index < 0) { index = 0; } canvas_clear(canvas); canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 2, 0, AlignLeft, AlignTop, "Share your..."); canvas_set_font(canvas, FontSecondary); canvas_draw_str_aligned(canvas, 15, 15, AlignLeft, AlignTop, contact_list[index++] + 1); canvas_draw_str_aligned(canvas, 15, 27, AlignLeft, AlignTop, contact_list[index++] + 1); canvas_draw_str_aligned(canvas, 15, 39, AlignLeft, AlignTop, contact_list[index++] + 1); if(index < (int)COUNT_OF(contact_list)) { canvas_draw_str_aligned(canvas, 15, 51, AlignLeft, AlignTop, contact_list[index++] + 1); } if(line == 0) { canvas_draw_str_aligned(canvas, 5, 15, AlignLeft, AlignTop, ">"); } else if(line == 1) { canvas_draw_str_aligned(canvas, 5, 27, AlignLeft, AlignTop, ">"); } else { canvas_draw_str_aligned(canvas, 5, 39, AlignLeft, AlignTop, ">"); } }
// Render UI when we are choosing a social identity to share. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L775-L804
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
get_char
static char get_char(GameContext* game_context, bool long_press) { int c_r = game_context->data->keyboard_row; int c_c = game_context->data->keyboard_col; char ch = keyboard[c_r][c_c]; if(!long_press && ch >= 'A' && ch <= 'Z') { ch += 32; } return ch; }
// Return the character at the current keyboard cursor position. // @param game_context pointer to a GameContext. // @param long_press true if the key was held down for a long time.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L809-L819
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
draw_arrow
static void draw_arrow(Canvas* canvas, int x, int y, bool tail) { canvas_draw_line(canvas, x, y + 2, x + 4, y + 2); canvas_draw_line(canvas, x, y + 2, x + 2, y); canvas_draw_line(canvas, x, y + 2, x + 2, y + 4); if(tail) { canvas_draw_line(canvas, x + 4, y + 2, x + 4, y); } }
// Render an arrow, for enter and backspace. // @param canvas rendering surface of the Flipper Zero. // @param x x coordinate of the arrow. // @param y y coordinate of the arrow. // @param tail true for enter, false for backspace.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L826-L833
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_input_text
static void rps_render_input_text(Canvas* canvas, void* ctx) { GameContext* game_context = ctx; UNUSED(game_context); canvas_clear(canvas); canvas_set_font(canvas, FontKeyboard); canvas_set_color(canvas, ColorBlack); canvas_draw_str(canvas, 0, 8, furi_string_get_cstr(game_context->data->keyboard_heading)); canvas_draw_rframe(canvas, 0, 10, 127, 14, 1); int input_offset = furi_string_utf8_length(game_context->data->keyboard_data) - 20; if(input_offset < 0) { input_offset = 0; } canvas_draw_str( canvas, 2, 20, furi_string_get_cstr(game_context->data->keyboard_data) + input_offset); int c_r = game_context->data->keyboard_row; int c_c = game_context->data->keyboard_col; for(int row = 0; row < 4; row++) { for(int col = 0; col < 14; col++) { char ch = keyboard[row][col]; int x = col * 9 + 2; int y = row * 10 + 33; if(row == c_r && col == c_c) { canvas_draw_box(canvas, x - 1, y - 8, 7, 9); canvas_set_color(canvas, ColorWhite); } canvas_draw_glyph(canvas, x, y, ch); if(ch == KEYBOARD_BACKSPACE) { draw_arrow(canvas, x, y - 5, false); } else if(ch == KEYBOARD_ENTER) { draw_arrow(canvas, x, y - 5, true); } canvas_set_color(canvas, ColorBlack); } } }
// Render UI when we are inputting text. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L838-L879
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_render_callback
static void rps_render_callback(Canvas* canvas, void* ctx) { furi_assert(ctx); GameContext* game_context = ctx; if(game_context->data->screen_state == ScreenHostGame) { rps_render_host_game(canvas, game_context); } else if(game_context->data->screen_state == ScreenError) { rps_render_error(canvas, game_context); } else if(game_context->data->screen_state == ScreenPlayingGame) { rps_render_playing_game(canvas, game_context); } else if(game_context->data->screen_state == ScreenJoinGame) { rps_render_join_game(canvas, game_context); } else if(game_context->data->screen_state == ScreenMainMenu) { rps_render_main_menu(canvas, game_context); } else if(game_context->data->screen_state == ScreenPastGames) { rps_render_past_games(canvas, game_context); } else if(game_context->data->screen_state == ScreenEditMessage) { rps_render_input_text(canvas, game_context); } else if(game_context->data->screen_state == ScreenChooseSocial) { rps_render_choose_social(canvas, game_context); } else if(game_context->data->screen_state == ScreenFinishedGame) { rps_render_game_result(canvas, game_context); } }
// We register this callback to get invoked whenever we need to render the screen. // We render the UI on this callback thread. // @param canvas rendering surface of the Flipper Zero. // @param ctx pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L942-L965
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_broadcast
static void rps_broadcast(GameContext* game_context, FuriString* buffer) { uint8_t* message = (uint8_t*)furi_string_get_cstr(buffer); FURI_LOG_I(TAG, "Broadcast message >%s<", message); // Make sure our message will fit into a packet; if not truncate it. size_t length = strlen((char*)message); if(length > MESSAGE_MAX_LEN) { // SECURITY REVIEW - Is it okay to log, or do we need to truncate first? FURI_LOG_E( TAG, "Outgoing message bigger than %d bytes! >%s<", MESSAGE_MAX_LEN, (char*)message); // Add \r\n(null) to the end of the 0-indexed string. message[MESSAGE_MAX_LEN - 1] = 0; message[MESSAGE_MAX_LEN - 2] = '\n'; message[MESSAGE_MAX_LEN - 3] = '\r'; length = MESSAGE_MAX_LEN; } while(!subghz_tx_rx_worker_write(game_context->subghz_txrx, message, length)) { // Wait a few milliseconds on failure before trying to send again. furi_delay_ms(20); } // Try to handle the case that *sometimes* a signal might not get through. for(int i = 0; i < 3; i++) { if(game_context->data->echo_duration > 0 && game_context->data->echo_duration < 50) { furi_delay_ms(game_context->data->echo_duration + i * 5); FURI_LOG_I(TAG, "Echoing message"); while(!subghz_tx_rx_worker_write(game_context->subghz_txrx, message, length)) { // Wait a few milliseconds on failure before trying to send again. furi_delay_ms(7); } } } }
// This is a helper method that broadcasts a buffer. // If the message is too large, the message will get truncated. // @param game_context pointer to a GameContext. // @param buffer string to broadcast.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L971-L1005
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_broadcast_move
static void rps_broadcast_move(GameContext* game_context, Move moveToSend) { GameData* data = game_context->data; FURI_LOG_I(TAG, "Sending move %c", moveToSend); // The message for game 42 with a move with value Rock should look like... "YourFlip: RPS:MA042R\r\n" furi_string_printf( data->buffer, "%s: %s:%c%c%03u%c\r\n", furi_hal_version_get_name_ptr(), RPS_GAME_NAME, GameRfPurposeMove, MAJOR_VERSION, data->game_number, moveToSend); rps_broadcast(game_context, data->buffer); }
// Our GameEventSendCounter handler invokes this method. // We broadcast - "YourFlip: " + "RPS:" + move"M" + version"A" + game"###" + move"R" + "\r\n" // @param game_context pointer to a GameContext. // @param moveToSend the move to send to the remote player.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1011-L1026
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_broadcast_beacon
static void rps_broadcast_beacon(GameContext* game_context) { GameData* data = game_context->data; FURI_LOG_I(TAG, "Sending beacon"); // The message for game 42 should look like... "YourFlip: RPS:BA042\r\n" furi_string_printf( data->buffer, "%s: %s:%c%c%03u\r\n", furi_hal_version_get_name_ptr(), RPS_GAME_NAME, GameRfPurposeBeacon, MAJOR_VERSION, data->game_number); rps_broadcast(game_context, data->buffer); }
// Our GameEventTypeTimer handler invokes this method. // We broadcast - "YourFlip: " + "RPS:" + beacon"B" + version"A" + game"###" + "\r\n" // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1031-L1045
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_broadcast_not_beacon
static void rps_broadcast_not_beacon(GameContext* game_context) { GameData* data = game_context->data; FURI_LOG_I(TAG, "Sending not beacon"); // The message for game 42 should look like... "YourFlip: RPS:NA042\r\n" furi_string_printf( data->buffer, "%s: %s:%c%c%03u\r\n", furi_hal_version_get_name_ptr(), RPS_GAME_NAME, GameRfPurposeNotBeacon, MAJOR_VERSION, data->game_number); rps_broadcast(game_context, data->buffer); }
// Our GameEventTypeTimer handler invokes this method. // We broadcast - "YourFlip: " + "RPS:" + notbeacon"N" + version"A" + game"###" + "\r\n" // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1050-L1064
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_broadcast_join
static void rps_broadcast_join(GameContext* game_context) { GameData* data = game_context->data; data->echo_duration = 42; unsigned int gameNumber = data->game_number; FURI_LOG_I(TAG, "Joining game %d.", gameNumber); // The message for game 42 should look like... "YourFlip: RPS:JA042NYourNameHere\r\n" furi_string_printf( data->buffer, "%s: %s:%c%c%03u%s\r\n", furi_hal_version_get_name_ptr(), RPS_GAME_NAME, GameRfPurposeJoin, MAJOR_VERSION, data->game_number, furi_string_get_cstr(data->local_contact)); rps_broadcast(game_context, data->buffer); }
// Send message that indicates Flipper is joining a specific game. // We broadcast - "YourFlip: " + "RPS:" + join"J" + version"A" + game"###" + "NYourNameHere" + "\r\n" // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1101-L1118
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_broadcast_join_acknowledge
static void rps_broadcast_join_acknowledge(GameContext* game_context) { GameData* data = game_context->data; data->echo_duration = 12; unsigned int gameNumber = data->game_number; FURI_LOG_I(TAG, "Acknowledge joining game %d.", gameNumber); // The message for game 42 should look like... "YourFlip: RPS:AA042NYourNameHere\r\n" furi_string_printf( data->buffer, "%s: %s:%c%c%03u%s\r\n", furi_hal_version_get_name_ptr(), RPS_GAME_NAME, GameRfPurposeJoinAcknowledge, MAJOR_VERSION, data->game_number, furi_string_get_cstr(data->local_contact)); rps_broadcast(game_context, data->buffer); }
// Send message that acknowledges Flipper joining a specific game. // We broadcast - "YourFlip: " + "RPS:" + joinAck"A" + version"A" + game"###" + "NYourNameHere" + "\r\n" // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1123-L1140
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
duration
static uint32_t duration(uint32_t tick) { uint32_t current = furi_get_tick(); // Every 55 days the tick could wrap. if(current < tick) { FURI_LOG_T(TAG, "tick count wrapped! current:%ld prev:%ld", current, tick); return current + (UINT32_MAX - tick); } return current - tick; }
// Calculates the elapsed duration (in ticks) since a previous tick. // @param tick previous tick obtained from furi_get_tick().
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1144-L1153
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_state_machine_update
static void rps_state_machine_update(GameContext* game_context) { GameData* d = game_context->data; if((d->screen_state != ScreenPlayingGame) && (d->screen_state != ScreenError)) { FURI_LOG_T(TAG, "Not in playing game state. screenState:%d", d->screen_state); return; } FURI_LOG_I( TAG, "Validating game state. local:%c Remote:%c", d->local_player, d->remote_player); // Did player leave after joining? if((StateReady == d->remote_player) && (duration(d->remote_move_tick) > DURATION_NO_MOVE_DETECTED_ERROR)) { d->remote_player = StateUnknown; d->remote_move_tick = furi_get_tick(); d->local_player = StateErrorRemoteTimeout; d->local_move_tick = furi_get_tick(); d->screen_state = ScreenError; // Should we tell other player we timed out? FURI_LOG_I(TAG, "Timed out after joining."); return; } // Check for winner. if(isFinalMove(d->local_player) && isFinalMove(d->remote_player) && (duration(d->local_move_tick) > DURATION_SHOW_MOVES)) { d->local_move_tick = furi_get_tick(); d->remote_move_tick = furi_get_tick(); if((d->local_player == StateRock) && (d->remote_player == StateScissors)) { d->local_player = StateWonRock; d->remote_player = StateLostScissors; FURI_LOG_I(TAG, "Local won w/Rock."); } else if((d->local_player == StateScissors) && (d->remote_player == StatePaper)) { d->local_player = StateWonScissors; d->remote_player = StateLostPaper; FURI_LOG_I(TAG, "Local won w/Scissors."); } else if((d->local_player == StatePaper) && (d->remote_player == StateRock)) { d->local_player = StateWonPaper; d->remote_player = StateLostRock; FURI_LOG_I(TAG, "Local won w/Paper."); } else if((d->local_player == StateRock) && (d->remote_player == StatePaper)) { d->local_player = StateLostRock; d->remote_player = StateWonPaper; FURI_LOG_I(TAG, "Remote won w/Paper."); } else if((d->local_player == StateScissors) && (d->remote_player == StateRock)) { d->local_player = StateLostScissors; d->remote_player = StateWonRock; FURI_LOG_I(TAG, "Remote won w/Rock."); } else if((d->local_player == StatePaper) && (d->remote_player == StateScissors)) { d->local_player = StateLostPaper; d->remote_player = StateWonScissors; FURI_LOG_I(TAG, "Remote won w/Scissors."); } else { FURI_LOG_I(TAG, "Tie game."); if(d->local_player == StateRock) { d->local_player = StateTieRock; d->remote_player = StateTieRock; } else if(d->local_player == StatePaper) { d->local_player = StateTiePaper; d->remote_player = StateTiePaper; } else { d->local_player = StateTieScissors; d->remote_player = StateTieScissors; } } GameEvent event = {.type = GameEventPlaySong}; furi_message_queue_put(game_context->queue, &event, FuriWaitForever); } }
// Updates the state machine, if needed. // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1157-L1227
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_state_machine_remote_joined
static bool rps_state_machine_remote_joined(GameContext* game_context) { if(StateHostingLookingForPlayer == game_context->data->local_player) { FURI_LOG_I(TAG, "Remote player joined our game!"); game_context->data->remote_player = StateReady; game_context->data->remote_move_tick = furi_get_tick(); game_context->data->local_player = StateReady; game_context->data->local_move_tick = furi_get_tick(); game_context->data->screen_state = ScreenPlayingGame; return true; } else { FURI_LOG_I( TAG, "Remote requested join, but we are state %c!", game_context->data->local_player); return false; } }
// Update the state machine to reflect that a remote user joined the game. // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1231-L1245
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_state_machine_local_moved
static bool rps_state_machine_local_moved(GameContext* game_context, Move move) { FURI_LOG_I(TAG, "Local move %c.", move); Move localMove = MoveUnknown; GameState localState = StateReady; if(MoveCount == move && StateReady == game_context->data->local_player) { localMove = MoveCount1; localState = StateCount1; } else if(MoveCount == move && StateCount1 == game_context->data->local_player) { localMove = MoveCount2; localState = StateCount2; } else if(StateCount2 == game_context->data->local_player) { if(MoveRock == move) { localMove = MoveRock; localState = StateRock; } else if(MovePaper == move) { localMove = MovePaper; localState = StatePaper; } else if(MoveScissors == move) { localMove = MoveScissors; localState = StateScissors; } else if(MoveCount == move) { // Ignore. We are already at count #2. } else { FURI_LOG_E( TAG, "Invalid Local move '%c' error. lState=%c. rState=%c.", move, game_context->data->local_player, game_context->data->remote_player); } } else { FURI_LOG_E( TAG, "Invalid Local move '%c' error. lState=%c. rState=%c.", move, game_context->data->local_player, game_context->data->remote_player); } if(MoveUnknown != localMove) { single_vibro(); rps_broadcast_move(game_context, localMove); } if(StateReady != localState) { game_context->data->local_player = localState; game_context->data->local_move_tick = furi_get_tick(); } return StateReady != localState; }
// Update the state machine to reflect the local user's move. // @param game_context pointer to a GameContext. // @param move local user move.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1250-L1302
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rps_state_machine_remote_moved
static bool rps_state_machine_remote_moved(GameContext* game_context, Move move) { GameState remoteState = StateReady; FURI_LOG_I(TAG, "Remote move %c.", move); if(MoveCount1 == move && StateReady == game_context->data->remote_player) { remoteState = StateCount1; } else if(MoveCount2 == move && StateCount1 == game_context->data->remote_player) { remoteState = StateCount2; } else if(MoveRock == move && StateCount2 == game_context->data->remote_player) { remoteState = StateRock; } else if(MovePaper == move && StateCount2 == game_context->data->remote_player) { remoteState = StatePaper; } else if(MoveScissors == move && StateCount2 == game_context->data->remote_player) { remoteState = StateScissors; } else { FURI_LOG_E( TAG, "Remote move '%c' error. lState=%c. rState=%c.", move, game_context->data->local_player, game_context->data->remote_player); } if(StateReady != remoteState) { game_context->data->remote_player = remoteState; game_context->data->remote_move_tick = furi_get_tick(); } return StateReady != remoteState; }
// Update the state machine to reflect the remote user's move. // @param game_context pointer to a GameContext. // @param move remote user move.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1307-L1336
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
ensure_dir_exists
static void ensure_dir_exists(Storage* storage) { // If apps_data directory doesn't exist, create it. if(!storage_dir_exists(storage, RPS_APPS_DATA_FOLDER)) { FURI_LOG_I(TAG, "Creating directory: %s", RPS_APPS_DATA_FOLDER); storage_simply_mkdir(storage, RPS_APPS_DATA_FOLDER); } else { FURI_LOG_I(TAG, "Directory exists: %s", RPS_APPS_DATA_FOLDER); } // If rock_paper_scissors directory doesn't exist, create it. if(!storage_dir_exists(storage, RPS_GAME_FOLDER)) { FURI_LOG_I(TAG, "Creating directory: %s", RPS_GAME_FOLDER); storage_simply_mkdir(storage, RPS_GAME_FOLDER); } else { FURI_LOG_I(TAG, "Directory exists: %s", RPS_GAME_FOLDER); } }
// This is a helper method that creates the game directory if it does not exist. // @param storage pointer to a Storage.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1530-L1546
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
save_local_contact
static void save_local_contact(GameContext* game_context) { if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) != FuriStatusOk) { return; } Storage* storage = furi_record_open(RECORD_STORAGE); ensure_dir_exists(storage); FURI_LOG_I(TAG, "Saving social: %s", furi_string_get_cstr(game_context->data->local_contact)); File* social_file = storage_file_alloc(storage); if(storage_file_open(social_file, RPS_SOCIAL_PATH, FSAM_WRITE, FSOM_OPEN_ALWAYS)) { FURI_LOG_T(TAG, "Opened file: %s", RPS_SOCIAL_PATH); int offset = (KEYBOARD_MAX_LEN + 2) * furi_string_get_char(game_context->data->local_contact, 0); if(offset < 0) { offset = 0; } int file_size = storage_file_size(social_file); if(file_size < offset) { storage_file_seek(social_file, file_size, true); for(int i = file_size; i < offset; i++) { storage_file_write(social_file, "\0", 1); } } storage_file_seek(social_file, offset, true); if(!storage_file_write( social_file, furi_string_get_cstr(game_context->data->local_contact), furi_string_size(game_context->data->local_contact))) { FURI_LOG_E(TAG, "Failed to write to file."); } storage_file_write(social_file, "\n", 1); storage_file_seek(social_file, 0, true); storage_file_write( social_file, furi_string_get_cstr(game_context->data->local_contact), furi_string_size(game_context->data->local_contact)); storage_file_write(social_file, "\n", 1); } else { FURI_LOG_E(TAG, "Failed to open file: %s", RPS_SOCIAL_PATH); } storage_file_close(social_file); storage_file_free(social_file); furi_record_close(RECORD_STORAGE); furi_mutex_release(game_context->mutex); }
// Saves a local contact to the file system. // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1550-L1600
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
load_social_data
static void load_social_data(int index, bool skip_first_char, FuriString* buffer) { Storage* storage = furi_record_open(RECORD_STORAGE); File* social_file = storage_file_alloc(storage); if(storage_file_open(social_file, RPS_SOCIAL_PATH, FSAM_READ, FSOM_OPEN_EXISTING)) { char ch; FURI_LOG_T(TAG, "Opened file: %s", RPS_SOCIAL_PATH); int offset = (KEYBOARD_MAX_LEN + 2) * index; if(skip_first_char) { offset++; // Skip first character when filling keyboard buffer. } int file_size = storage_file_size(social_file); if(file_size > offset) { storage_file_seek(social_file, offset, true); furi_string_reset(buffer); while(storage_file_read(social_file, &ch, 1) && !storage_file_eof(social_file)) { if(ch == '\n' || ch == '\0') { break; } furi_string_push_back(buffer, ch); } } } else { FURI_LOG_E(TAG, "Failed to open file: %s", RPS_SOCIAL_PATH); } storage_file_close(social_file); storage_file_free(social_file); furi_record_close(RECORD_STORAGE); }
// Loads a local contact from the file system. // @param index index of the contact to load. // @param skip_first_char true if the first character should be skipped. // @param buffer pointer to a FuriString.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1606-L1637
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
load_keyboard_data
static void load_keyboard_data(GameContext* game_context) { load_social_data( contact_list[game_context->data->social_line][0], true, game_context->data->keyboard_data); }
// Fills the keyboard data array with the previously saved social information. // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1641-L1644
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
load_local_contact
static void load_local_contact(GameContext* game_context) { load_social_data(0, false, game_context->data->local_contact); if(furi_string_size(game_context->data->local_contact) > 0) { char ch = furi_string_get_char(game_context->data->local_contact, 0); for(int i = 0; i < (int)COUNT_OF(contact_list); i++) { if(contact_list[i][0] == ch) { game_context->data->social_line = i; break; } } } }
// Loads the initial local contact from the file system. // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1648-L1659
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
save_result
static void save_result(GameContext* game_context) { if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) != FuriStatusOk) { return; } DateTime datetime; furi_hal_rtc_get_datetime(&datetime); furi_string_printf( game_context->data->buffer, "%c%c\t%04d-%02d-%02dT%02d:%02d:%02d\t%s\t%s", game_context->data->local_player, game_context->data->remote_player, datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second, (game_context->data->remote_name) ? furi_string_get_cstr(game_context->data->remote_name) : "Unknown", (game_context->data->remote_contact) ? furi_string_get_cstr(game_context->data->remote_contact) : CONTACT_INFO_NONE); FURI_LOG_I(TAG, "Saving result: %s", furi_string_get_cstr(game_context->data->buffer)); Storage* storage = furi_record_open(RECORD_STORAGE); ensure_dir_exists(storage); File* games_file = storage_file_alloc(storage); // Append contents to ending of games.txt (create if doesn't exist) if(storage_file_open(games_file, RPS_GAME_PATH, FSAM_WRITE, FSOM_OPEN_APPEND)) { FURI_LOG_T(TAG, "Opened file: %s", RPS_GAME_PATH); if(!storage_file_write( games_file, furi_string_get_cstr(game_context->data->buffer), furi_string_size(game_context->data->buffer))) { FURI_LOG_E(TAG, "Failed to write to file."); } storage_file_write(games_file, "\n", 1); } else { FURI_LOG_E(TAG, "Failed to open file: %s", RPS_GAME_PATH); } furi_string_printf( game_context->data->buffer, "%04d-%02d-%02dT%02d:%02d:%02d", datetime.year, datetime.month, datetime.day, datetime.hour, datetime.minute, datetime.second); update_player_stats( game_context, game_context->data->remote_player, furi_string_get_cstr(game_context->data->remote_name), furi_string_get_cstr(game_context->data->remote_contact), furi_string_get_cstr(game_context->data->buffer)); storage_file_close(games_file); storage_file_free(games_file); furi_record_close(RECORD_STORAGE); furi_mutex_release(game_context->mutex); }
// Saves a game result to the file system. // @param game_context pointer to a GameContext.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1663-L1731
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
rock_paper_scissors_app
int32_t rock_paper_scissors_app(void* p) { UNUSED(p); // Configure our initial data. GameContext* game_context = malloc(sizeof(GameContext)); game_context->mutex = furi_mutex_alloc(FuriMutexTypeNormal); game_context->data = malloc(sizeof(GameData)); game_context->data->buffer = furi_string_alloc(); game_context->data->game_number = 42; game_context->data->frequency_index = 10; game_context->data->local_move_tick = 0; game_context->data->remote_move_tick = 0; game_context->data->local_player = StateMainMenuMessage; game_context->data->remote_player = StateUnknown; game_context->data->screen_state = ScreenMainMenu; game_context->data->remote_games = NULL; game_context->data->local_contact = furi_string_alloc(); furi_string_set(game_context->data->local_contact, CONTACT_INFO); game_context->data->keyboard_heading = furi_string_alloc(); game_context->data->keyboard_data = furi_string_alloc(); load_player_stats(game_context); load_local_contact(game_context); // Queue for events game_context->queue = furi_message_queue_alloc(8, sizeof(GameEvent)); // Subghz worker. game_context->subghz_txrx = subghz_tx_rx_worker_alloc(); subghz_devices_init(); // All the subghz CLI apps disable charging; so our game does it too. furi_hal_power_suppress_charge_enter(); // Set ViewPort callbacks ViewPort* view_port = view_port_alloc(); view_port_draw_callback_set(view_port, rps_render_callback, game_context); view_port_input_callback_set(view_port, rps_input_callback, game_context->queue); // Open GUI and register view_port Gui* gui = furi_record_open(RECORD_GUI); gui_add_view_port(gui, view_port, GuiLayerFullscreen); // Run routine once a second. FuriTimer* timer = furi_timer_alloc(rps_timer_callback, FuriTimerTypePeriodic, game_context); furi_timer_start(timer, 1000); // Main loop GameEvent event; uint8_t beaconCounter = 0; bool processing = true; do { if(furi_message_queue_get(game_context->queue, &event, FuriWaitForever) == FuriStatusOk) { switch(event.type) { case GameEventTypeKey: if((event.input.type == InputTypeLong) && (event.input.key == InputKeyBack)) { // Long press back to exit. processing = false; } else if( (event.input.type == InputTypeShort) && (event.input.key == InputKeyBack) && game_context->data->screen_state != ScreenFinishedGame) { if(game_context->data->local_player == StateHostingLookingForPlayer) { rps_broadcast_not_beacon(game_context); } // Short press back to go back to main menu. game_context->data->local_player = StateMainMenuHost; game_context->data->remote_player = StateUnknown; game_context->data->screen_state = ScreenMainMenu; } else if( game_context->data->screen_state == ScreenHostGame && event.input.type == InputTypeShort) { GameEvent newEvent = { .type = GameEventLocalMove, .tick = furi_get_tick(), .move = MoveUnknown}; switch(event.input.key) { case InputKeyUp: if(game_context->data->local_player == StateHostingLookingForPlayer) { rps_broadcast_not_beacon(game_context); } game_context->data->local_player = StateHostingSetFrequency; break; case InputKeyDown: if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { if(game_context->data->local_player == StateHostingLookingForPlayer) { rps_broadcast_not_beacon(game_context); } game_context->data->local_player = StateHostingSetGameNumber; } break; case InputKeyOk: if(update_frequency(game_context)) { game_context->data->local_player = StateHostingLookingForPlayer; } else { game_context->data->local_player = StateHostingBadFrequency; } break; case InputKeyRight: if(game_context->data->local_player == StateHostingSetGameNumber) { if(game_context->data->game_number < 999) { game_context->data->game_number++; } } else if( game_context->data->local_player == StateHostingSetFrequency || game_context->data->local_player == StateHostingBadFrequency) { if((uint8_t)(game_context->data->frequency_index + 1) < sizeof(frequency_list) / sizeof(frequency_list[0])) { game_context->data->frequency_index++; if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateHostingSetFrequency; } else { game_context->data->local_player = StateHostingBadFrequency; } } } break; case InputKeyLeft: if(game_context->data->local_player == StateHostingSetGameNumber) { if(game_context->data->game_number > 0) { game_context->data->game_number--; } } else if( game_context->data->local_player == StateHostingSetFrequency || game_context->data->local_player == StateHostingBadFrequency) { if(game_context->data->frequency_index > 0) { game_context->data->frequency_index--; if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateHostingSetFrequency; } else { game_context->data->local_player = StateHostingBadFrequency; } } } break; default: FURI_LOG_T(TAG, "No support for key %d", event.input.key); break; } if(newEvent.move != MoveUnknown) { furi_message_queue_put(game_context->queue, &newEvent, FuriWaitForever); } } else if( game_context->data->screen_state == ScreenJoinGame && event.input.type == InputTypeShort) { GameInfo* game; GameEvent newEvent = { .type = GameEventLocalMove, .tick = furi_get_tick(), .move = MoveUnknown}; switch(event.input.key) { case InputKeyUp: if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateJoiningSetFrequency; } else { game_context->data->local_player = StateJoiningBadFrequency; } break; case InputKeyDown: if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateJoiningSetGameNumber; } break; case InputKeyOk: game = remote_games_current(game_context); if(game && update_frequency(game_context)) { // We send "Join" when OK button clicked. game_context->data->game_number = game->game_number; if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) == FuriStatusOk) { game_context->data->local_player = StateHostingLookingForPlayer; rps_broadcast_join(game_context); furi_mutex_release(game_context->mutex); } else { FURI_LOG_E(TAG, "Failed to aquire mutex."); } } else if(game) { game_context->data->local_player = StateJoiningBadFrequency; } break; case InputKeyRight: if(game_context->data->local_player == StateJoiningSetGameNumber) { remote_games_next(game_context); } else if( game_context->data->local_player == StateJoiningSetFrequency || game_context->data->local_player == StateJoiningBadFrequency) { if((uint8_t)(game_context->data->frequency_index + 1) < sizeof(frequency_list) / sizeof(frequency_list[0])) { game_context->data->frequency_index++; if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateJoiningSetFrequency; } else { game_context->data->local_player = StateJoiningBadFrequency; } remote_games_clear(game_context); update_frequency(game_context); } } break; case InputKeyLeft: if(game_context->data->local_player == StateJoiningSetGameNumber) { remote_games_previous(game_context); } else if( game_context->data->local_player == StateJoiningSetFrequency || game_context->data->local_player == StateJoiningBadFrequency) { if(game_context->data->frequency_index > 0) { game_context->data->frequency_index--; if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateJoiningSetFrequency; } else { game_context->data->local_player = StateJoiningBadFrequency; } remote_games_clear(game_context); update_frequency(game_context); } } break; default: FURI_LOG_T(TAG, "No support for key %d", event.input.key); break; } if(newEvent.move != MoveUnknown) { furi_message_queue_put(game_context->queue, &newEvent, FuriWaitForever); } } else if( game_context->data->screen_state == ScreenPlayingGame && event.input.type == InputTypeShort) { GameEvent newEvent = { .type = GameEventLocalMove, .tick = furi_get_tick(), .move = MoveUnknown}; switch(event.input.key) { case InputKeyOk: newEvent.move = MoveCount; break; case InputKeyUp: newEvent.move = MoveRock; break; case InputKeyRight: newEvent.move = MovePaper; break; case InputKeyDown: newEvent.move = MoveScissors; break; default: FURI_LOG_T(TAG, "No support for key %d", event.input.key); break; } if(newEvent.move != MoveUnknown) { furi_message_queue_put(game_context->queue, &newEvent, FuriWaitForever); } } else if( game_context->data->screen_state == ScreenError && event.input.type == InputTypeShort) { switch(event.input.key) { case InputKeyOk: game_context->data->local_player = StateMainMenuHost; game_context->data->remote_player = StateUnknown; game_context->data->screen_state = ScreenMainMenu; break; default: FURI_LOG_T(TAG, "No support for key %d", event.input.key); break; } } else if( game_context->data->screen_state == ScreenEditMessage && event.input.type == InputTypeShort) { char ch; switch(event.input.key) { case InputKeyLeft: if(game_context->data->keyboard_col) { game_context->data->keyboard_col--; } else { game_context->data->keyboard_col = 13; } break; case InputKeyRight: if(game_context->data->keyboard_col < 13) { game_context->data->keyboard_col++; } else { game_context->data->keyboard_col = 0; } break; case InputKeyUp: if(game_context->data->keyboard_row) { game_context->data->keyboard_row--; } else { game_context->data->keyboard_row = 3; } break; case InputKeyDown: if(game_context->data->keyboard_row < 3) { game_context->data->keyboard_row++; } else { game_context->data->keyboard_row = 0; } break; case InputKeyOk: ch = get_char(game_context, true); if(ch >= ' ' && ch <= '~') { int len = furi_string_utf8_length(game_context->data->keyboard_data); if(len < KEYBOARD_MAX_LEN) { furi_string_push_back(game_context->data->keyboard_data, ch); } else { single_vibro(); } } else if(ch == KEYBOARD_BACKSPACE) { int len = furi_string_utf8_length(game_context->data->keyboard_data); if(len > 0) { furi_string_left(game_context->data->keyboard_data, len - 1); } } else if(ch == KEYBOARD_ENTER) { furi_string_printf( game_context->data->local_contact, "%c%s", contact_list[game_context->data->social_line][0], furi_string_get_cstr(game_context->data->keyboard_data)); save_local_contact(game_context); game_context->data->screen_state = ScreenMainMenu; } break; default: break; } } else if( game_context->data->screen_state == ScreenEditMessage && event.input.type == InputTypeLong) { char ch; switch(event.input.key) { case InputKeyOk: ch = get_char(game_context, false); if(ch >= ' ' && ch <= '~') { int len = furi_string_utf8_length(game_context->data->keyboard_data); if(len < KEYBOARD_MAX_LEN) { furi_string_push_back(game_context->data->keyboard_data, ch); } else { single_vibro(); } } else if(ch == KEYBOARD_BACKSPACE) { furi_string_left(game_context->data->keyboard_data, 0); } break; default: break; } } else if( game_context->data->screen_state == ScreenChooseSocial && event.input.type == InputTypeShort) { switch(event.input.key) { case InputKeyUp: if(game_context->data->social_line) { game_context->data->social_line--; } else { single_vibro(); } break; case InputKeyDown: if(++game_context->data->social_line >= (int)COUNT_OF(contact_list)) { game_context->data->social_line--; single_vibro(); } break; case InputKeyOk: if(game_context->data->social_line == 0) { furi_string_set(game_context->data->local_contact, CONTACT_INFO_NONE); save_local_contact(game_context); game_context->data->screen_state = ScreenMainMenu; } else { furi_string_set( game_context->data->keyboard_heading, contact_list[game_context->data->social_line] + 1); game_context->data->keyboard_row = 3; game_context->data->keyboard_col = 13; load_keyboard_data(game_context); game_context->data->screen_state = ScreenEditMessage; } break; default: break; } } else if( game_context->data->screen_state == ScreenMainMenu && event.input.type == InputTypeShort) { switch(event.input.key) { case InputKeyUp: if(game_context->data->local_player == StateMainMenuJoin) { game_context->data->local_player = StateMainMenuHost; } else if(game_context->data->local_player == StateMainMenuPastGames) { game_context->data->local_player = StateMainMenuJoin; } else if(game_context->data->local_player == StateMainMenuHost) { game_context->data->local_player = StateMainMenuMessage; } break; case InputKeyDown: if(game_context->data->local_player == StateMainMenuHost) { game_context->data->local_player = StateMainMenuJoin; } else if(game_context->data->local_player == StateMainMenuJoin) { game_context->data->local_player = StateMainMenuPastGames; } else if(game_context->data->local_player == StateMainMenuMessage) { game_context->data->local_player = StateMainMenuHost; } break; case InputKeyOk: if(game_context->data->local_player == StateMainMenuHost) { if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateHostingSetFrequency; } else { game_context->data->local_player = StateHostingBadFrequency; } game_context->data->remote_player = StateUnknown; game_context->data->local_move_tick = furi_get_tick(); game_context->data->remote_move_tick = furi_get_tick(); game_context->data->screen_state = ScreenHostGame; } else if(game_context->data->local_player == StateMainMenuJoin) { if(furi_hal_region_is_frequency_allowed( frequency_list[game_context->data->frequency_index])) { game_context->data->local_player = StateJoiningSetFrequency; update_frequency(game_context); } else { game_context->data->local_player = StateJoiningBadFrequency; } remote_games_clear(game_context); game_context->data->remote_player = StateUnknown; game_context->data->local_move_tick = furi_get_tick(); game_context->data->remote_move_tick = furi_get_tick(); game_context->data->screen_state = ScreenJoinGame; } else if(game_context->data->local_player == StateMainMenuPastGames) { game_context->data->viewing_player_stats = game_context->data->player_stats; game_context->data->screen_state = ScreenPastGames; } else if(game_context->data->local_player == StateMainMenuMessage) { game_context->data->screen_state = ScreenChooseSocial; } break; default: FURI_LOG_T(TAG, "No support for key %d", event.input.key); break; } } else if( game_context->data->screen_state == ScreenFinishedGame && event.input.type == InputTypeShort) { switch(event.input.key) { case InputKeyLeft: game_context->data->keyboard_col = 0; // YES - Play again break; case InputKeyRight: game_context->data->keyboard_col = 1; // NO - Back to main menu break; case InputKeyBack: game_context->data->keyboard_col = 1; // NO - Back to main menu rps_broadcast_quit(game_context); game_context->data->local_player = StateMainMenuHost; game_context->data->remote_player = StateUnknown; game_context->data->screen_state = ScreenMainMenu; break; case InputKeyOk: if(game_context->data->keyboard_col == 1) { rps_broadcast_quit(game_context); game_context->data->local_player = StateMainMenuHost; game_context->data->remote_player = StateUnknown; game_context->data->screen_state = ScreenMainMenu; } else { rps_broadcast_play_again(game_context); game_context->data->remote_player = StateReady; game_context->data->remote_move_tick = furi_get_tick(); game_context->data->local_player = StateReady; game_context->data->local_move_tick = furi_get_tick(); game_context->data->screen_state = ScreenPlayingGame; } break; default: break; } } else if( game_context->data->screen_state == ScreenPastGames && event.input.type == InputTypeShort) { switch(event.input.key) { case InputKeyLeft: if(game_context->data->viewing_player_stats) { if(game_context->data->viewing_player_stats->prev) { game_context->data->viewing_player_stats = game_context->data->viewing_player_stats->prev; FURI_LOG_I( TAG, "Moved to item %s.", furi_string_get_cstr( game_context->data->viewing_player_stats->flipper_name)); } else { FURI_LOG_I(TAG, "Viewing first item in list."); } } break; case InputKeyRight: if(game_context->data->viewing_player_stats) { if(game_context->data->viewing_player_stats->next) { game_context->data->viewing_player_stats = game_context->data->viewing_player_stats->next; FURI_LOG_I( TAG, "Moved to item %s.", furi_string_get_cstr( game_context->data->viewing_player_stats->flipper_name)); } else { FURI_LOG_I(TAG, "Viewing last item in list."); } } break; default: FURI_LOG_T(TAG, "No support for key %d", event.input.key); break; } } break; case GameEventPlaySong: save_result(game_context); play_song(game_context); break; case GameEventSongEnded: if(isResult(game_context->data->local_player)) { game_context->data->keyboard_col = 0; // YES game_context->data->screen_state = ScreenFinishedGame; } break; case GameEventDataDetected: rps_receive_data(game_context, event.tick); break; case GameEventTypeTimer: if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) == FuriStatusOk) { if(StateHostingLookingForPlayer == game_context->data->local_player && ++beaconCounter >= BEACON_DURATION) { rps_broadcast_beacon(game_context); beaconCounter = 0; } rps_state_machine_update(game_context); furi_mutex_release(game_context->mutex); } else { FURI_LOG_E(TAG, "Failed to aquire mutex."); } break; case GameEventRemoteBeacon: FURI_LOG_I(TAG, "Remote beacon detected. game number %03u", event.game_number); remote_games_add(game_context, &event); break; case GameEventRemoteNotBeacon: FURI_LOG_I(TAG, "Remote not beacon detected. game number %03u", event.game_number); remote_games_remove(game_context, &event); break; case GameEventRemotePlayAgain: game_context->data->remote_player = StateReady; game_context->data->remote_move_tick = furi_get_tick(); game_context->data->local_player = StateReady; game_context->data->local_move_tick = furi_get_tick(); game_context->data->screen_state = ScreenPlayingGame; break; case GameEventRemoteQuit: game_context->data->local_player = StateMainMenuHost; game_context->data->remote_player = StateUnknown; game_context->data->screen_state = ScreenMainMenu; break; case GameEventRemoteJoined: if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) == FuriStatusOk) { if(event.game_number == game_context->data->game_number) { if(rps_state_machine_remote_joined(game_context)) { rps_broadcast_join_acknowledge(game_context); if(game_context->data->remote_name) { furi_string_free(game_context->data->remote_name); } game_context->data->remote_name = event.sender_name; if(game_context->data->remote_contact) { furi_string_free(game_context->data->remote_contact); } game_context->data->remote_contact = event.sender_contact; // Take ownership of the name and contact event.sender_name = NULL; event.sender_contact = NULL; } else { remote_games_remove(game_context, &event); } } else { FURI_LOG_T( TAG, "Remote joining another Flipper on game %03u.", event.game_number); remote_games_remove(game_context, &event); } furi_mutex_release(game_context->mutex); } else { FURI_LOG_E(TAG, "Failed to aquire mutex."); } break; case GameEventRemoteJoinAcknowledged: if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) == FuriStatusOk) { if(event.game_number == game_context->data->game_number) { FURI_LOG_I(TAG, "Remote join acknowledged."); if(game_context->data->remote_name) { furi_string_free(game_context->data->remote_name); } game_context->data->remote_name = event.sender_name; if(game_context->data->remote_contact) { furi_string_free(game_context->data->remote_contact); } game_context->data->remote_contact = event.sender_contact; game_context->data->remote_player = StateReady; game_context->data->remote_move_tick = furi_get_tick(); game_context->data->local_player = StateReady; game_context->data->local_move_tick = furi_get_tick(); game_context->data->screen_state = ScreenPlayingGame; // Take ownership of the name and contact event.sender_name = NULL; event.sender_contact = NULL; } else { FURI_LOG_T( TAG, "Remote join acknowledge another Flipper on game %03u.", event.game_number); } furi_mutex_release(game_context->mutex); } else { FURI_LOG_E(TAG, "Failed to aquire mutex."); } break; case GameEventLocalMove: if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) == FuriStatusOk) { rps_state_machine_local_moved(game_context, event.move); furi_mutex_release(game_context->mutex); } else { FURI_LOG_E(TAG, "Failed to aquire mutex for local move."); } break; case GameEventRemoteMove: if(furi_mutex_acquire(game_context->mutex, FuriWaitForever) == FuriStatusOk) { rps_state_machine_remote_moved(game_context, event.move); furi_mutex_release(game_context->mutex); } else { FURI_LOG_E(TAG, "Failed to aquire mutex for remote move."); } break; default: FURI_LOG_E(TAG, "Queue had unknown message type: %u", event.type); break; } // If message contains a sender name furi_string, free it. if(event.sender_name) { furi_string_free(event.sender_name); } // Send signal to update the screen (callback will get invoked at some point later.) view_port_update(view_port); } else { // We had an issue getting message from the queue, so exit application. FURI_LOG_E(TAG, "Issue encountered reading from queue. Exiting application."); processing = false; } } while(processing); // Free resources furi_timer_free(timer); if(subghz_tx_rx_worker_is_running(game_context->subghz_txrx)) { subghz_tx_rx_worker_stop(game_context->subghz_txrx); } subghz_tx_rx_worker_free(game_context->subghz_txrx); subghz_devices_deinit(); view_port_enabled_set(view_port, false); gui_remove_view_port(gui, view_port); view_port_free(view_port); furi_record_close(RECORD_GUI); furi_message_queue_free(game_context->queue); furi_mutex_free(game_context->mutex); furi_string_free(game_context->data->buffer); furi_string_free(game_context->data->local_contact); if(game_context->data->remote_name) { furi_string_free(game_context->data->remote_name); } if(game_context->data->remote_contact) { furi_string_free(game_context->data->remote_contact); } remote_games_clear(game_context); free(game_context->data); free(game_context); // Reenable charging. furi_hal_power_suppress_charge_exit(); return 0; }
// This is the entry point for our application, which should match the application.fam file.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/rock_paper_scissors/rock_paper_scissors.c#L1872-L2575
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_worker_update_rx_event_callback
static void subghz_demo_worker_update_rx_event_callback(void* ctx) { furi_assert(ctx); DemoContext* demo_context = ctx; DemoEvent event = {.type = DemoEventDataDetected}; furi_message_queue_put(demo_context->queue, &event, FuriWaitForever); }
// We register this callback to get invoked whenever new subghz data is received. // We queue a DemoEventDataDetected message and then return to the caller.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L89-L94
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_receive_data
static void subghz_demo_receive_data(DemoContext* instance) { uint8_t message[MESSAGE_MAX_LEN] = {0}; memset(message, 0x00, MESSAGE_MAX_LEN); size_t len = subghz_tx_rx_worker_read(instance->subghz_txrx, message, MESSAGE_MAX_LEN); size_t game_name_len = strlen(SUBGHZ_GAME_NAME); if(len < (game_name_len + 2)) { FURI_LOG_D(TAG, "Message not long enough. >%s<", message); // Message wasn't big enough to have our game name + the reason code + version; so it must not be for us. return; } // The message for a counter (C) (like 42) using version (A) should be "SGDEMO:" + "C" + "A" + "0042" + ":" + "YourFlip" + "\r\n" if(strcmp(SUBGHZ_GAME_NAME, (const char*)message)) { FURI_LOG_D(TAG, "Got message >%s<", message); // The purpose immediately follows the game name. DemoRfPurpose purpose = message[game_name_len]; uint8_t version = message[game_name_len + 1]; FURI_LOG_T(TAG, "Purpose is %c and Version is %c", purpose, version); // Right now we don't care much about the version of the application, but in the future we might need to // respond differently based on the version of the application running on the other Flipper Zero. // Important: Don't always trust what is sent, some people with Flipper Zero might send an // invalid version to trick your code into interpreting the payload in a special way. // Null terminate the buffer at the end of message so we don't accidently overrun our buffer. message[MESSAGE_MAX_LEN - 1] = 0; unsigned int number; char senderName[9]; switch(purpose) { case DemoRfPurposeCounter: // We expect this mesage to contain both the count and the sender name. if(sscanf((const char*)message + game_name_len + 2, "%04u:%8s", &number, senderName) == 2) { // IMPORTANT: The code processing the event needs to furi_string_free the senderName! FuriString* name = furi_string_alloc(); furi_string_set(name, senderName); // The counter is supposed to be a 4 digit number. if(number >= 10000U) { FURI_LOG_W(TAG, "Number was >= 10000U. >%s<", message); number %= 10000U; } DemoEvent event = { .type = DemoEventReceivedCounter, .number = number, .senderName = name}; furi_message_queue_put(instance->queue, &event, FuriWaitForever); } else { FURI_LOG_W(TAG, "Failed to parse counter message. >%s<", message); } break; case DemoRfPurposeTone: // We expect this message to contain both the frequency and the sender name. if(sscanf((const char*)message + game_name_len + 2, "%u:%8s", &number, senderName) == 2) { // IMPORTANT: The code processing the event needs to furi_string_free the senderName! FuriString* name = furi_string_alloc(); furi_string_set(name, senderName); DemoEvent event = { .type = DemoEventReceivedTone, .number = number, .senderName = name}; furi_message_queue_put(instance->queue, &event, FuriWaitForever); } else { FURI_LOG_W(TAG, "Failed to parse tone message. >%s<", message); } break; // Add parsing for other messages here. default: if(version <= MAJOR_VERSION) { // The version is same or less than ours, so we should know about the message purpose. FURI_LOG_W(TAG, "Message purpose not handled for known version. >%s<", message); } else { // The version is newer, so it's not surprising we don't know about the purpose. FURI_LOG_T(TAG, "Message purpose not handled. >%s<", message); } break; } } else { FURI_LOG_D(TAG, "Message not for our application. >%s<", message); } }
// This gets invoked when we process a DemoEventDataDetected event. // We read the message using subghz_tx_rx_worker_read. // We determine if the message is in the valid format. // If valid, we queue a DemoEventReceivedCounter/Tone message with the counter/frequency. // IMPORTANT: The code processing our event needs to furi_string_free the senderName!
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L101-L182
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_input_callback
static void subghz_demo_input_callback(InputEvent* input_event, void* ctx_q) { furi_assert(ctx_q); FuriMessageQueue* queue = ctx_q; DemoEvent event = {.type = DemoEventTypeKey, .input = *input_event}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// This gets invoked when input (button press) is detected. // We queue a DemoEventTypeKey message with the input event data.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L186-L191
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_tick_callback
static void subghz_demo_tick_callback(void* ctx_q) { furi_assert(ctx_q); FuriMessageQueue* queue = ctx_q; DemoEvent event = {.type = DemoEventTypeTick}; // We don't pass a wait value for 3rd parameter -- this event is not critical (and will happen again soon). furi_message_queue_put(queue, &event, 0); }
// We register this callback to get invoked by the timer on every tick. // We queue a DemoEventTypeTick message and then return to the caller.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L195-L201
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_send_count
static void subghz_demo_send_count(void* ctx) { furi_assert(ctx); DemoContext* demo_context = ctx; FuriMessageQueue* queue = demo_context->queue; DemoData* data = demo_context->data; unsigned int counter = data->localCounter; DemoEvent event = {.type = DemoEventSendCounter, .number = counter}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// Our DemoEventTypeKey handler invokes this method when user clicks OK button. // We queue a DemoEventSendCounter message with the counter data.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L205-L213
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_send_tone
static void subghz_demo_send_tone(void* ctx, unsigned int frequency) { furi_assert(ctx); DemoContext* demo_context = ctx; FuriMessageQueue* queue = demo_context->queue; DemoEvent event = {.type = DemoEventSendTone, .number = frequency}; furi_message_queue_put(queue, &event, FuriWaitForever); }
// Our DemoEventTypeKey handler invokes this method when user clicks UP button. // We queue a DemoEventSendTone message with the frequency data.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L217-L223
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_render_callback
static void subghz_demo_render_callback(Canvas* canvas, void* ctx) { furi_assert(ctx); DemoContext* demo_context = ctx; // Attempt to aquire context, so we can read the data. if(furi_mutex_acquire(demo_context->mutex, 200) != FuriStatusOk) { return; } DemoData* data = demo_context->data; unsigned int localCounter = data->localCounter; unsigned int remoteCounter = data->remoteCounter; // The counter is supposed to be a 4 digit number. furi_assert(localCounter < 10000U); furi_assert(remoteCounter <= 10000U); // 10000 means don't display. // Other fonts are FontPrimary, FontSecondary, FontKeyboard, FontBigNumbers, canvas_set_font(canvas, FontPrimary); canvas_draw_str_aligned(canvas, 5, 8, AlignLeft, AlignCenter, "Press OK to send count."); canvas_draw_str_aligned(canvas, 5, 20, AlignLeft, AlignCenter, "Press UP to send tone."); furi_string_printf(data->buffer, "%04u", localCounter); canvas_set_font(canvas, FontSecondary); canvas_draw_str_aligned( canvas, 64, 42, AlignCenter, AlignTop, furi_string_get_cstr(data->buffer)); if(remoteCounter < 10000U) { furi_string_printf(data->buffer, "Received %04u", remoteCounter); canvas_draw_str_aligned( canvas, 64, 52, AlignCenter, AlignTop, furi_string_get_cstr(data->buffer)); } furi_mutex_release(demo_context->mutex); }
// We register this callback to get invoked whenever we need to render the screen. // We render the UI on this callback thread.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L227-L260
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_update_local_counter
static void subghz_demo_update_local_counter(DemoContext* demo_context) { DemoData* data = demo_context->data; // Increment the counter (which is supposed to be a 4 digit number for this app.) data->localCounter++; if(data->localCounter >= 10000U) { data->localCounter = 0; } FURI_LOG_T(TAG, "Local counter %04u", data->localCounter); }
// Our DemoEventTypeTick handler invokes this method. // We increment our counter (wrapping back to 0 if it exceeds a 4 digit number.)
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L264-L274
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_update_remote_counter
static void subghz_demo_update_remote_counter(DemoContext* demo_context, DemoEvent* event) { // The queueing code should have made sure the value was valid. furi_assert(event->number < 10000U); DemoData* data = demo_context->data; data->remoteCounter = event->number; FURI_LOG_I(TAG, "Remote counter %04u", data->remoteCounter); }
// Our DemoEventReceivedCounter handler invokes this method. // We update our remote counter.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L278-L285
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_play_tone
static void subghz_demo_play_tone(DemoContext* demo_context, DemoEvent* event) { UNUSED(demo_context); unsigned int frequency = event->number; FURI_LOG_I(TAG, "Playing frequency %04u", frequency); // Make tones if the speaker is available. if(furi_hal_speaker_acquire(1000)) { // We wait up to a second for now, is that too long? float freq = (float)frequency; float volume = 1.0f; // 100% volume. furi_hal_speaker_start(freq, volume); furi_delay_ms(100); furi_hal_speaker_stop(); furi_hal_speaker_release(); } }
// Our DemoEventReceivedTone handler invokes this method. // We play a quick (100ms) tone of the desired frequency.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L289-L303
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_broadcast
static void subghz_demo_broadcast(DemoContext* demo_context, FuriString* buffer) { uint8_t* message = (uint8_t*)furi_string_get_cstr(buffer); // Make sure our message will fit into a packet; if not truncate it. size_t length = strlen((char*)message); if(length > MESSAGE_MAX_LEN) { FURI_LOG_E( TAG, "Outgoing message bigger than %d bytes! >%s<", MESSAGE_MAX_LEN, (char*)message); // Add \r\n(null) to the end of the 0-indexed string. message[MESSAGE_MAX_LEN - 1] = 0; message[MESSAGE_MAX_LEN - 2] = '\n'; message[MESSAGE_MAX_LEN - 3] = '\r'; length = MESSAGE_MAX_LEN; } while(!subghz_tx_rx_worker_write(demo_context->subghz_txrx, message, length)) { // Wait a few milliseconds on failure before trying to send again. furi_delay_ms(20); } }
// This is a helper method that broadcasts a buffer. // If the message is too large, the message will get truncated.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L307-L327
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_broadcast_counter
static void subghz_demo_broadcast_counter(DemoContext* demo_context, unsigned int counterToSend) { // The counter is supposed to be a 4 digit number. furi_assert(counterToSend < 10000U); DemoData* data = demo_context->data; FURI_LOG_I(TAG, "Sending counter %04u", counterToSend); // The message for a counter with value 42 should look like... "SGDEMO:CA0042:YourFlip\r\n" furi_string_printf( data->buffer, "%s%c%c%04u:%s\r\n", SUBGHZ_GAME_NAME, DemoRfPurposeCounter, MAJOR_VERSION, counterToSend, furi_hal_version_get_name_ptr()); subghz_demo_broadcast(demo_context, data->buffer); }
// Our DemoEventSendCounter handler invokes this method. // We broadcast - "game name + purpose (Counter) + Version (A) + 4 digit counter value + : + Flipper name + \r\n"
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L331-L349
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_broadcast_tone
static void subghz_demo_broadcast_tone(DemoContext* demo_context, unsigned int frequency) { DemoData* data = demo_context->data; FURI_LOG_I(TAG, "Sending frequency %04u", frequency); // The message for a frequency of 440 should look like... "SGDEMO:TA440:YourFlip\r\n" furi_string_printf( data->buffer, "%s%c%c%u:%s\r\n", SUBGHZ_GAME_NAME, DemoRfPurposeTone, MAJOR_VERSION, frequency, furi_hal_version_get_name_ptr()); subghz_demo_broadcast(demo_context, data->buffer); }
// Our DemoEventSendTone handler invokes this method. // We broadcast - "game name + purpose (Tone) + Version (A) + frequency + : + Flipper name + \r\n"
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L353-L369
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_demo_app
int32_t subghz_demo_app(void* p) { UNUSED(p); // For this demo we hardcode to 433.92MHz. uint32_t frequency = 433920000; // TODO: Have an ordered list of frequencies we try, instead of just 1 frequency. // Configure our initial data. DemoContext* demo_context = malloc(sizeof(DemoContext)); demo_context->mutex = furi_mutex_alloc(FuriMutexTypeNormal); demo_context->data = malloc(sizeof(DemoData)); demo_context->data->buffer = furi_string_alloc(); demo_context->data->localCounter = 0; demo_context->data->remoteCounter = 10000U; // Won't display, since larger than 4-digit number. // Queue for events demo_context->queue = furi_message_queue_alloc(8, sizeof(DemoEvent)); // Subghz worker. demo_context->subghz_txrx = subghz_tx_rx_worker_alloc(); subghz_devices_init(); // Try to start the TX/RX on the frequency and configure our callback // whenever new data is received. const SubGhzDevice* device = subghz_devices_get_by_name(SUBGHZ_DEVICE_CC1101_INT_NAME); // Use internal CC1101 radio furi_assert(device); if(subghz_tx_rx_worker_start(demo_context->subghz_txrx, device, frequency)) { subghz_tx_rx_worker_set_callback_have_read( demo_context->subghz_txrx, subghz_demo_worker_update_rx_event_callback, demo_context); } else { FURI_LOG_E(TAG, "Failed to start subghz_tx_rx_worker."); // For this demo we don't show a friendly error about not being // allowed to broadcast on this frequency. Instead the application // just exits. if(subghz_tx_rx_worker_is_running(demo_context->subghz_txrx)) { subghz_tx_rx_worker_stop(demo_context->subghz_txrx); } subghz_tx_rx_worker_free(demo_context->subghz_txrx); subghz_devices_deinit(); furi_message_queue_free(demo_context->queue); furi_mutex_free(demo_context->mutex); furi_string_free(demo_context->data->buffer); free(demo_context->data); free(demo_context); return 2; } // All the subghz CLI apps disable charging; so our demo does it too. furi_hal_power_suppress_charge_enter(); // Set ViewPort callbacks ViewPort* view_port = view_port_alloc(); view_port_draw_callback_set(view_port, subghz_demo_render_callback, demo_context); view_port_input_callback_set(view_port, subghz_demo_input_callback, demo_context->queue); // Open GUI and register view_port Gui* gui = furi_record_open(RECORD_GUI); gui_add_view_port(gui, view_port, GuiLayerFullscreen); // Update the screen fairly frequently (every 250 milliseconds.) FuriTimer* timer = furi_timer_alloc(subghz_demo_tick_callback, FuriTimerTypePeriodic, demo_context->queue); furi_timer_start(timer, 250); // Main loop DemoEvent event; bool processing = true; do { if(furi_message_queue_get(demo_context->queue, &event, FuriWaitForever) == FuriStatusOk) { switch(event.type) { case DemoEventTypeKey: // Short press of OK button, queue DemoEventSendCounter event with the current count. if(event.input.type == InputTypeShort && event.input.key == InputKeyOk) { furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_send_count(demo_context); furi_mutex_release(demo_context->mutex); } // Short press of UP button, queue DemoEventSendTone event. else if(event.input.type == InputTypeShort && event.input.key == InputKeyUp) { furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_send_tone(demo_context, 440U); furi_mutex_release(demo_context->mutex); } // Long press of UP button, queue DemoEventSendTone event. else if(event.input.type == InputTypeLong && event.input.key == InputKeyUp) { furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_send_tone(demo_context, 880U); furi_mutex_release(demo_context->mutex); } // Short press of back button exits the program. else if(event.input.type == InputTypeShort && event.input.key == InputKeyBack) { processing = false; } break; case DemoEventTypeTick: // Every timer tick we update the counter. furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_update_local_counter(demo_context); furi_mutex_release(demo_context->mutex); break; case DemoEventSendCounter: // Actually send the counter value to the other Flipper Zero. furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_broadcast_counter(demo_context, event.number); furi_mutex_release(demo_context->mutex); break; case DemoEventSendTone: // Actually send the frequency value to the other Flipper Zero. furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_broadcast_tone(demo_context, event.number); furi_mutex_release(demo_context->mutex); break; case DemoEventDataDetected: // Another Flipper sent us data! Process it, potentially queuing an event. subghz_demo_receive_data(demo_context); break; case DemoEventReceivedCounter: // Process the counter sent by the other Flipper Zero. furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_update_remote_counter(demo_context, &event); furi_mutex_release(demo_context->mutex); break; case DemoEventReceivedTone: // Process the tone sent by the other Flipper Zero. furi_mutex_acquire(demo_context->mutex, FuriWaitForever); subghz_demo_play_tone(demo_context, &event); furi_mutex_release(demo_context->mutex); break; default: FURI_LOG_E(TAG, "Queue had unknown message type: %u", event.type); break; } // If message contains a sender name furi_string, free it. if(event.senderName) { furi_string_free(event.senderName); } // Send signal to update the screen (callback will get invoked at some point later.) view_port_update(view_port); } else { // We had an issue getting message from the queue, so exit application. FURI_LOG_E(TAG, "Issue encountered reading from queue. Exiting application."); processing = false; } } while(processing); // Free resources furi_timer_free(timer); if(subghz_tx_rx_worker_is_running(demo_context->subghz_txrx)) { subghz_tx_rx_worker_stop(demo_context->subghz_txrx); } subghz_tx_rx_worker_free(demo_context->subghz_txrx); subghz_devices_deinit(); view_port_enabled_set(view_port, false); gui_remove_view_port(gui, view_port); view_port_free(view_port); furi_record_close(RECORD_GUI); furi_message_queue_free(demo_context->queue); furi_mutex_free(demo_context->mutex); furi_string_free(demo_context->data->buffer); free(demo_context->data); free(demo_context); // Reenable charging. furi_hal_power_suppress_charge_exit(); return 0; }
// This is the entry point for our application, which should match the application.fam file.
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/plugins/subghz_demo/subghz_demo_app.c#L372-L543
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
subghz_protocol_x10_check_remote_controller
static void subghz_protocol_x10_check_remote_controller(SubGhzBlockGeneric* instance) { instance->serial = (instance->data & 0xF0000000) >> (24+4); instance->btn = (((instance->data & 0x07000000) >> 24) | ((instance->data & 0xF800) >> 8)); }
/** * Set the serial and btn values based on the data and data_count_bit. * @param instance Pointer to a SubGhzBlockGeneric* instance */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/subghz/protocols/x10/x10.c#L209-L212
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_navigation_exit_callback
static uint32_t skeleton_navigation_exit_callback(void* _context) { UNUSED(_context); return VIEW_NONE; }
/** * @brief Callback for exiting the application. * @details This function is called when user press back button. We return VIEW_NONE to * indicate that we want to exit the application. * @param _context The context - unused * @return next view id */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L69-L72
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_navigation_submenu_callback
static uint32_t skeleton_navigation_submenu_callback(void* _context) { UNUSED(_context); return SkeletonViewSubmenu; }
/** * @brief Callback for returning to submenu. * @details This function is called when user press back button. We return VIEW_NONE to * indicate that we want to navigate to the submenu. * @param _context The context - unused * @return next view id */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L81-L84
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_navigation_configure_callback
static uint32_t skeleton_navigation_configure_callback(void* _context) { UNUSED(_context); return SkeletonViewConfigure; }
/** * @brief Callback for returning to configure screen. * @details This function is called when user press back button. We return VIEW_NONE to * indicate that we want to navigate to the configure screen. * @param _context The context - unused * @return next view id */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L93-L96
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_submenu_callback
static void skeleton_submenu_callback(void* context, uint32_t index) { SkeletonApp* app = (SkeletonApp*)context; switch(index) { case SkeletonSubmenuIndexConfigure: view_dispatcher_switch_to_view(app->view_dispatcher, SkeletonViewConfigure); break; case SkeletonSubmenuIndexGame: view_dispatcher_switch_to_view(app->view_dispatcher, SkeletonViewGame); break; case SkeletonSubmenuIndexAbout: view_dispatcher_switch_to_view(app->view_dispatcher, SkeletonViewAbout); break; default: break; } }
/** * @brief Handle submenu item selection. * @details This function is called when user selects an item from the submenu. * @param context The context - SkeletonApp object. * @param index The SkeletonSubmenuIndex item that was clicked. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L104-L119
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_setting_item_clicked
static void skeleton_setting_item_clicked(void* context, uint32_t index) { SkeletonApp* app = (SkeletonApp*)context; index++; // The index starts at zero, but we want to start at 1. // Our configuration UI has the 2nd item as a text field. if(index == 2) { // Header to display on the text input screen. text_input_set_header_text(app->text_input, setting_2_entry_text); // Copy the current name into the temporary buffer. bool redraw = false; with_view_model( app->view_game, SkeletonGameModel * model, { strncpy( app->temp_buffer, furi_string_get_cstr(model->setting_2_name), app->temp_buffer_size); }, redraw); // Configure the text input. When user enters text and clicks OK, skeleton_setting_text_updated be called. bool clear_previous_text = false; text_input_set_result_callback( app->text_input, skeleton_setting_2_text_updated, app, app->temp_buffer, app->temp_buffer_size, clear_previous_text); // Pressing the BACK button will reload the configure screen. view_set_previous_callback( text_input_get_view(app->text_input), skeleton_navigation_configure_callback); // Show text input dialog. view_dispatcher_switch_to_view(app->view_dispatcher, SkeletonViewTextInput); } }
/** * @brief Callback when item in configuration screen is clicked. * @details This function is called when user clicks OK on an item in the configuration screen. * If the item clicked is our text field then we switch to the text input screen. * @param context The context - SkeletonApp object. * @param index - The index of the item that was clicked. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L165-L204
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_view_game_draw_callback
static void skeleton_view_game_draw_callback(Canvas* canvas, void* model) { SkeletonGameModel* my_model = (SkeletonGameModel*)model; canvas_draw_icon(canvas, my_model->x, 20, &I_glyph_1_14x40); canvas_draw_str(canvas, 1, 10, "LEFT/RIGHT to change x"); FuriString* xstr = furi_string_alloc(); furi_string_printf(xstr, "x: %u OK=play tone", my_model->x); canvas_draw_str(canvas, 44, 24, furi_string_get_cstr(xstr)); furi_string_printf(xstr, "random: %u", (uint8_t)(furi_hal_random_get() % 256)); canvas_draw_str(canvas, 44, 36, furi_string_get_cstr(xstr)); furi_string_printf( xstr, "team: %s (%u)", setting_1_names[my_model->setting_1_index], setting_1_values[my_model->setting_1_index]); canvas_draw_str(canvas, 44, 48, furi_string_get_cstr(xstr)); furi_string_printf(xstr, "name: %s", furi_string_get_cstr(my_model->setting_2_name)); canvas_draw_str(canvas, 44, 60, furi_string_get_cstr(xstr)); furi_string_free(xstr); }
/** * @brief Callback for drawing the game screen. * @details This function is called when the screen needs to be redrawn, like when the model gets updated. * @param canvas The canvas to draw on. * @param model The model - MyModel object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L212-L230
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_view_game_timer_callback
static void skeleton_view_game_timer_callback(void* context) { SkeletonApp* app = (SkeletonApp*)context; view_dispatcher_send_custom_event(app->view_dispatcher, SkeletonEventIdRedrawScreen); }
/** * @brief Callback for timer elapsed. * @details This function is called when the timer is elapsed. We use this to queue a redraw event. * @param context The context - SkeletonApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L237-L240
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_view_game_enter_callback
static void skeleton_view_game_enter_callback(void* context) { uint32_t period = furi_ms_to_ticks(200); SkeletonApp* app = (SkeletonApp*)context; furi_assert(app->timer == NULL); app->timer = furi_timer_alloc(skeleton_view_game_timer_callback, FuriTimerTypePeriodic, context); furi_timer_start(app->timer, period); }
/** * @brief Callback when the user starts the game screen. * @details This function is called when the user enters the game screen. We start a timer to * redraw the screen periodically (so the random number is refreshed). * @param context The context - SkeletonApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L248-L255
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_view_game_exit_callback
static void skeleton_view_game_exit_callback(void* context) { SkeletonApp* app = (SkeletonApp*)context; furi_timer_stop(app->timer); furi_timer_free(app->timer); app->timer = NULL; }
/** * @brief Callback when the user exits the game screen. * @details This function is called when the user exits the game screen. We stop the timer. * @param context The context - SkeletonApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L262-L267
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_view_game_custom_event_callback
static bool skeleton_view_game_custom_event_callback(uint32_t event, void* context) { SkeletonApp* app = (SkeletonApp*)context; switch(event) { case SkeletonEventIdRedrawScreen: // Redraw screen by passing true to last parameter of with_view_model. { bool redraw = true; with_view_model( app->view_game, SkeletonGameModel * _model, { UNUSED(_model); }, redraw); return true; } case SkeletonEventIdOkPressed: // Process the OK button. We play a tone based on the x coordinate. if(furi_hal_speaker_acquire(500)) { float frequency; bool redraw = false; with_view_model( app->view_game, SkeletonGameModel * model, { frequency = model->x * 100 + 100; }, redraw); furi_hal_speaker_start(frequency, 1.0); furi_delay_ms(100); furi_hal_speaker_stop(); furi_hal_speaker_release(); } return true; default: return false; } }
/** * @brief Callback for custom events. * @details This function is called when a custom event is sent to the view dispatcher. * @param event The event id - SkeletonEventId value. * @param context The context - SkeletonApp object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L275-L305
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_view_game_input_callback
static bool skeleton_view_game_input_callback(InputEvent* event, void* context) { SkeletonApp* app = (SkeletonApp*)context; if(event->type == InputTypeShort) { if(event->key == InputKeyLeft) { // Left button clicked, reduce x coordinate. bool redraw = true; with_view_model( app->view_game, SkeletonGameModel * model, { if(model->x > 0) { model->x--; } }, redraw); } else if(event->key == InputKeyRight) { // Right button clicked, increase x coordinate. bool redraw = true; with_view_model( app->view_game, SkeletonGameModel * model, { // Should we have some maximum value? model->x++; }, redraw); } } else if(event->type == InputTypePress) { if(event->key == InputKeyOk) { // We choose to send a custom event when user presses OK button. skeleton_custom_event_callback will // handle our SkeletonEventIdOkPressed event. We could have just put the code from // skeleton_custom_event_callback here, it's a matter of preference. view_dispatcher_send_custom_event(app->view_dispatcher, SkeletonEventIdOkPressed); return true; } } return false; }
/** * @brief Callback for game screen input. * @details This function is called when the user presses a button while on the game screen. * @param event The event - InputEvent object. * @param context The context - SkeletonApp object. * @return true if the event was handled, false otherwise. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L314-L352
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
skeleton_app_free
static void skeleton_app_free(SkeletonApp* app) { #ifdef BACKLIGHT_ON notification_message(app->notifications, &sequence_display_backlight_enforce_auto); #endif furi_record_close(RECORD_NOTIFICATION); view_dispatcher_remove_view(app->view_dispatcher, SkeletonViewTextInput); text_input_free(app->text_input); free(app->temp_buffer); view_dispatcher_remove_view(app->view_dispatcher, SkeletonViewAbout); widget_free(app->widget_about); view_dispatcher_remove_view(app->view_dispatcher, SkeletonViewGame); view_free(app->view_game); view_dispatcher_remove_view(app->view_dispatcher, SkeletonViewConfigure); variable_item_list_free(app->variable_item_list_config); view_dispatcher_remove_view(app->view_dispatcher, SkeletonViewSubmenu); submenu_free(app->submenu); view_dispatcher_free(app->view_dispatcher); furi_record_close(RECORD_GUI); free(app); }
/** * @brief Free the skeleton application. * @details This function frees the skeleton application resources. * @param app The skeleton application object. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L457-L478
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
main_skeleton_app
int32_t main_skeleton_app(void* _p) { UNUSED(_p); SkeletonApp* app = skeleton_app_alloc(); view_dispatcher_run(app->view_dispatcher); skeleton_app_free(app); return 0; }
/** * @brief Main function for skeleton application. * @details This function is the entry point for the skeleton application. It should be defined in * application.fam as the entry_point setting. * @param _p Input parameter - unused * @return 0 - Success */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/ui/skeleton_app/app.c#L487-L495
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_thread
static int32_t imu_thread(void* context) { furi_assert(context); ImuThread* imu = context; // float yaw_last = 0.f; // float pitch_last = 0.f; // float diff_x = 0.f; // float diff_y = 0.f; calibrate_gyro(imu); icm42688p_accel_config(imu->icm42688p, AccelFullScale16G, ACCEL_GYRO_RATE); icm42688p_gyro_config(imu->icm42688p, GyroFullScale2000DPS, ACCEL_GYRO_RATE); imu->processed_data.q0 = 1.f; imu->processed_data.q1 = 0.f; imu->processed_data.q2 = 0.f; imu->processed_data.q3 = 0.f; icm42688_fifo_enable(imu->icm42688p, imu_irq_callback, imu); while(1) { uint32_t events = furi_thread_flags_wait(FLAGS_ALL, FuriFlagWaitAny, FuriWaitForever); if(events & ImuStop) { break; } if(events & ImuNewData) { uint16_t data_pending = icm42688_fifo_get_count(imu->icm42688p); ICM42688PFifoPacket data; while(data_pending--) { icm42688_fifo_read(imu->icm42688p, &data); imu_process_data(imu, &data); } } } icm42688_fifo_disable(imu->icm42688p); return 0; }
// static float imu_angle_diff(float a, float b) { // float diff = a - b; // if(diff > 180.f) // diff -= 360.f; // else if(diff < -180.f) // diff += 360.f; // return diff; // }
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/air_level/engine/sensors/imu.c#L125-L165
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_madgwick_filter
static void imu_madgwick_filter( ImuProcessedData* out, ICM42688PScaledData* accel, ICM42688PScaledData* gyro) { float recipNorm; float s0, s1, s2, s3; float qDot1, qDot2, qDot3, qDot4; float _2q0, _2q1, _2q2, _2q3, _4q0, _4q1, _4q2, _8q1, _8q2, q0q0, q1q1, q2q2, q3q3; // Rate of change of quaternion from gyroscope qDot1 = 0.5f * (-out->q1 * gyro->x - out->q2 * gyro->y - out->q3 * gyro->z); qDot2 = 0.5f * (out->q0 * gyro->x + out->q2 * gyro->z - out->q3 * gyro->y); qDot3 = 0.5f * (out->q0 * gyro->y - out->q1 * gyro->z + out->q3 * gyro->x); qDot4 = 0.5f * (out->q0 * gyro->z + out->q1 * gyro->y - out->q2 * gyro->x); // Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation) if(!((accel->x == 0.0f) && (accel->y == 0.0f) && (accel->z == 0.0f))) { // Normalise accelerometer measurement recipNorm = imu_inv_sqrt(accel->x * accel->x + accel->y * accel->y + accel->z * accel->z); accel->x *= recipNorm; accel->y *= recipNorm; accel->z *= recipNorm; // Auxiliary variables to avoid repeated arithmetic _2q0 = 2.0f * out->q0; _2q1 = 2.0f * out->q1; _2q2 = 2.0f * out->q2; _2q3 = 2.0f * out->q3; _4q0 = 4.0f * out->q0; _4q1 = 4.0f * out->q1; _4q2 = 4.0f * out->q2; _8q1 = 8.0f * out->q1; _8q2 = 8.0f * out->q2; q0q0 = out->q0 * out->q0; q1q1 = out->q1 * out->q1; q2q2 = out->q2 * out->q2; q3q3 = out->q3 * out->q3; // Gradient decent algorithm corrective step s0 = _4q0 * q2q2 + _2q2 * accel->x + _4q0 * q1q1 - _2q1 * accel->y; s1 = _4q1 * q3q3 - _2q3 * accel->x + 4.0f * q0q0 * out->q1 - _2q0 * accel->y - _4q1 + _8q1 * q1q1 + _8q1 * q2q2 + _4q1 * accel->z; s2 = 4.0f * q0q0 * out->q2 + _2q0 * accel->x + _4q2 * q3q3 - _2q3 * accel->y - _4q2 + _8q2 * q1q1 + _8q2 * q2q2 + _4q2 * accel->z; s3 = 4.0f * q1q1 * out->q3 - _2q1 * accel->x + 4.0f * q2q2 * out->q3 - _2q2 * accel->y; recipNorm = imu_inv_sqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3); // normalise step magnitude s0 *= recipNorm; s1 *= recipNorm; s2 *= recipNorm; s3 *= recipNorm; // Apply feedback step qDot1 -= FILTER_BETA * s0; qDot2 -= FILTER_BETA * s1; qDot3 -= FILTER_BETA * s2; qDot4 -= FILTER_BETA * s3; } // Integrate rate of change of quaternion to yield quaternion out->q0 += qDot1 * (1.0f / FILTER_SAMPLE_FREQ); out->q1 += qDot2 * (1.0f / FILTER_SAMPLE_FREQ); out->q2 += qDot3 * (1.0f / FILTER_SAMPLE_FREQ); out->q3 += qDot4 * (1.0f / FILTER_SAMPLE_FREQ); // Normalise quaternion recipNorm = imu_inv_sqrt( out->q0 * out->q0 + out->q1 * out->q1 + out->q2 * out->q2 + out->q3 * out->q3); out->q0 *= recipNorm; out->q1 *= recipNorm; out->q2 *= recipNorm; out->q3 *= recipNorm; }
/* Simple madgwik filter, based on: https://github.com/arduino-libraries/MadgwickAHRS/ */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/air_level/engine/sensors/imu.c#L200-L272
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
level_imu_alloc
static void level_imu_alloc(Level* level, GameManager* manager, void* ctx) { UNUSED(ctx); UNUSED(manager); level_add_entity(level, &imu_debug_desc); }
/**** Level ****/
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/air_level/levels/level_imu.c#L130-L134
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
level_alloc
static void level_alloc(Level* level, GameManager* manager, void* context) { UNUSED(manager); UNUSED(context); // Add player entity to the level player_spawn(level, manager); // Add wall entities to the level wall_index = 0; for(size_t i = 0; i < COUNT_OF(walls); i++) { level_add_entity(level, &wall_desc); } }
/****** Level ******/
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/apps/air_labyrinth/game.c#L296-L308
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
game_start
static void game_start(GameManager* game_manager, void* ctx) { UNUSED(game_manager); // Do some initialization here, for example you can load score from storage. // For simplicity, we will just set it to 0. GameContext* game_context = ctx; game_context->score = 0; game_context->imu = imu_alloc(); game_context->imu_present = imu_present(game_context->imu); // Add level to the game game_manager_add_level(game_manager, &level); }
/****** Game ******/ /* Write here the start code for your game, for example: creating a level and so on. Game context is allocated (game.context_size) and passed to this function, you can use it to store your game data. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/apps/air_labyrinth/game.c#L331-L344
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
game_stop
static void game_stop(void* ctx) { GameContext* game_context = ctx; imu_free(game_context->imu); game_context->imu = NULL; // Do some deinitialization here, for example you can save score to storage. // For simplicity, we will just print it. FURI_LOG_I("Game", "Your score: %lu", game_context->score); }
/* Write here the stop code for your game, for example: freeing memory, if it was allocated. You don't need to free level, sprites or entities, it will be done automatically. Also, you don't need to free game_context, it will be done automatically, after this function. */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/apps/air_labyrinth/game.c#L351-L359
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_release
static void imu_controller_release(ImuController* controller, InputKey key) { // If the button was already released, ignore the request. if(controller->button_state[key] == ButtonStateReleased) { return; } if(controller->config->vibro_duration) { furi_hal_vibro_on(true); } // If the button was pressed, send a InputTypeShort event // (otherwise we already sent a InputTypeLong event). if(controller->button_state[key] == ButtonStatePressed) { controller->queue_message(controller->context, InputTypeShort, key); } // Send a InputTypeRelease event controller->queue_message(controller->context, InputTypeRelease, key); // Reset the button state controller->button_press_tick[key] = 0; controller->button_state[key] = ButtonStateReleased; if(controller->config->vibro_duration) { furi_delay_ms(controller->config->vibro_duration); furi_hal_vibro_on(false); } }
/** * @brief Release a virtual button * @param controller The controller * @param key The key */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L49-L75
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_press
static void imu_controller_press(ImuController* controller, InputKey key) { if(controller->button_press_tick[key]) { // If the button was already pressed, check if we need to send a InputTypeLong or InputTypeRepeat event. uint32_t duration = furi_get_tick() - controller->button_press_tick[key]; // If the button was pressed for a long time, send a InputTypeLong event. if(controller->config->button_state_long_ms && (controller->button_state[key] == ButtonStatePressed && duration >= controller->config->button_state_long_ms)) { // Send a InputTypeLong event controller->queue_message(controller->context, InputTypeLong, key); // Update the button state controller->button_press_tick[key] = furi_get_tick(); controller->button_state[key] = ButtonStateLongPressed; } // If we already sent a InputTypeLong, check if we need to send a InputTypeRepeat event. else if( controller->config->button_state_repeat_ms && (controller->button_state[key] >= ButtonStateLongPressed && duration > controller->config->button_state_repeat_ms)) { // Send a InputTypeRepeat event controller->queue_message(controller->context, InputTypeRepeat, key); // Update the button state controller->button_press_tick[key] = furi_get_tick(); controller->button_state[key] = ButtonStateRepeatPressed; } return; } if(controller->config->vibro_duration) { furi_hal_vibro_on(true); } // Release the button in the opposite direction switch(key) { case InputKeyUp: imu_controller_release(controller, InputKeyDown); break; case InputKeyDown: imu_controller_release(controller, InputKeyUp); break; case InputKeyLeft: imu_controller_release(controller, InputKeyRight); break; case InputKeyRight: imu_controller_release(controller, InputKeyLeft); break; default: break; } // Send a InputTypePress event controller->queue_message(controller->context, InputTypePress, key); // Update the button state controller->button_press_tick[key] = furi_get_tick(); controller->button_state[key] = ButtonStatePressed; if(controller->config->vibro_duration) { furi_delay_ms(controller->config->vibro_duration); furi_hal_vibro_on(false); } }
/** * @brief Press a virtual button * @param controller The controller * @param key The key */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L82-L145
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_callback
static void imu_controller_callback(void* context) { ImuController* imu_controller = (ImuController*)context; // Acquire the mutex to access the IMU furi_mutex_acquire(imu_controller->mutex, FuriWaitForever); if(imu_present(imu_controller->imu)) { // Get the roll (up/down) float roll = imu_roll_get(imu_controller->imu); if(roll > imu_controller->config->roll_up) { imu_controller_press(imu_controller, InputKeyUp); } else if(roll < imu_controller->config->roll_down) { imu_controller_press(imu_controller, InputKeyDown); } // If the roll is outside the hysteresis range, release the up and down buttons else if( roll < imu_controller->config->roll_up - imu_controller->config->roll_hysteresis && roll > imu_controller->config->roll_down + imu_controller->config->roll_hysteresis) { imu_controller_release(imu_controller, InputKeyUp); imu_controller_release(imu_controller, InputKeyDown); } // Get the pitch (left/right) float pitch = imu_pitch_get(imu_controller->imu); if(pitch > imu_controller->config->pitch_left) { imu_controller_press(imu_controller, InputKeyLeft); } else if(pitch < imu_controller->config->pitch_right) { imu_controller_press(imu_controller, InputKeyRight); } // If the pitch is outside the hysteresis range, release the left and right buttons else if( pitch < imu_controller->config->pitch_left - imu_controller->config->pitch_hysteresis && pitch > imu_controller->config->pitch_right + imu_controller->config->pitch_hysteresis) { imu_controller_release(imu_controller, InputKeyLeft); imu_controller_release(imu_controller, InputKeyRight); } } // Release the mutex, so other threads can access the IMU furi_mutex_release(imu_controller->mutex); }
/** * @brief IMU controller callback * @details This function is called periodically to check the IMU orientation and send virtual button events. * @param context The context */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L152-L192
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_release_buttons
static void imu_controller_release_buttons(void* context) { ImuController* imu_controller = (ImuController*)context; imu_controller_release(imu_controller, InputKeyUp); imu_controller_release(imu_controller, InputKeyDown); imu_controller_release(imu_controller, InputKeyLeft); imu_controller_release(imu_controller, InputKeyRight); }
/** * @brief Release all virtual buttons * @param context The context */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L198-L204
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_free
void imu_controller_free(ImuController* imu_controller) { furi_timer_stop(imu_controller->timer); furi_timer_free(imu_controller->timer); imu_controller_release_buttons(imu_controller); imu_free(imu_controller->imu); furi_mutex_free(imu_controller->mutex); free(imu_controller); }
/** * @brief Free the IMU controller * @param imu_controller The IMU controller */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L233-L240
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_start
void imu_controller_start(ImuController* imu_controller) { furi_timer_start( imu_controller->timer, furi_kernel_get_tick_frequency() / BUTTON_READINGS_PER_SECOND); }
/** * @brief Start the IMU controller * @details This function starts the IMU controller, which will periodically check the IMU orientation and send virtual button events. * @param imu_controller The IMU controller */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L247-L250
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_stop
void imu_controller_stop(ImuController* imu_controller) { furi_timer_stop(imu_controller->timer); }
/** * @brief Stop the IMU controller * @details This function stops the IMU controller, which will stop checking the IMU orientation and sending virtual button events. * @param imu_controller The IMU controller */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L257-L259
89716a9b00eacce7055a75fddb5a3adde93f265f
flipper-zero-tutorials
github_2023
jamisonderek
c
imu_controller_recalibrate
void imu_controller_recalibrate(ImuController* imu_controller) { imu_controller_stop(imu_controller); furi_mutex_acquire(imu_controller->mutex, FuriWaitForever); imu_free(imu_controller->imu); imu_controller->imu = imu_alloc(); furi_mutex_release(imu_controller->mutex); imu_controller_start(imu_controller); }
/** * @brief Recalibrate the IMU controller * @details This function stops the IMU controller, recalibrates the IMU and starts the IMU controller again. * @param imu_controller The IMU controller */
https://github.com/jamisonderek/flipper-zero-tutorials/blob/89716a9b00eacce7055a75fddb5a3adde93f265f/vgm/imu_controller/imu_controller.c#L266-L273
89716a9b00eacce7055a75fddb5a3adde93f265f
SBEMU
github_2023
crazii
c
MAIN_InterruptPM
static void MAIN_InterruptPM() { const uint8_t irq = PIC_GetIRQ(); if(irq != aui.card_irq) //shared IRQ handled by other handlers(EOI sent) or new irq arrived after EOI but not for us return; //if(MAIN_InINT&MAIN_ININT_PM) return; //skip reentrance. go32 will do this so actually we don't need it //DBG_Log("INTPM %d\n", MAIN_InINT); MAIN_InINT |= MAIN_ININT_PM; //note: we have full control of the calling chain, if the irq belongs to the sound card, //we send EOI and skip calling the chain - it will be a little faster. if other devices raises irq at the same time, //the interrupt handler will entered again (not nested) so won't be a problem. //also we send EOI on our own and terminate, this doesn't rely on the default implementation in IVT - some platform (i.e. VirtualBox) //don't send EOI on default handler in IVT. // //it has one problem that if other drivers (shared IRQ) enables interrupts (because it needs wait or is time consuming) //then because we're still in MAIN_InterruptPM, so MAIN_InterruptPM is never entered again (guarded by go32 or MAIN_ININT_PM), //so the newly coming irq will never be processed and the IRQ will flood the system (freeze) //an alternative chained methods will EXIT MAIN_InterruptPM FIRST and calls next handler, which will avoid this case, see @MAIN_ISR_CHAINED //but we need a hack if the default handler in IVT doesn't send EOI or masks the irq - this is done in the RM final wrapper, see @DPMI_RMISR_ChainedWrapper //MAIN_IntContext.EFLAGS |= (MAIN_InINT&MAIN_ININT_RM) ? (MAIN_IntContext.EFLAGS&CPU_VMFLAG) : 0; HDPMIPT_GetInterrupContext(&MAIN_IntContext); if(/*!(MAIN_InINT&MAIN_ININT_RM) && */aui.card_handler->irq_routine && aui.card_handler->irq_routine(&aui)) //check if the irq belong the sound card { MAIN_Interrupt(); PIC_SendEOIWithIRQ(aui.card_irq); //some BIOS driver doesn't works well if not sending EOI, there's extra check for EOI in DPMI_RMISR_ChainedWrapper } #if !MAIN_ISR_CHAINED else { if(/*(MAIN_InINT&MAIN_ININT_RM) || */(MAIN_IntContext.EFLAGS&CPU_VMFLAG)) DPMI_CallOldISR(&MAIN_IntHandlePM); else DPMI_CallOldISRWithContext(&MAIN_IntHandlePM, &MAIN_IntContext.regs); PIC_UnmaskIRQ(aui.card_irq); } #endif //DBG_Log("INTPME %d\n", MAIN_InINT); MAIN_InINT &= ~MAIN_ININT_PM; }
//with the modified fork of HDPMI, HDPMI will route PM interrupts to IVT. //IRQ routing path: //PM: IDT -> PM handlers after SBEMU -> SBEMU MAIN_InterruptPM(*) -> PM handlers befoe SBEMU -> IVT -> SBEMU MAIN_InterruptRM(*) -> DPMI entrance -> IVT handlers before DPMI installed //RM: IVT -> RM handlers before SBEMU -> SBEMU MAIN_InterruptRM(*) -> RM handlers after SBEMU -> DPMI entrance -> PM handlers after SBEMU -> SBEMU MAIN_InterruptPM(*) -> PM handlers befoe SBEMU -> IVT handlers before DPMI installed //(*) means SBEMU might early terminate the calling chain if sound irq is handled (when MAIN_ISR_CHAINED==0). //early terminating is OK because PCI irq are level triggered, IRQ signal will keep high (raised) unless the hardware IRQ is ACKed.
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/main.c#L1084-L1125
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
setenv
int setenv(const char *name, const char *value, int rewrite) { int namelen; int vallen; if(name == NULL || value == NULL || (namelen=strlen(name)) == 0 || (vallen=strlen(value)) == 0) return -1; //find PSP of COMMAND.COM uint32_t psp = 0; uint32_t parent = 0; { DPMI_REG r = {0}; r.h.ah = 0x62; DPMI_CallRealModeINT(0x21, &r); parent = psp = r.w.bx; } do { psp = parent; //printf("PSP:%x\n",psp); parent = DPMI_LoadW((psp<<4)+0x16); }while(parent != psp); uint16_t env = DPMI_LoadW((parent<<4)+0x2C); uint16_t mcb = env - 1; uint16_t size = DPMI_LoadW((mcb<<4) + 0x03) << 4; //printf("size:%d\n",size); char* buf = (char*)malloc(size+namelen+1+vallen+1); memset(buf, 0, size+namelen+1+vallen+1); DPMI_CopyLinear(DPMI_PTR2L(buf), env<<4, size); char* s; s = buf; do { #if DEBUG && 0 s += printf("%s\n", s); #else s += strlen(s) + 1; #endif }while(*s); if((s-buf+1) + (namelen+1)+1+(vallen+1) > size) //not enough space. TODO: allocate new { free(buf); return -1; } s = buf; do { int len = strlen(s); if(memicmp(s, name, namelen) == 0 && s[namelen] == '=') { if(rewrite) { memmove(s, s+len+1, size-(s-buf+len+1)); if(!*s) break; //bugfix (exposed in FreeDOS) len = strlen(s); } else { free(buf); return -1; } } s += len+1; }while(*s); *(s + sprintf(s, "%s=%s", name, value)+1)='\0'; //size = namelen + vallen + 3; #if DEBUG && 0 s = buf; do { s += printf("%s\n", s); }while(*s); #endif //DPMI_StoreW((mcb<<4), (size+15)>>4); DPMI_CopyLinear(env<<4, DPMI_PTR2L(buf), size); free(buf); return 0; }
// http://www.techhelpmanual.com/346-dos_environment.html
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/utility.c#L7-L91
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_als4000_configure2
static void snd_als4000_configure2(struct snd_sb *chip) { u8 tmp; int i; /* do some more configuration */ spin_lock_irq(&chip->mixer_lock); tmp = snd_als4_cr_read(chip, ALS4K_CR0_SB_CONFIG); snd_als4_cr_write(chip, ALS4K_CR0_SB_CONFIG, tmp|ALS4K_CR0_MX80_81_REG_WRITE_ENABLE); /* always select DMA channel 0, since we do not actually use DMA * SPECS_PAGE: 19/20 */ snd_sbmixer_write(chip, SB_DSP4_DMASETUP, SB_DMASETUP_DMA0); // CR0 set to IRQ controlled mode //snd_sbmixer_write(chip, 0x80, 0); //snd_sbmixer_write(chip, 0x80, 2); //snd_sbmixer_write(chip, 0x80, 0); // XXX snd_als4_cr_write(chip, ALS4K_CR0_SB_CONFIG, tmp & ~ALS4K_CR0_MX80_81_REG_WRITE_ENABLE); spin_unlock_irq(&chip->mixer_lock); spin_lock_irq(&chip->reg_lock); /* enable interrupts */ // Version 3(ALS200/ALS110//ALS4000/ALS120) FIFO controlled continuous DMA mode snd_als4k_gcr_write(chip, ALS4K_GCR8C_MISC_CTRL, (3<<16) | ALS4K_GCR8C_IRQ_MASK_CTRL_ENABLE); #if 0 /* SPECS_PAGE: 39 */ for (i = ALS4K_GCR91_DMA0_ADDR; i <= ALS4K_GCR96_DMA3_MODE_COUNT; ++i) snd_als4k_gcr_write(chip, i, 0); #endif /* enable burst mode to prevent dropouts during high PCI bus usage */ snd_als4k_gcr_write(chip, ALS4K_GCR99_DMA_EMULATION_CTRL, (snd_als4k_gcr_read(chip, ALS4K_GCR99_DMA_EMULATION_CTRL) & ~0x07) | 0x04); //snd_als4k_gcr_write(chip, ALS4K_GCR99_DMA_EMULATION_CTRL, // (snd_als4k_gcr_read(chip, ALS4K_GCR99_DMA_EMULATION_CTRL)) | 0x100); // from OSS driver spin_unlock_irq(&chip->reg_lock); als4000_mixer_init(chip); }
// Need to call this after playback_trigger, or else PCM interrupts do not fire and FM sound volume is extremely low
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/als4000.c#L293-L332
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_als4000_interrupt
irqreturn_t snd_als4000_interrupt(int irq, void *dev_id) { struct snd_sb *chip = dev_id; uint8_t pci_irqstatus; uint8_t sb_irqstatus; //snd_als4k_gcr_write(chip, ALS4K_GCR8C_MISC_CTRL, (3<<16) | 0); // Mask INTA# output /* find out which bit of the ALS4000 PCI block produced the interrupt, SPECS_PAGE: 38, 5 */ pci_irqstatus = snd_als4k_iobase_readb(chip->alt_port, ALS4K_IOB_0E_IRQTYPE_SB_CR1E_MPU); bool handled = false; if ((pci_irqstatus & ALS4K_IOB_0E_SB_DMA_IRQ)) handled = true; #if 0 if ((pci_irqstatus & ALS4K_IOB_0E_SB_DMA_IRQ) && (chip->playback_substream)) /* playback */ snd_pcm_period_elapsed(chip->playback_substream); if ((pci_irqstatus & ALS4K_IOB_0E_CR1E_IRQ) && (chip->capture_substream)) /* capturing */ snd_pcm_period_elapsed(chip->capture_substream); if ((pci_irqstatus & ALS4K_IOB_0E_MPU_IRQ) && (chip->rmidi)) /* MPU401 interrupt */ snd_mpu401_uart_interrupt(irq, chip->rmidi->private_data); #endif if ((pci_irqstatus & ALS4K_IOB_0E_MPU_IRQ)) { uint8_t midi_in_data = snd_als4k_iobase_readb(chip->alt_port, ALS4K_IOB_30_MIDI_DATA); //printk("uartint %2.2X\n", midi_in_data); handled = true; } /* ACK the PCI block IRQ */ // -> Except for the SB IRQ since they are acknowledged below -> ??? //if (pci_irqstatus & ~ALS4K_IOB_0E_SB_DMA_IRQ) snd_als4k_iobase_writeb(chip->alt_port, ALS4K_IOB_0E_IRQTYPE_SB_CR1E_MPU, pci_irqstatus & ~ALS4K_IOB_0E_SB_DMA_IRQ); snd_als4k_iobase_writeb(chip->alt_port, ALS4K_IOB_0E_IRQTYPE_SB_CR1E_MPU, pci_irqstatus); if (!handled) goto done; spin_lock(&chip->mixer_lock); /* SPECS_PAGE: 20 */ sb_irqstatus = snd_sbmixer_read(chip, SB_DSP4_IRQSTATUS); spin_unlock(&chip->mixer_lock); if (sb_irqstatus & SB_IRQTYPE_8BIT) { snd_sb_ack_8bit(chip); } if (sb_irqstatus & SB_IRQTYPE_16BIT) { snd_sb_ack_16bit(chip); } if (sb_irqstatus & SB_IRQTYPE_MPUIN) { // chip->mpu_port is not used //inb(chip->mpu_port); uint8_t midi_in_data = snd_als4k_iobase_readb(chip->alt_port, ALS4K_IOB_30_MIDI_DATA); //printk("mpuin %2.2X\n", midi_in_data); } if (sb_irqstatus & ALS4K_IRQTYPE_CR1E_DMA) { //snd_sb_ack_CR1E(chip); snd_als4k_iobase_readb(chip->alt_port, ALS4K_IOB_16_ACK_FOR_CR1E); } //if (pci_irqstatus != 0x80 || sb_irqstatus != 0x02) printk("irq 0x%2.2X 0x%2.2X\n", pci_irqstatus, sb_irqstatus); /* dev_dbg(chip->card->dev, "als4000: irq 0x%04x 0x%04x\n", pci_irqstatus, sb_irqstatus); */ #if 0 bool handled = (pci_irqstatus & (ALS4K_IOB_0E_SB_DMA_IRQ|ALS4K_IOB_0E_CR1E_IRQ| ALS4K_IOB_0E_MPU_IRQ)) || (sb_irqstatus & (SB_IRQTYPE_8BIT|SB_IRQTYPE_16BIT| SB_IRQTYPE_MPUIN|ALS4K_IRQTYPE_CR1E_DMA)); #endif done: //snd_als4k_gcr_write(chip, ALS4K_GCR8C_MISC_CTRL, (3<<16) | ALS4K_GCR8C_IRQ_MASK_CTRL_ENABLE); // Enable INTA# output again /* only ack the things we actually handled above */ return IRQ_RETVAL(handled); }
/* FIXME: this IRQ routine doesn't really support IRQ sharing (we always * return IRQ_HANDLED no matter whether we actually had an IRQ flag or not). * ALS4000a.PDF writes that while ACKing IRQ in PCI block will *not* ACK * the IRQ in the SB core, ACKing IRQ in SB block *will* ACK the PCI IRQ * register (alt_port + ALS4K_IOB_0E_IRQTYPE_SB_CR1E_MPU). Probably something * could be optimized here to query/write one register only... * And even if both registers need to be queried, then there's still the * question of whether it's actually correct to ACK PCI IRQ before reading * SB IRQ like we do now, since ALS4000a.PDF mentions that PCI IRQ will *clear* * SB IRQ status. * (hmm, SPECS_PAGE: 38 mentions it the other way around!) * And do we *really* need the lock here for *reading* SB_DSP4_IRQSTATUS?? * */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/als4000.c#L400-L475
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_als4000_playback_open
int snd_als4000_playback_open(struct snd_pcm_substream *substream) { struct snd_sb *chip = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; chip->playback_substream = substream; runtime->hw = snd_als4000_playback; return 0; }
/*****************************************************************/
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/als4000.c#L531-L539
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_als4000_set_addr
static void snd_als4000_set_addr(unsigned long iobase, unsigned int sb_io, unsigned int mpu_io, unsigned int opl_io, unsigned int game_io) { u32 cfg1 = 0; u32 cfg2 = 0; if (mpu_io > 0) cfg2 |= (mpu_io | 1) << 16; if (sb_io > 0) cfg2 |= (sb_io | 1); if (game_io > 0) cfg1 |= (game_io | 1) << 16; if (opl_io > 0) cfg1 |= (opl_io | 1); snd_als4k_gcr_write_addr(iobase, ALS4K_GCRA8_LEGACY_CFG1, cfg1); snd_als4k_gcr_write_addr(iobase, ALS4K_GCRA9_LEGACY_CFG2, cfg2); }
/******************************************************************/
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/als4000.c#L612-L631
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sbdsp_command
int snd_sbdsp_command(struct snd_sb *chip, unsigned char val) { int i; #ifdef IO_DEBUG snd_printk(KERN_DEBUG "command (%X) 0x%x\n", chip->port, val); #endif for (i = BUSY_LOOPS; i; i--) if ((inb(SBP(chip, STATUS)) & 0x80) == 0) { outb(val, SBP(chip, COMMAND)); return 1; } snd_printd("%s [0x%lx]: timeout (0x%x)\n", __func__, chip->port, val); return 0; }
//#define IO_DEBUG 1
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_common.c#L31-L44
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sbmixer_write
void snd_sbmixer_write(struct snd_sb *chip, unsigned char reg, unsigned char data) { outb(reg, SBP(chip, MIXER_ADDR)); udelay(10); outb(data, SBP(chip, MIXER_DATA)); udelay(10); #ifdef IO_DEBUG snd_printk(KERN_DEBUG "mixer_write (%X) 0x%x 0x%x\n", chip->port, reg, data); #endif }
//#define IO_DEBUG 1
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L17-L26
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sbmixer_info_single
static int snd_sbmixer_info_single(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { int mask = (kcontrol->private_value >> 24) & 0xff; uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 1; uinfo->value.integer.min = 0; uinfo->value.integer.max = mask; return 0; }
/* * Single channel mixer element */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L48-L57
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sbmixer_info_double
static int snd_sbmixer_info_double(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { int mask = (kcontrol->private_value >> 24) & 0xff; uinfo->type = mask == 1 ? SNDRV_CTL_ELEM_TYPE_BOOLEAN : SNDRV_CTL_ELEM_TYPE_INTEGER; uinfo->count = 2; uinfo->value.integer.min = 0; uinfo->value.integer.max = mask; return 0; }
/* * Double channel mixer element */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L100-L109
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_dt019x_input_sw_info
static int snd_dt019x_input_sw_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static const char * const texts[5] = { "CD", "Mic", "Line", "Synth", "Master" }; return snd_ctl_enum_info(uinfo, 1, 5, texts); }
/* * DT-019x / ALS-007 capture/input switch */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L171-L178
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_als4k_mono_capture_route_info
static int snd_als4k_mono_capture_route_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static const char * const texts[3] = { "L chan only", "R chan only", "L ch/2 + R ch/2" }; return snd_ctl_enum_info(uinfo, 1, 3, texts); }
/* * ALS4000 mono recording control switch */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L257-L265
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sb8mixer_info_mux
static int snd_sb8mixer_info_mux(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { static const char * const texts[3] = { "Mic", "CD", "Line" }; return snd_ctl_enum_info(uinfo, 1, 3, texts); }
/* * SBPRO input multiplexer */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L311-L318
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sb16mixer_info_input_sw
static int snd_sb16mixer_info_input_sw(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN; uinfo->count = 4; uinfo->value.integer.min = 0; uinfo->value.integer.max = 1; return 0; }
/* * SB16 input switch */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L378-L385
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
snd_sbmixer_add_ctl
int snd_sbmixer_add_ctl(struct snd_sb *chip, const char *name, int index, int type, unsigned long value) { static const struct snd_kcontrol_new newctls[] = { [SB_MIX_SINGLE] = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = snd_sbmixer_info_single, .get = snd_sbmixer_get_single, .put = snd_sbmixer_put_single, }, [SB_MIX_DOUBLE] = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = snd_sbmixer_info_double, .get = snd_sbmixer_get_double, .put = snd_sbmixer_put_double, }, [SB_MIX_INPUT_SW] = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = snd_sb16mixer_info_input_sw, .get = snd_sb16mixer_get_input_sw, .put = snd_sb16mixer_put_input_sw, }, [SB_MIX_CAPTURE_PRO] = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = snd_sb8mixer_info_mux, .get = snd_sb8mixer_get_mux, .put = snd_sb8mixer_put_mux, }, [SB_MIX_CAPTURE_DT019X] = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = snd_dt019x_input_sw_info, .get = snd_dt019x_input_sw_get, .put = snd_dt019x_input_sw_put, }, [SB_MIX_MONO_CAPTURE_ALS4K] = { .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .info = snd_als4k_mono_capture_route_info, .get = snd_als4k_mono_capture_route_get, .put = snd_als4k_mono_capture_route_put, }, }; struct snd_kcontrol *ctl; int err; ctl = snd_ctl_new1(&newctls[type], chip); if (! ctl) return -ENOMEM; strscpy(ctl->id.name, name, sizeof(ctl->id.name)); ctl->id.index = index; ctl->private_value = value; err = snd_ctl_add(chip->card, ctl); if (err < 0) return err; return 0; }
/* */ /* */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/als4000/sb_mixer.c#L442-L495
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
amixer_set_y
static int amixer_set_y(struct amixer *amixer, unsigned int y) { struct hw *hw; hw = amixer->rsc.hw; hw->amixer_set_y(amixer->rsc.ctrl_blk, y); return 0; }
/* y is a 14-bit immediate constant */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctamixer.c#L71-L79
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
sum_master
static void sum_master(struct rsc *rsc) { rsc->conj = 0; rsc->idx = container_of(rsc, struct sum, rsc)->idx[0]; }
/* SUM resource management */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctamixer.c#L333-L337
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
ct_map_audio_buffer
static int ct_map_audio_buffer(struct ct_atc *atc, struct ct_atc_pcm *apcm) { struct snd_pcm_runtime *runtime; struct ct_vm *vm; if (!apcm->substream) return 0; runtime = apcm->substream->runtime; vm = atc->vm; apcm->vm_block = vm->map(vm, apcm->substream, runtime->dma_bytes); if (!apcm->vm_block) return -ENOENT; return 0; }
/* * * Only mono and interleaved modes are supported now. * Always allocates a contiguous channel block. * */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctatc.c#L140-L157
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
ct_atc_create
int ct_atc_create(struct snd_card *card, struct pci_dev *pci, unsigned int rsr, unsigned int msr, int chip_type, unsigned int ssid, struct ct_atc **ratc) { struct ct_atc *atc; static const struct snd_device_ops ops = { .dev_free = atc_dev_free, }; int err; *ratc = NULL; atc = kzalloc(sizeof(*atc), GFP_KERNEL); if (!atc) return -ENOMEM; /* Set operations */ *atc = atc_preset; atc->card = card; atc->pci = pci; atc->rsr = rsr; atc->msr = msr; atc->chip_type = chip_type; mutex_init(&atc->atc_mutex); /* Find card model */ err = atc_identify_card(atc, ssid); if (err < 0) { dev_err(card->dev, "ctatc: Card not recognised\n"); goto error1; } /* Set up device virtual memory management object */ err = ct_vm_create(&atc->vm, pci); if (err < 0) { dev_err(card->dev, "ctatc: vm error\n"); goto error1; } /* Create all atc hw devices */ err = atc_create_hw_devs(atc); if (err < 0) goto error1; err = ct_mixer_create(atc, (struct ct_mixer **)&atc->mixer); if (err) { dev_err(card->dev, "Failed to create mixer obj!!!\n"); goto error1; } /* Get resources */ err = atc_get_resources(atc); if (err < 0) { dev_err(card->dev, "ctatc: resources error\n"); goto error1; } /* Build topology */ atc_connect_resources(atc); atc->timer = ct_timer_new(atc); if (!atc->timer) { err = -ENOMEM; dev_err(card->dev, "ctatc: timer error\n"); goto error1; } #if 0 err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, atc, &ops); if (err < 0) goto error1; #endif *ratc = atc; return 0; error1: ct_atc_destroy(atc); dev_err(card->dev, "Something wrong!!!\n"); return err; }
/** * ct_atc_create - create and initialize a hardware manager * @card: corresponding alsa card object * @pci: corresponding kernel pci device object * @rsr: reference sampling rate * @msr: master sampling rate * @chip_type: CHIPTYP enum values * @ssid: vendor ID (upper 16 bits) and device ID (lower 16 bits) * @ratc: return created object address in it * * Creates and initializes a hardware manager. * * Creates kmallocated ct_atc structure. Initializes hardware. * Returns 0 if succeeds, or negative error code if fails. */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctatc.c#L1698-L1780
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
create_hw_obj
int create_hw_obj(struct pci_dev *pci, enum CHIPTYP chip_type, enum CTCARDS model, struct hw **rhw) { int err; switch (chip_type) { case ATC20K1: err = create_20k1_hw_obj(rhw); break; case ATC20K2: err = create_20k2_hw_obj(rhw); break; default: err = -ENODEV; break; } if (err) return err; (*rhw)->pci = pci; (*rhw)->chip_type = chip_type; (*rhw)->model = model; return 0; }
//#include <linux/bug.h>
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthardware.c#L19-L43
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
src_get_rsc_ctrl_blk
static int src_get_rsc_ctrl_blk(void **rblk) { struct src_rsc_ctrl_blk *blk; *rblk = NULL; blk = kzalloc(sizeof(*blk), GFP_KERNEL); if (!blk) return -ENOMEM; *rblk = blk; return 0; }
/* * Function implementation block. */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k1.c#L155-L167
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
set_timer_irq
static int set_timer_irq(struct hw *hw, int enable) { hw_write_20kx(hw, GIE, enable ? IT_INT : 0); return 0; }
/* Timer interrupt */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k1.c#L1165-L1169
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
hw_trn_init
static int hw_trn_init(struct hw *hw, const struct trn_conf *info) { u32 trnctl; u32 ptp_phys_low, ptp_phys_high; /* Set up device page table */ if ((~0UL) == info->vm_pgt_phys) { dev_err(hw->card->dev, "Wrong device page table page address!\n"); return -1; } trnctl = 0x13; /* 32-bit, 4k-size page */ ptp_phys_low = (u32)info->vm_pgt_phys; ptp_phys_high = 0; //assumes 32-bit system upper_32_bits(info->vm_pgt_phys); if (sizeof(void *) == 8) /* 64bit address */ trnctl |= (1 << 2); #if 0 /* Only 4k h/w pages for simplicitiy */ #if PAGE_SIZE == 8192 trnctl |= (1<<5); #endif #endif hw_write_20kx(hw, PTPALX, ptp_phys_low); hw_write_20kx(hw, PTPAHX, ptp_phys_high); hw_write_20kx(hw, TRNCTL, trnctl); hw_write_20kx(hw, TRNIS, 0x200c01); /* really needed? */ return 0; }
/* TRANSPORT operations */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k1.c#L1254-L1282
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
hw_reset_dac
static int hw_reset_dac(struct hw *hw) { u32 i; u16 gpioorg; unsigned int ret; if (i2c_unlock(hw)) return -1; do { ret = hw_read_pci(hw, 0xEC); } while (!(ret & 0x800000)); hw_write_pci(hw, 0xEC, 0x05); /* write to i2c status control */ /* To be effective, need to reset the DAC twice. */ for (i = 0; i < 2; i++) { /* set gpio */ msleep(100); gpioorg = (u16)hw_read_20kx(hw, GPIO); gpioorg &= 0xfffd; hw_write_20kx(hw, GPIO, gpioorg); mdelay(1); hw_write_20kx(hw, GPIO, gpioorg | 0x2); } i2c_write(hw, 0x00180080, 0x01, 0x80); i2c_write(hw, 0x00180080, 0x02, 0x10); i2c_lock(hw); return 0; }
/* DAC operations */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k1.c#L1390-L1421
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
is_adc_input_selected_SB055x
static int is_adc_input_selected_SB055x(struct hw *hw, enum ADCSRC type) { return 0; }
/* ADC operations */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k1.c#L1485-L1488
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
src_get_rsc_ctrl_blk
static int src_get_rsc_ctrl_blk(void **rblk) { struct src_rsc_ctrl_blk *blk; *rblk = NULL; blk = kzalloc(sizeof(*blk), GFP_KERNEL); if (!blk) return -ENOMEM; *rblk = blk; return 0; }
/* * Function implementation block. */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k2.c#L155-L167
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
set_timer_irq
static int set_timer_irq(struct hw *hw, int enable) { hw_write_20kx(hw, GIE, enable ? IT_INT : 0); return 0; }
/* Timer interrupt */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k2.c#L1108-L1112
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
hw_trn_init
static int hw_trn_init(struct hw *hw, const struct trn_conf *info) { u32 vmctl, data; u32 ptp_phys_low, ptp_phys_high; int i; /* Set up device page table */ if ((~0UL) == info->vm_pgt_phys) { dev_alert(hw->card->dev, "Wrong device page table page address!!!\n"); return -1; } vmctl = 0x80000C0F; /* 32-bit, 4k-size page */ ptp_phys_low = (u32)info->vm_pgt_phys; ptp_phys_high = 0; // assumes 32-bit upper_32_bits(info->vm_pgt_phys); if (sizeof(void *) == 8) /* 64bit address */ vmctl |= (3 << 8); /* Write page table physical address to all PTPAL registers */ for (i = 0; i < 64; i++) { hw_write_20kx(hw, VMEM_PTPAL+(16*i), ptp_phys_low); hw_write_20kx(hw, VMEM_PTPAH+(16*i), ptp_phys_high); } /* Enable virtual memory transfer */ hw_write_20kx(hw, VMEM_CTL, vmctl); /* Enable transport bus master and queueing of request */ hw_write_20kx(hw, TRANSPORT_CTL, 0x03); hw_write_20kx(hw, TRANSPORT_INT, 0x200c01); /* Enable transport ring */ data = hw_read_20kx(hw, TRANSPORT_ENB); hw_write_20kx(hw, TRANSPORT_ENB, (data | 0x03)); return 0; }
/* TRANSPORT operations */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/cthw20k2.c#L1232-L1265
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
uint16_to_float14
static unsigned int uint16_to_float14(unsigned int x) { unsigned int i; if (x < 17) return 0; x *= 2031; x /= 65535; x += 16; /* i <= 6 */ for (i = 0; !(x & 0x400); i++) x <<= 1; x = (((7 - i) & 0x7) << 10) | (x & 0x3ff); return x; }
/* Map integer value ranging from 0 to 65535 to 14-bit float value ranging * from 2^-6 to (1+1023/1024) */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctmixer.c#L286-L304
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
ct_pcm_playback_open
int ct_pcm_playback_open(struct snd_pcm_substream *substream) { struct ct_atc *atc = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; struct ct_atc_pcm *apcm; int err; apcm = kzalloc(sizeof(*apcm), GFP_KERNEL); if (!apcm) return -ENOMEM; apcm->substream = substream; apcm->interrupt = ct_atc_pcm_interrupt; if (IEC958 == substream->pcm->device) { runtime->hw = ct_spdif_passthru_playback_hw; atc->spdif_out_passthru(atc, 1); } else { runtime->hw = ct_pcm_playback_hw; if (FRONT == substream->pcm->device) runtime->hw.channels_max = 8; } #if 0 // XXX err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); if (err < 0) goto free_pcm; err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 1024, UINT_MAX); if (err < 0) goto free_pcm; #endif apcm->timer = ct_timer_instance_new(atc->timer, apcm); if (!apcm->timer) { err = -ENOMEM; goto free_pcm; } runtime->private_data = apcm; runtime->private_free = ct_atc_pcm_free_substream; return 0; free_pcm: kfree(apcm); return err; }
/* pcm playback operations */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctpcm.c#L118-L166
f0cbde063396deb2c1246c9b3108a37755c68e9a
SBEMU
github_2023
crazii
c
ct_pcm_capture_open
static int ct_pcm_capture_open(struct snd_pcm_substream *substream) { struct ct_atc *atc = snd_pcm_substream_chip(substream); struct snd_pcm_runtime *runtime = substream->runtime; struct ct_atc_pcm *apcm; int err; apcm = kzalloc(sizeof(*apcm), GFP_KERNEL); if (!apcm) return -ENOMEM; apcm->started = 0; apcm->substream = substream; apcm->interrupt = ct_atc_pcm_interrupt; runtime->hw = ct_pcm_capture_hw; runtime->hw.rate_max = atc->rsr * atc->msr; #if 0 // XXX err = snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS); if (err < 0) goto free_pcm; err = snd_pcm_hw_constraint_minmax(runtime, SNDRV_PCM_HW_PARAM_BUFFER_BYTES, 1024, UINT_MAX); if (err < 0) goto free_pcm; #endif apcm->timer = ct_timer_instance_new(atc->timer, apcm); if (!apcm->timer) { err = -ENOMEM; goto free_pcm; } runtime->private_data = apcm; runtime->private_free = ct_atc_pcm_free_substream; return 0; free_pcm: kfree(apcm); return err; }
/* pcm capture operations */
https://github.com/crazii/SBEMU/blob/f0cbde063396deb2c1246c9b3108a37755c68e9a/drivers/ctxfi/ctpcm.c#L268-L311
f0cbde063396deb2c1246c9b3108a37755c68e9a