1 /*
2  * Copyright (c) 2023 Raspberry Pi (Trading) Ltd.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include "btstack_config.h"
8 
9 #ifdef HAVE_BTSTACK_STDIN
10 
11 #include "btstack_stdin.h"
12 #include "btstack_run_loop.h"
13 #include "pico/stdio.h"
14 
15 static btstack_data_source_t stdin_data_source;
16 static void (*stdin_handler)(char c);
17 
18 // Data source callback, return any character received
btstack_stdin_process(__unused struct btstack_data_source * ds,__unused btstack_data_source_callback_type_t callback_type)19 static void btstack_stdin_process(__unused struct btstack_data_source *ds, __unused btstack_data_source_callback_type_t callback_type){
20     if (stdin_handler) {
21         while(true) {
22             int c = getchar_timeout_us(0);
23             if (c == PICO_ERROR_TIMEOUT) return;
24             (*stdin_handler)(c);
25         }
26     }
27 }
28 
on_chars_available_callback(__unused void * param)29 void on_chars_available_callback(__unused void *param) {
30     btstack_run_loop_poll_data_sources_from_irq();
31 }
32 
33 // Test code calls this if HAVE_BTSTACK_STDIN is defined and it wants key presses
btstack_stdin_setup(void (* handler)(char c))34 void btstack_stdin_setup(void (*handler)(char c)) {
35     if (stdin_handler) {
36         return;
37     }
38 
39 	// set handler
40 	stdin_handler = handler;
41 
42 	// set up polling data_source
43 	btstack_run_loop_set_data_source_handler(&stdin_data_source, &btstack_stdin_process);
44 	btstack_run_loop_enable_data_source_callbacks(&stdin_data_source, DATA_SOURCE_CALLBACK_POLL);
45 	btstack_run_loop_add_data_source(&stdin_data_source);
46 
47     stdio_set_chars_available_callback(on_chars_available_callback, NULL);
48 }
49 
50 // Deinit everything
btstack_stdin_reset(void)51 void btstack_stdin_reset(void){
52     if (!stdin_handler) {
53         return;
54     }
55     stdio_set_chars_available_callback(NULL, NULL);
56     stdin_handler = NULL;
57     btstack_run_loop_remove_data_source(&stdin_data_source);
58 }
59 
60 #endif