// Returns standard error codes: 0 for success, 1 for all other errors, // except if FORCED_EXIT bit is set then script raised SystemExit and the // value of the exit is in the lower 8 bits of the return value STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) { if (lex == NULL) { printf("MemoryError: lexer could not allocate memory\n"); return 1; } nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { qstr source_name = lex->source_name; #if MICROPY_PY___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } #endif mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); mp_obj_t module_fun = mp_compile(&parse_tree, source_name, emit_opt, is_repl); if (!compile_only) { // execute it mp_call_function_0(module_fun); } nlr_pop(); return 0; } else { // uncaught exception return handle_uncaught_exception((mp_obj_t)nlr.ret_val); } }
// Returns standard error codes: 0 for success, 1 for all other errors, // except if FORCED_EXIT bit is set then script raised SystemExit and the // value of the exit is in the lower 8 bits of the return value STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) { if (lex == NULL) { printf("MemoryError: lexer could not allocate memory\n"); return 1; } #ifndef _WIN32 // enable signal handler struct sigaction sa; sa.sa_handler = sighandler; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, NULL); sa.sa_handler = SIG_DFL; #endif nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { qstr source_name = lex->source_name; #if MICROPY_PY___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } #endif mp_parse_node_t pn = mp_parse(lex, input_kind); /* printf("----------------\n"); mp_parse_node_print(pn, 0); printf("----------------\n"); */ mp_obj_t module_fun = mp_compile(pn, source_name, emit_opt, is_repl); if (!compile_only) { // execute it mp_call_function_0(module_fun); } #ifndef _WIN32 // disable signal handler sigaction(SIGINT, &sa, NULL); #endif nlr_pop(); return 0; } else { // uncaught exception #ifndef _WIN32 // disable signal handler sigaction(SIGINT, &sa, NULL); #endif return handle_uncaught_exception((mp_obj_t)nlr.ret_val); } }
// Returns standard error codes: 0 for success, 1 for all other errors, // except if FORCED_EXIT bit is set then script raised SystemExit and the // value of the exit is in the lower 8 bits of the return value STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) { if (lex == NULL) { printf("MemoryError: lexer could not allocate memory\n"); return 1; } mp_hal_set_interrupt_char(CHAR_CTRL_C); nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { qstr source_name = lex->source_name; #if MICROPY_PY___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } #endif mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); /* printf("----------------\n"); mp_parse_node_print(parse_tree.root, 0); printf("----------------\n"); */ mp_obj_t module_fun = mp_compile(&parse_tree, source_name, emit_opt, is_repl); if (!compile_only) { // execute it mp_call_function_0(module_fun); // check for pending exception if (MP_STATE_VM(mp_pending_exception) != MP_OBJ_NULL) { mp_obj_t obj = MP_STATE_VM(mp_pending_exception); MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL; nlr_raise(obj); } } mp_hal_set_interrupt_char(-1); nlr_pop(); return 0; } else { // uncaught exception mp_hal_set_interrupt_char(-1); return handle_uncaught_exception(nlr.ret_val); } }
STATIC int compile_and_save(const char *file, const char *output_file, const char *source_file) { mp_lexer_t *lex = mp_lexer_new_from_file(file); if (lex == NULL) { printf("could not open file '%s' for reading\n", file); return 1; } nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { qstr source_name; if (source_file == NULL) { source_name = lex->source_name; } else { source_name = qstr_from_str(source_file); } #if MICROPY_PY___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } #endif mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT); mp_raw_code_t *rc = mp_compile_to_raw_code(&parse_tree, source_name, emit_opt, false); vstr_t vstr; vstr_init(&vstr, 16); if (output_file == NULL) { vstr_add_str(&vstr, file); vstr_cut_tail_bytes(&vstr, 2); vstr_add_str(&vstr, "mpy"); } else { vstr_add_str(&vstr, output_file); } mp_raw_code_save_file(rc, vstr_null_terminated_str(&vstr)); vstr_clear(&vstr); nlr_pop(); return 0; } else { // uncaught exception mp_obj_print_exception(&mp_stderr_print, (mp_obj_t)nlr.ret_val); return 1; } }
STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t kind, bool repl) { if (lex == NULL) { init_console(); printf("MemoryError: lexer could not allocate memory\n"); return ERR_MEMORY_ALLOC; } nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { qstr source_name = lex->source_name; if (kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } mp_parse_tree_t parse_tree = mp_parse(lex, kind); mp_obj_t module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, repl); mp_call_function_0(module_fun); if (MP_STATE_VM(mp_pending_exception) != MP_OBJ_NULL) { mp_obj_t obj = MP_STATE_VM(mp_pending_exception); MP_STATE_VM(mp_pending_exception) = MP_OBJ_NULL; nlr_raise(obj); } nlr_pop(); return 0; } else { if (mp_obj_exception_match(nlr.ret_val, &mp_type_SystemExit)) { return ERR_SYS_EXIT; } if (mp_obj_is_exception_type(nlr.ret_val) && ((mp_obj_exception_t *) nlr.ret_val)->args != NULL && ((mp_obj_exception_t *) nlr.ret_val)->args->len == 1) { int code = mp_obj_get_int(((mp_obj_exception_t *) nlr.ret_val)->args->items[0]); if (code == 0xDEAD0000) { return ERR_NETLOAD; } } init_console(); mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); return ERR_PARSE; } }
int main(int argc, char **argv) { mp_stack_set_limit(40000 * (BYTES_PER_WORD / 4)); pre_process_options(argc, argv); #if MICROPY_ENABLE_GC char *heap = malloc(heap_size); gc_init(heap, heap + heap_size); #endif mp_init(); #ifndef _WIN32 // create keyboard interrupt object MP_STATE_VM(keyboard_interrupt_obj) = mp_obj_new_exception(&mp_type_KeyboardInterrupt); #endif char *home = getenv("HOME"); char *path = getenv("MICROPYPATH"); if (path == NULL) { #ifdef MICROPY_PY_SYS_PATH_DEFAULT path = MICROPY_PY_SYS_PATH_DEFAULT; #else path = "~/.micropython/lib:/usr/lib/micropython"; #endif } mp_uint_t path_num = 1; // [0] is for current dir (or base dir of the script) for (char *p = path; p != NULL; p = strchr(p, PATHLIST_SEP_CHAR)) { path_num++; if (p != NULL) { p++; } } mp_obj_list_init(mp_sys_path, path_num); mp_obj_t *path_items; mp_obj_list_get(mp_sys_path, &path_num, &path_items); path_items[0] = MP_OBJ_NEW_QSTR(MP_QSTR_); { char *p = path; for (mp_uint_t i = 1; i < path_num; i++) { char *p1 = strchr(p, PATHLIST_SEP_CHAR); if (p1 == NULL) { p1 = p + strlen(p); } if (p[0] == '~' && p[1] == '/' && home != NULL) { // Expand standalone ~ to $HOME CHECKBUF(buf, PATH_MAX); CHECKBUF_APPEND(buf, home, strlen(home)); CHECKBUF_APPEND(buf, p + 1, (size_t)(p1 - p - 1)); path_items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(buf, CHECKBUF_LEN(buf))); } else { path_items[i] = MP_OBJ_NEW_QSTR(qstr_from_strn(p, p1 - p)); } p = p1 + 1; } } mp_obj_list_init(mp_sys_argv, 0); #if defined(MICROPY_UNIX_COVERAGE) { MP_DECLARE_CONST_FUN_OBJ(extra_coverage_obj); mp_store_global(QSTR_FROM_STR_STATIC("extra_coverage"), (mp_obj_t)&extra_coverage_obj); } #endif // Here is some example code to create a class and instance of that class. // First is the Python, then the C code. // // class TestClass: // pass // test_obj = TestClass() // test_obj.attr = 42 // // mp_obj_t test_class_type, test_class_instance; // test_class_type = mp_obj_new_type(QSTR_FROM_STR_STATIC("TestClass"), mp_const_empty_tuple, mp_obj_new_dict(0)); // mp_store_name(QSTR_FROM_STR_STATIC("test_obj"), test_class_instance = mp_call_function_0(test_class_type)); // mp_store_attr(test_class_instance, QSTR_FROM_STR_STATIC("attr"), mp_obj_new_int(42)); /* printf("bytes:\n"); printf(" total %d\n", m_get_total_bytes_allocated()); printf(" cur %d\n", m_get_current_bytes_allocated()); printf(" peak %d\n", m_get_peak_bytes_allocated()); */ const int NOTHING_EXECUTED = -2; int ret = NOTHING_EXECUTED; for (int a = 1; a < argc; a++) { if (argv[a][0] == '-') { if (strcmp(argv[a], "-c") == 0) { if (a + 1 >= argc) { return usage(argv); } ret = do_str(argv[a + 1]); if (ret & FORCED_EXIT) { break; } a += 1; } else if (strcmp(argv[a], "-m") == 0) { if (a + 1 >= argc) { return usage(argv); } mp_obj_t import_args[4]; import_args[0] = mp_obj_new_str(argv[a + 1], strlen(argv[a + 1]), false); import_args[1] = import_args[2] = mp_const_none; // Ask __import__ to handle imported module specially - set its __name__ // to __main__, and also return this leaf module, not top-level package // containing it. import_args[3] = mp_const_false; // TODO: https://docs.python.org/3/using/cmdline.html#cmdoption-m : // "the first element of sys.argv will be the full path to // the module file (while the module file is being located, // the first element will be set to "-m")." set_sys_argv(argv, argc, a + 1); mp_obj_t mod; nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mod = mp_builtin___import__(MP_ARRAY_SIZE(import_args), import_args); nlr_pop(); } else { // uncaught exception return handle_uncaught_exception((mp_obj_t)nlr.ret_val) & 0xff; } if (mp_obj_is_package(mod)) { // TODO fprintf(stderr, "%s: -m for packages not yet implemented\n", argv[0]); exit(1); } ret = 0; break; } else if (strcmp(argv[a], "-X") == 0) { a += 1; } else if (strcmp(argv[a], "-v") == 0) { mp_verbose_flag++; } else if (strncmp(argv[a], "-O", 2) == 0) { if (isdigit(argv[a][2])) { MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf; } else { MP_STATE_VM(mp_optimise_value) = 0; for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++); } } else { return usage(argv); } } else { char *pathbuf = malloc(PATH_MAX); char *basedir = realpath(argv[a], pathbuf); if (basedir == NULL) { fprintf(stderr, "%s: can't open file '%s': [Errno %d] ", argv[0], argv[a], errno); perror(""); // CPython exits with 2 in such case ret = 2; break; } // Set base dir of the script as first entry in sys.path char *p = strrchr(basedir, '/'); path_items[0] = MP_OBJ_NEW_QSTR(qstr_from_strn(basedir, p - basedir)); free(pathbuf); set_sys_argv(argv, argc, a); ret = do_file(argv[a]); break; } } if (ret == NOTHING_EXECUTED) { if (isatty(0)) { prompt_read_history(); ret = do_repl(); prompt_write_history(); } else { mp_lexer_t *lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false); ret = execute_from_lexer(lex, MP_PARSE_FILE_INPUT, false); } } #if MICROPY_PY_MICROPYTHON_MEM_INFO if (mp_verbose_flag) { mp_micropython_mem_info(0, NULL); } #endif mp_deinit(); #if MICROPY_ENABLE_GC && !defined(NDEBUG) // We don't really need to free memory since we are about to exit the // process, but doing so helps to find memory leaks. free(heap); #endif //printf("total bytes = %d\n", m_get_total_bytes_allocated()); return ret & 0xff; }
// function to run extra tests for things that can't be checked by scripts STATIC mp_obj_t extra_coverage(void) { // mp_printf (used by ports that don't have a native printf) { printf("# mp_printf\n"); mp_printf(&mp_plat_print, "%"); // nothing after percent mp_printf(&mp_plat_print, "%d %+d % d\n", -123, 123, 123); // sign mp_printf(&mp_plat_print, "%05d\n", -123); // negative number with zero padding mp_printf(&mp_plat_print, "%ld\n", 123); // long mp_printf(&mp_plat_print, "%X\n", 0x1abcdef); // capital hex mp_printf(&mp_plat_print, "%.2s %.3s\n", "abc", "abc"); // fixed string precision mp_printf(&mp_plat_print, "%.*s\n", -1, "abc"); // negative string precision mp_printf(&mp_plat_print, "%b %b\n", 0, 1); // bools mp_printf(&mp_plat_print, "%s\n", NULL); // null string mp_printf(&mp_plat_print, "%t\n"); // non-format char } // vstr { printf("# vstr\n"); vstr_t *vstr = vstr_new_size(16); vstr_hint_size(vstr, 32); vstr_add_str(vstr, "ts"); vstr_ins_byte(vstr, 1, 'e'); vstr_ins_char(vstr, 3, 't'); vstr_ins_char(vstr, 10, 's'); printf("%.*s\n", (int)vstr->len, vstr->buf); vstr_cut_head_bytes(vstr, 2); printf("%.*s\n", (int)vstr->len, vstr->buf); vstr_cut_tail_bytes(vstr, 10); printf("%.*s\n", (int)vstr->len, vstr->buf); vstr_printf(vstr, "t%cst", 'e'); printf("%.*s\n", (int)vstr->len, vstr->buf); vstr_cut_out_bytes(vstr, 3, 10); printf("%.*s\n", (int)vstr->len, vstr->buf); VSTR_FIXED(fix, 4); vstr_add_str(&fix, "large"); printf("%.*s\n", (int)fix.len, fix.buf); } // repl autocomplete { printf("# repl\n"); const char *str; mp_uint_t len = mp_repl_autocomplete("__n", 3, &mp_plat_print, &str); printf("%.*s\n", (int)len, str); mp_store_global(MP_QSTR_sys, mp_import_name(MP_QSTR_sys, mp_const_none, MP_OBJ_NEW_SMALL_INT(0))); mp_repl_autocomplete("sys.", 4, &mp_plat_print, &str); len = mp_repl_autocomplete("sys.impl", 8, &mp_plat_print, &str); printf("%.*s\n", (int)len, str); } // attrtuple { printf("# attrtuple\n"); static const qstr fields[] = {MP_QSTR_start, MP_QSTR_stop, MP_QSTR_step}; static const mp_obj_t items[] = {MP_OBJ_NEW_SMALL_INT(1), MP_OBJ_NEW_SMALL_INT(2), MP_OBJ_NEW_SMALL_INT(3)}; mp_obj_print_helper(&mp_plat_print, mp_obj_new_attrtuple(fields, 3, items), PRINT_REPR); printf("\n"); } return mp_const_none; }
// returns standard error codes: 0 for success, 1 for all other errors STATIC int execute_from_lexer(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) { if (lex == NULL) { return 1; } if (0) { // just tokenise while (!mp_lexer_is_kind(lex, MP_TOKEN_END)) { mp_token_show(mp_lexer_cur(lex)); mp_lexer_to_next(lex); } mp_lexer_free(lex); return 0; } mp_parse_error_kind_t parse_error_kind; mp_parse_node_t pn = mp_parse(lex, input_kind, &parse_error_kind); if (pn == MP_PARSE_NODE_NULL) { // parse error mp_parse_show_exception(lex, parse_error_kind); mp_lexer_free(lex); return 1; } qstr source_name = mp_lexer_source_name(lex); #if MICROPY_PY___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } #endif mp_lexer_free(lex); /* printf("----------------\n"); mp_parse_node_print(pn, 0); printf("----------------\n"); */ mp_obj_t module_fun = mp_compile(pn, source_name, emit_opt, is_repl); if (module_fun == mp_const_none) { // compile error return 1; } if (compile_only) { return 0; } // execute it nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_call_function_0(module_fun); nlr_pop(); return 0; } else { // uncaught exception // check for SystemExit mp_obj_t exc = (mp_obj_t)nlr.ret_val; if (mp_obj_is_subclass_fast(mp_obj_get_type(exc), &mp_type_SystemExit)) { mp_obj_t exit_val = mp_obj_exception_get_value(exc); mp_int_t val; if (!mp_obj_get_int_maybe(exit_val, &val)) { val = 0; } exit(val); } mp_obj_print_exception((mp_obj_t)nlr.ret_val); return 1; } }
// function to run extra tests for things that can't be checked by scripts STATIC mp_obj_t extra_coverage(void) { // mp_printf (used by ports that don't have a native printf) { mp_printf(&mp_plat_print, "# mp_printf\n"); mp_printf(&mp_plat_print, "%d %+d % d\n", -123, 123, 123); // sign mp_printf(&mp_plat_print, "%05d\n", -123); // negative number with zero padding mp_printf(&mp_plat_print, "%ld\n", 123); // long mp_printf(&mp_plat_print, "%X\n", 0x1abcdef); // capital hex mp_printf(&mp_plat_print, "%.2s %.3s\n", "abc", "abc"); // fixed string precision mp_printf(&mp_plat_print, "%.*s\n", -1, "abc"); // negative string precision mp_printf(&mp_plat_print, "%b %b\n", 0, 1); // bools mp_printf(&mp_plat_print, "%s\n", NULL); // null string mp_printf(&mp_plat_print, "%d\n", 0x80000000); // should print signed mp_printf(&mp_plat_print, "%u\n", 0x80000000); // should print unsigned mp_printf(&mp_plat_print, "%x\n", 0x80000000); // should print unsigned mp_printf(&mp_plat_print, "%X\n", 0x80000000); // should print unsigned } // vstr { mp_printf(&mp_plat_print, "# vstr\n"); vstr_t *vstr = vstr_new(16); vstr_hint_size(vstr, 32); vstr_add_str(vstr, "ts"); vstr_ins_byte(vstr, 1, 'e'); vstr_ins_char(vstr, 3, 't'); vstr_ins_char(vstr, 10, 's'); mp_printf(&mp_plat_print, "%.*s\n", (int)vstr->len, vstr->buf); vstr_cut_head_bytes(vstr, 2); mp_printf(&mp_plat_print, "%.*s\n", (int)vstr->len, vstr->buf); vstr_cut_tail_bytes(vstr, 10); mp_printf(&mp_plat_print, "%.*s\n", (int)vstr->len, vstr->buf); vstr_printf(vstr, "t%cst", 'e'); mp_printf(&mp_plat_print, "%.*s\n", (int)vstr->len, vstr->buf); vstr_cut_out_bytes(vstr, 3, 10); mp_printf(&mp_plat_print, "%.*s\n", (int)vstr->len, vstr->buf); VSTR_FIXED(fix, 4); vstr_add_str(&fix, "large"); mp_printf(&mp_plat_print, "%.*s\n", (int)fix.len, fix.buf); } // repl autocomplete { mp_printf(&mp_plat_print, "# repl\n"); const char *str; mp_uint_t len = mp_repl_autocomplete("__n", 3, &mp_plat_print, &str); mp_printf(&mp_plat_print, "%.*s\n", (int)len, str); mp_store_global(MP_QSTR_sys, mp_import_name(MP_QSTR_sys, mp_const_none, MP_OBJ_NEW_SMALL_INT(0))); mp_repl_autocomplete("sys.", 4, &mp_plat_print, &str); len = mp_repl_autocomplete("sys.impl", 8, &mp_plat_print, &str); mp_printf(&mp_plat_print, "%.*s\n", (int)len, str); } // attrtuple { mp_printf(&mp_plat_print, "# attrtuple\n"); static const qstr fields[] = {MP_QSTR_start, MP_QSTR_stop, MP_QSTR_step}; static const mp_obj_t items[] = {MP_OBJ_NEW_SMALL_INT(1), MP_OBJ_NEW_SMALL_INT(2), MP_OBJ_NEW_SMALL_INT(3)}; mp_obj_print_helper(&mp_plat_print, mp_obj_new_attrtuple(fields, 3, items), PRINT_REPR); mp_printf(&mp_plat_print, "\n"); } // str { mp_printf(&mp_plat_print, "# str\n"); // intern string mp_printf(&mp_plat_print, "%d\n", MP_OBJ_IS_QSTR(mp_obj_str_intern(mp_obj_new_str("intern me", 9, false)))); } // mpz { mp_printf(&mp_plat_print, "# mpz\n"); mp_uint_t value; mpz_t mpz; mpz_init_zero(&mpz); // mpz_as_uint_checked, with success mpz_set_from_int(&mpz, 12345678); mp_printf(&mp_plat_print, "%d\n", mpz_as_uint_checked(&mpz, &value)); mp_printf(&mp_plat_print, "%d\n", (int)value); // mpz_as_uint_checked, with negative arg mpz_set_from_int(&mpz, -1); mp_printf(&mp_plat_print, "%d\n", mpz_as_uint_checked(&mpz, &value)); // mpz_as_uint_checked, with overflowing arg mpz_set_from_int(&mpz, 1); mpz_shl_inpl(&mpz, &mpz, 70); mp_printf(&mp_plat_print, "%d\n", mpz_as_uint_checked(&mpz, &value)); } // runtime utils { mp_printf(&mp_plat_print, "# runtime utils\n"); // call mp_call_function_1_protected mp_call_function_1_protected(MP_OBJ_FROM_PTR(&mp_builtin_abs_obj), MP_OBJ_NEW_SMALL_INT(1)); // call mp_call_function_1_protected with invalid args mp_call_function_1_protected(MP_OBJ_FROM_PTR(&mp_builtin_abs_obj), mp_obj_new_str("abc", 3, false)); // call mp_call_function_2_protected mp_call_function_2_protected(MP_OBJ_FROM_PTR(&mp_builtin_divmod_obj), MP_OBJ_NEW_SMALL_INT(1), MP_OBJ_NEW_SMALL_INT(1)); // call mp_call_function_2_protected with invalid args mp_call_function_2_protected(MP_OBJ_FROM_PTR(&mp_builtin_divmod_obj), mp_obj_new_str("abc", 3, false), mp_obj_new_str("abc", 3, false)); } // warning { mp_emitter_warning(MP_PASS_CODE_SIZE, "test"); } // format float { mp_printf(&mp_plat_print, "# format float\n"); // format with inadequate buffer size char buf[5]; mp_format_float(1, buf, sizeof(buf), 'g', 0, '+'); mp_printf(&mp_plat_print, "%s\n", buf); // format with just enough buffer so that precision must be // set from 0 to 1 twice char buf2[8]; mp_format_float(1, buf2, sizeof(buf2), 'g', 0, '+'); mp_printf(&mp_plat_print, "%s\n", buf2); // format where precision is trimmed to avoid buffer overflow mp_format_float(1, buf2, sizeof(buf2), 'e', 0, '+'); mp_printf(&mp_plat_print, "%s\n", buf2); } // return a tuple of data for testing on the Python side mp_obj_t items[] = {(mp_obj_t)&str_no_hash_obj, (mp_obj_t)&bytes_no_hash_obj}; return mp_obj_new_tuple(MP_ARRAY_SIZE(items), items); }
int main(void) { // Stack limit should be less than real stack size, so we // had chance to recover from limit hit. mp_stack_set_limit((char*)&_ram_end - (char*)&_heap_end - 1024); /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Global MSP (MCU Support Package) initialization */ HAL_Init(); // basic sub-system init pendsv_init(); timer_tim3_init(); led_init(); soft_reset: // check if user switch held to select the reset mode led_state(LED_RED, 1); led_state(LED_GREEN, 1); led_state(LED_BLUE, 1); #if MICROPY_HW_ENABLE_RTC rtc_init(); #endif // GC init gc_init(&_heap_start, &_heap_end); // Micro Python init mp_init(); mp_obj_list_init(mp_sys_path, 0); mp_obj_list_init(mp_sys_argv, 0); readline_init0(); pin_init0(); extint_init0(); timer_init0(); rng_init0(); i2c_init0(); spi_init0(); uart_init0(); pyb_usb_init0(); usbdbg_init(); if (sensor_init() != 0) { __fatal_error("Failed to init sensor"); } /* Export functions to the global python namespace */ mp_store_global(qstr_from_str("randint"), (mp_obj_t)&py_randint_obj); mp_store_global(qstr_from_str("cpu_freq"), (mp_obj_t)&py_cpu_freq_obj); mp_store_global(qstr_from_str("Image"), (mp_obj_t)&py_image_load_image_obj); mp_store_global(qstr_from_str("HaarCascade"), (mp_obj_t)&py_image_load_cascade_obj); mp_store_global(qstr_from_str("FreakDesc"), (mp_obj_t)&py_image_load_descriptor_obj); mp_store_global(qstr_from_str("FreakDescSave"), (mp_obj_t)&py_image_save_descriptor_obj); mp_store_global(qstr_from_str("LBPDesc"), (mp_obj_t)&py_image_load_lbp_obj); mp_store_global(qstr_from_str("vcp_is_connected"), (mp_obj_t)&py_vcp_is_connected_obj); if (sdcard_is_present()) { sdcard_init(); FRESULT res = f_mount(&fatfs, "1:", 1); if (res != FR_OK) { __fatal_error("could not mount SD\n"); } // Set CWD and USB medium to SD f_chdrive("1:"); pyb_usb_storage_medium = PYB_USB_STORAGE_MEDIUM_SDCARD; } else { storage_init(); // try to mount the flash FRESULT res = f_mount(&fatfs, "0:", 1); if (res == FR_NO_FILESYSTEM) { // create a fresh fs make_flash_fs(); } else if (res != FR_OK) { __fatal_error("could not access LFS\n"); } // Set CWD and USB medium to flash f_chdrive("0:"); pyb_usb_storage_medium = PYB_USB_STORAGE_MEDIUM_FLASH; } // turn boot-up LEDs off led_state(LED_RED, 0); led_state(LED_GREEN, 0); led_state(LED_BLUE, 0); // init USB device to default setting if it was not already configured if (!(pyb_usb_flags & PYB_USB_FLAG_USB_MODE_CALLED)) { pyb_usb_dev_init(USBD_VID, USBD_PID_CDC_MSC, USBD_MODE_CDC_MSC, NULL); } // Run the main script from the current directory. FRESULT res = f_stat("main.py", NULL); if (res == FR_OK) { if (!pyexec_file("main.py")) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { flash_error(3); nlr_pop(); } } } // Enter REPL nlr_buf_t nlr; for (;;) { if (nlr_push(&nlr) == 0) { while (usbdbg_script_ready()) { nlr_buf_t nlr; vstr_t *script_buf = usbdbg_get_script(); // clear script flag usbdbg_clr_script(); // execute the script if (nlr_push(&nlr) == 0) { pyexec_push_scope(); // parse and compile script mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr_str(script_buf), vstr_len(script_buf), 0); mp_parse_node_t pn = mp_parse(lex, MP_PARSE_FILE_INPUT); mp_obj_t script = mp_compile(pn, lex->source_name, MP_EMIT_OPT_NONE, false); // execute the script mp_call_function_0(script); nlr_pop(); } else { mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); } pyexec_pop_scope(); } // clear script flag usbdbg_clr_script(); // no script run REPL pyexec_friendly_repl(); nlr_pop(); } } printf("PYB: sync filesystems\n"); storage_flush(); printf("PYB: soft reboot\n"); goto soft_reset; }
int main(void) { FRESULT f_res; int sensor_init_ret; // Stack limit should be less than real stack size, so we // had chance to recover from limit hit. mp_stack_set_limit((char*)&_ram_end - (char*)&_heap_end - 1024); /* STM32F4xx HAL library initialization: - Configure the Flash prefetch, instruction and Data caches - Configure the Systick to generate an interrupt each 1 msec - Set NVIC Group Priority to 4 - Global MSP (MCU Support Package) initialization */ HAL_Init(); // basic sub-system init pendsv_init(); timer_tim3_init(); led_init(); soft_reset: // check if user switch held to select the reset mode led_state(LED_RED, 1); led_state(LED_GREEN, 1); led_state(LED_BLUE, 1); #if MICROPY_HW_ENABLE_RTC rtc_init(); #endif // GC init gc_init(&_heap_start, &_heap_end); // Micro Python init mp_init(); mp_obj_list_init(mp_sys_path, 0); mp_obj_list_init(mp_sys_argv, 0); readline_init0(); pin_init0(); extint_init0(); timer_init0(); rng_init0(); i2c_init0(); spi_init0(); uart_init0(); pyb_usb_init0(); usbdbg_init(); sensor_init_ret = sensor_init(); /* Export functions to the global python namespace */ mp_store_global(qstr_from_str("randint"), (mp_obj_t)&py_randint_obj); mp_store_global(qstr_from_str("cpu_freq"), (mp_obj_t)&py_cpu_freq_obj); mp_store_global(qstr_from_str("vcp_is_connected"), (mp_obj_t)&py_vcp_is_connected_obj); if (sdcard_is_present()) { sdcard_init(); FRESULT res = f_mount(&fatfs, "1:", 1); if (res != FR_OK) { __fatal_error("could not mount SD\n"); } // Set CWD and USB medium to SD f_chdrive("1:"); pyb_usb_storage_medium = PYB_USB_STORAGE_MEDIUM_SDCARD; } else { storage_init(); // try to mount the flash FRESULT res = f_mount(&fatfs, "0:", 1); if (res == FR_NO_FILESYSTEM) { // create a fresh fs make_flash_fs(); } else if (res != FR_OK) { __fatal_error("could not access LFS\n"); } // Set CWD and USB medium to flash f_chdrive("0:"); pyb_usb_storage_medium = PYB_USB_STORAGE_MEDIUM_FLASH; } // turn boot-up LEDs off led_state(LED_RED, 0); led_state(LED_GREEN, 0); led_state(LED_BLUE, 0); // init USB device to default setting if it was not already configured if (!(pyb_usb_flags & PYB_USB_FLAG_USB_MODE_CALLED)) { pyb_usb_dev_init(USBD_VID, USBD_PID_CDC_MSC, USBD_MODE_CDC_MSC, NULL); } // check sensor init result if (sensor_init_ret != 0) { char buf[512]; snprintf(buf, sizeof(buf), "Failed to init sensor, error:%d", sensor_init_ret); __fatal_error(buf); } // Run self tests the first time only f_res = f_stat("selftest.py", NULL); if (f_res == FR_OK) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { // Parse, compile and execute the self-tests script. pyexec_file("selftest.py"); nlr_pop(); } else { // Get the exception message. TODO: might be a hack. mp_obj_str_t *str = mp_obj_exception_get_value((mp_obj_t)nlr.ret_val); // If any of the self-tests fail log the exception message // and loop forever. Note: IDE exceptions will not be caught. __fatal_error((const char*) str->data); } // Success: remove self tests script and flush cache f_unlink("selftest.py"); storage_flush(); } // Run the main script from the current directory. f_res = f_stat("main.py", NULL); if (f_res == FR_OK) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { // Parse, compile and execute the main script. pyexec_file("main.py"); nlr_pop(); } else { mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); if (nlr_push(&nlr) == 0) { flash_error(3); nlr_pop(); }// if this gets interrupted again ignore it. } } // Enter REPL nlr_buf_t nlr; for (;;) { if (nlr_push(&nlr) == 0) { while (usbdbg_script_ready()) { nlr_buf_t nlr; vstr_t *script_buf = usbdbg_get_script(); // clear debugging flags usbdbg_clear_flags(); // re-init MP mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); mp_init(); MICROPY_END_ATOMIC_SECTION(atomic_state); // execute the script if (nlr_push(&nlr) == 0) { // parse, compile and execute script pyexec_str(script_buf); nlr_pop(); } else { mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); } } // clear debugging flags usbdbg_clear_flags(); // re-init MP mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); mp_init(); MICROPY_END_ATOMIC_SECTION(atomic_state); // no script run REPL pyexec_friendly_repl(); nlr_pop(); } } printf("PYB: sync filesystems\n"); storage_flush(); printf("PYB: soft reboot\n"); goto soft_reset; }
int main(void) { rcc_ctrl_set_frequency(SYSCLK_168_MHZ); /* Init SysTick timer */ systick_init(); /* Init MicroPython */ libmp_init(); /* init USB debug */ usbdbg_init(); /* init rng */ rng_init(); /* Add functions to the global python namespace */ mp_store_global(qstr_from_str("help"), mp_make_function_n(0, py_help)); mp_store_global(qstr_from_str("open"), mp_make_function_n(2, py_file_open)); mp_store_global(qstr_from_str("vcp_connected"), mp_make_function_n(0, py_vcp_connected)); mp_store_global(qstr_from_str("info"), mp_make_function_n(0, py_info)); mp_store_global(qstr_from_str("gc_collect"), mp_make_function_n(0, py_gc_collect)); mp_store_global(qstr_from_str("Image"), mp_make_function_n(1, py_image_load_image)); mp_store_global(qstr_from_str("HaarCascade"), mp_make_function_n(1, py_image_load_cascade)); /* Export Python modules to the global python namespace */ for (const module_t *p = exported_modules; p->name != NULL; p++) { const mp_obj_module_t *module = p->init(); if (module == NULL) { __fatal_error("failed to init module"); } else { mp_module_register(p->name, (mp_obj_t)module); } } /* prepare workarea for sdcard fs */ f_mount(&fatfs1, "1:", 0); /* Try to mount the flash fs */ bool reset_filesystem = false; FRESULT res = f_mount(&fatfs0, "0:", 1); if (!reset_filesystem && res == FR_OK) { /* Mount sucessful */ } else if (reset_filesystem || res == FR_NO_FILESYSTEM) { /* No filesystem, so create a fresh one */ res = f_mkfs("0:", 0, 0); if (res != FR_OK) { __fatal_error("could not create LFS"); } /* Create main.py */ FIL fp; f_open(&fp, "0:/main.py", FA_WRITE | FA_CREATE_ALWAYS); UINT n; f_write(&fp, fresh_main_py, sizeof(fresh_main_py) - 1 /* don't count null terminator */, &n); // TODO check we could write n bytes f_close(&fp); } else { __fatal_error("could not access LFS"); } pyb_usb_dev_init(PYB_USB_DEV_VCP_MSC); #if 1 /* run main script */ if (!libmp_do_file("0:/main.py")) { printf("failed to run main script\n"); } libmp_do_repl(); #else // led_init(LED_BLUE); systick_sleep(100); wlan_test(); #endif while(1); }