upython.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <malloc.h>
  2. #include <furi.h>
  3. #include <dialogs/dialogs.h>
  4. #include <storage/storage.h>
  5. #include <mp_flipper_runtime.h>
  6. #include <mp_flipper_compiler.h>
  7. #define TAG "uPython"
  8. static void execute_file(FuriString* file) {
  9. size_t stack;
  10. const char* path = furi_string_get_cstr(file);
  11. FuriString* file_path = furi_string_alloc_printf("%s", path);
  12. do {
  13. FURI_LOG_I(TAG, "executing script %s", path);
  14. const size_t heap_size = memmgr_get_free_heap() * 0.1;
  15. const size_t stack_size = 2 * 1024;
  16. uint8_t* heap = malloc(heap_size * sizeof(uint8_t));
  17. FURI_LOG_D(TAG, "initial heap size is %zu bytes", heap_size);
  18. FURI_LOG_D(TAG, "stack size is %zu bytes", stack_size);
  19. size_t index = furi_string_search_rchar(file_path, '/');
  20. furi_check(index != FURI_STRING_FAILURE);
  21. bool is_py_file = furi_string_end_with_str(file_path, ".py");
  22. furi_string_left(file_path, index);
  23. mp_flipper_set_root_module_path(furi_string_get_cstr(file_path));
  24. mp_flipper_init(heap, heap_size, stack_size, &stack);
  25. if(is_py_file) {
  26. mp_flipper_exec_py_file(path);
  27. } else {
  28. mp_flipper_exec_mpy_file(path);
  29. }
  30. mp_flipper_deinit();
  31. free(heap);
  32. } while(false);
  33. furi_string_free(file_path);
  34. }
  35. static bool select_python_file(FuriString* file_path) {
  36. DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS);
  37. DialogsFileBrowserOptions browser_options;
  38. dialog_file_browser_set_basic_options(&browser_options, "py", NULL);
  39. browser_options.hide_ext = false;
  40. browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX;
  41. bool result = dialog_file_browser_show(dialogs, file_path, file_path, &browser_options);
  42. furi_record_close(RECORD_DIALOGS);
  43. return result;
  44. }
  45. int32_t upython(void* p) {
  46. UNUSED(p);
  47. FuriString* file_path = furi_string_alloc();
  48. if(select_python_file(file_path)) {
  49. execute_file(file_path);
  50. }
  51. furi_string_free(file_path);
  52. return 0;
  53. }