mp_flipper_app.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include <furi.h>
  2. #include <dialogs/dialogs.h>
  3. #include <storage/storage.h>
  4. #include <port/micropython_embed.h>
  5. static void load_python_file(FuriString* code) {
  6. Storage* storage = furi_record_open(RECORD_STORAGE);
  7. DialogsApp* dialogs = furi_record_open(RECORD_DIALOGS);
  8. File* file = storage_file_alloc(storage);
  9. FuriString* file_path = furi_string_alloc();
  10. DialogsFileBrowserOptions browser_options;
  11. dialog_file_browser_set_basic_options(&browser_options, "py", NULL);
  12. browser_options.hide_ext = false;
  13. browser_options.base_path = STORAGE_APP_DATA_PATH_PREFIX;
  14. bool result = dialog_file_browser_show(dialogs, file_path, file_path, &browser_options);
  15. furi_record_close(RECORD_DIALOGS);
  16. if(result) {
  17. result = storage_file_open(file, furi_string_get_cstr(file_path), FSAM_READ, FSOM_OPEN_EXISTING);
  18. }
  19. if(result) {
  20. size_t read = 0;
  21. do {
  22. uint8_t buffer[64] = {'\0'};
  23. read = storage_file_read(file, buffer, sizeof(buffer) - 1);
  24. for(size_t i = 0; i < read; i++) {
  25. furi_string_push_back(code, buffer[i]);
  26. }
  27. } while(read > 0);
  28. furi_string_trim(code);
  29. } else {
  30. furi_string_set(code, "print('it works!')");
  31. }
  32. storage_file_free(file);
  33. furi_record_close(RECORD_STORAGE);
  34. furi_string_free(file_path);
  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. FuriString* code = furi_string_alloc();
  42. load_python_file(code);
  43. mp_embed_init(memory + stack_size, memory_size - stack_size, memory);
  44. mp_embed_exec_str(furi_string_get_cstr(code));
  45. mp_embed_deinit();
  46. furi_string_free(code);
  47. free(memory);
  48. return 0;
  49. }