I'm working on a way to execute Python code from a FreeRTOS callback handler. The way I tried to do this is by using the parse_compile_execute function from "lib/utils/pyexec.c" and feeding it a qstr with content like "print(123)".
This does work when the function is called from the main thread in the file "main.c". However, my program gets locked up with a "LoadProhibited" error when I'm calling this function from another source, in my case from a Bluetooth callback handler. Specifically, it panics when executing mp_globals_get() in "runtime.h":130.
Does anyone know why it is not working as if it were called from the "main.c" file? Is there a workaround?
Thanks in advance,
stegomon
Execute Python code from C
Re: Execute Python code from C
To compile and execute code, you need to call these functions.stegomon wrote: ↑Sun May 13, 2018 2:49 pmI'm working on a way to execute Python code from a FreeRTOS callback handler. The way I tried to do this is by using the parse_compile_execute function from "lib/utils/pyexec.c" and feeding it a qstr with content like "print(123)".
This does work when the function is called from the main thread in the file "main.c". However, my program gets locked up with a "LoadProhibited" error when I'm calling this function from another source, in my case from a Bluetooth callback handler. Specifically, it panics when executing mp_globals_get() in "runtime.h":130.
Does anyone know why it is not working as if it were called from the "main.c" file? Is there a workaround?
Thanks in advance,
stegomon
You need to populate first 3 vars with your own values.
Code: Select all
const char* ptr_code;
unsigned int code_length;
bool repl;
bool ret_val = false;
mp_parse_input_kind_t parse_type = MP_PARSE_SINGLE_INPUT;
if (repl == true)
{
parse_type = MP_PARSE_SINGLE_INPUT;
}
else
{
parse_type = MP_PARSE_FILE_INPUT;
}
mp_lexer_t * lex = mp_lexer_new_from_str_len(0, ptr_code, (size_t)code_length, (size_t)0);
mp_parse_tree_t parse_tree = mp_parse(lex, parse_type);
mp_obj_t module_func = mp_compile(&parse_tree, lex->source_name, MP_EMIT_OPT_NONE, repl);
mp_call_function_0(module_func);
Re: Execute Python code from C
mp_parse_compile_execute already does that for the OP so it's unlikely the problem is there.
Rather has something to do with doing this from within a callback.
I don't know anything about FreeRTOS nor how it's threads/callbacks are implemented in MicroPython but if that callback actually runs on a seperate thread or as an interrupt without MicroPython knowing about it, hence without synchronization, there's a data race which needs to be resolved. Possible solutions include: using synchronisation, if available, and/or doing something like setting a flag in the callback and polling that from a loop in the same thread which initialized MicroPython.