mp_flipper_app.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <furi.h>
  2. #include <dialogs/dialogs.h>
  3. #include <storage/storage.h>
  4. #include <port/micropython_embed.h>
  5. #include "mp_flipper_app.h"
  6. const char* root_module_path;
  7. static void load_python_file(FuriString* file_path, FuriString* code) {
  8. Storage* storage = furi_record_open(RECORD_STORAGE);
  9. DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS);
  10. File* file = storage_file_alloc(storage);
  11. DialogsFileBrowserOptions browser_options;
  12. dialog_file_browser_set_basic_options(&browser_options, "py", NULL);
  13. browser_options.hide_ext = false;
  14. browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX;
  15. bool result = dialog_file_browser_show(dialogs, file_path, file_path, &browser_options);
  16. furi_record_close(RECORD_DIALOGS);
  17. if(result) {
  18. result = storage_file_open(file, furi_string_get_cstr(file_path), FSAM_READ, FSOM_OPEN_EXISTING);
  19. }
  20. if(result) {
  21. size_t read = 0;
  22. do {
  23. uint8_t buffer[64] = {'\0'};
  24. read = storage_file_read(file, buffer, sizeof(buffer) - 1);
  25. for(size_t i = 0; i < read; i++) {
  26. furi_string_push_back(code, buffer[i]);
  27. }
  28. } while(read > 0);
  29. furi_string_trim(code);
  30. } else {
  31. furi_string_set(code, "print('it works!')");
  32. }
  33. storage_file_free(file);
  34. furi_record_close(RECORD_STORAGE);
  35. }
  36. int32_t mp_flipper_app(void* p) {
  37. UNUSED(p);
  38. const size_t memory_size = memmgr_get_free_heap() * 0.5;
  39. const size_t stack_size = 2 * 1024;
  40. uint8_t* memory = malloc(memory_size * sizeof(uint8_t));
  41. FURI_LOG_I(TAG, "allocated memory is %zu bytes", memory_size);
  42. FURI_LOG_I(TAG, "stack size is %zu bytes", stack_size);
  43. FuriString* file_path = furi_string_alloc();
  44. FuriString* code = furi_string_alloc();
  45. load_python_file(file_path, code);
  46. size_t index = furi_string_search_rchar(file_path, '/');
  47. furi_check(index != FURI_STRING_FAILURE);
  48. furi_string_left(file_path, index);
  49. root_module_path = furi_string_get_cstr(file_path);
  50. mp_embed_init(memory + stack_size, memory_size - stack_size, memory);
  51. mp_embed_exec_str(furi_string_get_cstr(code));
  52. mp_embed_deinit();
  53. furi_string_free(file_path);
  54. furi_string_free(code);
  55. free(memory);
  56. return 0;
  57. }