mp_obj_t py_file_open(mp_obj_t path, mp_obj_t mode_str) { BYTE mode=0; FRESULT res; py_file_obj_t *o; switch (mp_obj_str_get_str(mode_str)[0]) { case 'r': /* Open file for reading, fail if the file is not existing. */ mode = FA_READ|FA_OPEN_EXISTING; break; case 'w': /* Open file for reading/writing, create the file if not existing. */ mode = FA_READ|FA_WRITE|FA_OPEN_ALWAYS; break; case 'a': /* Open file for reading/writing, fail if the file is not existing. */ mode = FA_READ|FA_WRITE|FA_OPEN_EXISTING; break; default: nlr_jump(mp_obj_new_exception_msg(qstr_from_str("File"), "invalid open mode")); } /* Create new python file obj */ o = m_new_obj(py_file_obj_t); o->base.type = &py_file_type; /* Open underlying file handle */ res = f_open(&o->fp, mp_obj_str_get_str(path), mode); if (res != FR_OK) { nlr_jump(mp_obj_new_exception_msg(qstr_from_str("File"), ffs_strerror(res))); } return o; }
static mp_obj_t py_image_find_features(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { struct image *image = NULL; struct cascade *cascade = NULL; array_t *objects_array=NULL; mp_obj_t objects_list = mp_const_none; /* sanity checks */ PY_ASSERT_TRUE_MSG(sensor.pixformat == PIXFORMAT_GRAYSCALE, "This function is only supported on GRAYSCALE images"); PY_ASSERT_TRUE_MSG(sensor.framesize <= OMV_MAX_INT_FRAME, "This function is only supported on "OMV_MAX_INT_FRAME_STR" and smaller frames"); /* read arguments */ image = py_image_cobj(args[0]); cascade = py_cascade_cobj(args[1]); /* set some defaults */ cascade->threshold = 0.65f; cascade->scale_factor = 1.65f; /* read kw args */ mp_map_elem_t *kw_thresh = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("threshold")), MP_MAP_LOOKUP); if (kw_thresh != NULL) { cascade->threshold = mp_obj_get_float(kw_thresh->value); } mp_map_elem_t *kw_scalef = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("scale")), MP_MAP_LOOKUP); if (kw_scalef != NULL) { cascade->scale_factor = mp_obj_get_float(kw_scalef->value); } /* Detect objects */ objects_array = imlib_detect_objects(image, cascade); /* Create empty Python list */ objects_list = mp_obj_new_list(0, NULL); /* Add detected objects to the list */ for (int i=0; i<array_length(objects_array); i++) { struct rectangle *r = array_at(objects_array, i); mp_obj_t rec_obj[4] = { mp_obj_new_int(r->x), mp_obj_new_int(r->y), mp_obj_new_int(r->w), mp_obj_new_int(r->h), }; mp_obj_list_append(objects_list, mp_obj_new_tuple(4, rec_obj)); } /* Free the objects array */ array_free(objects_array); return objects_list; }
static mp_obj_t py_image_save(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { int res; image_t *image = py_image_cobj(args[0]); const char *path = mp_obj_str_get_str(args[1]); mp_map_elem_t *kw_subimage = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("subimage")), MP_MAP_LOOKUP); if (kw_subimage != NULL) { mp_obj_t *array; mp_obj_get_array_fixed_n(kw_subimage->value, 4, &array); rectangle_t r = { mp_obj_get_int(array[0]), mp_obj_get_int(array[1]), mp_obj_get_int(array[2]), mp_obj_get_int(array[3]), }; res = imlib_save_image(image, path, &r); } else { res = imlib_save_image(image, path, NULL); } if (res != FR_OK) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, ffs_strerror(res))); } return mp_const_true; }
mp_obj_t py_imlib_save_template(mp_obj_t image_obj, mp_obj_t rectangle_obj, mp_obj_t path_obj) { struct image t; struct image *image = NULL; struct rectangle r; mp_obj_t *array; const char *path = mp_obj_str_get_str(path_obj); array = mp_obj_get_array_fixed_n(rectangle_obj, 4); r.x = mp_obj_get_int(array[0]); r.y = mp_obj_get_int(array[1]); r.w = mp_obj_get_int(array[2]); r.h = mp_obj_get_int(array[3]); /* get C image pointer */ image = py_image_cobj(image_obj); t.w = r.w; t.h = r.h; t.data = malloc(sizeof(*t.data)*t.w*t.h); imlib_subimage(image, &t, r.x, r.y); int res = imlib_save_template(&t, path); free(t.data); if (res != FR_OK) { nlr_jump(mp_obj_new_exception_msg(qstr_from_str("Imlib"), ffs_strerror(res))); } return mp_const_true; }
static mp_obj_t mod_wlan_connect(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { int ssid_len =0; const char *ssid = NULL; const char *bssid = NULL; int key_len =0; int sec = WLAN_SEC_UNSEC; const char *key = NULL; mp_map_elem_t *kw_key, *kw_sec, *kw_bssid; ssid = mp_obj_str_get_str(args[0]); ssid_len = strlen(ssid); /* get KW args */ kw_key = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("key")), MP_MAP_LOOKUP); kw_sec = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("sec")), MP_MAP_LOOKUP); kw_bssid = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("bssid")), MP_MAP_LOOKUP); /* get key and sec */ if (kw_key && kw_sec) { key = mp_obj_str_get_str(kw_key->value); key_len = strlen(key); sec = mp_obj_get_int(kw_sec->value); if (!IS_WLAN_SEC(sec)) { nlr_raise(mp_obj_new_exception_msg( &mp_type_ValueError, "Invalid security mode")); return mp_const_false; } } /* get bssid */ if (kw_bssid != NULL) { bssid = mp_obj_str_get_str(kw_bssid->value); } /* connect to AP */ if (wlan_connect(sec, (char*) ssid, ssid_len, (uint8_t*)bssid, (uint8_t*)key, key_len) != 0) { return mp_const_false; } return mp_const_true; }
mp_lexer_t *mp_lexer_new_from_file(const char *filename) { void *data; size_t len; if (memzip_locate(filename, &data, &len) != MZ_OK) { return NULL; } return mp_lexer_new_from_str_len(qstr_from_str(filename), (const char *)data, (mp_uint_t)len, 0); }
mp_obj_t micropy_load_raw_code(const char *mod_name, const char *file_str) { qstr qstr_mod_name = qstr_from_str(mod_name); mp_obj_t module_obj = mp_obj_new_module(qstr_mod_name); // print_time(); mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str); // printf("raw_code %lx\n", (uint64_t)raw_code); do_execute_raw_code(module_obj, raw_code); // print_time(); return module_obj; }
mp_lexer_t *mp_lexer_new_from_file(const char *filename) { mp_lexer_file_buf_t *fb = m_new_obj(mp_lexer_file_buf_t); fb->fd = open(filename, O_RDONLY); if (fb->fd < 0) { m_del_obj(mp_lexer_file_buf_t, fb); return NULL; } int n = read(fb->fd, fb->buf, sizeof(fb->buf)); fb->len = n; fb->pos = 0; return mp_lexer_new(qstr_from_str(filename), fb, (mp_lexer_stream_next_char_t)file_buf_next_char, (mp_lexer_stream_close_t)file_buf_close); }
mp_obj_t micropy_call_0(mp_obj_t module_obj, const char *func) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_obj_t py_func = mp_load_attr(module_obj, qstr_from_str(func)); mp_obj_t module_obj = mp_call_function_0(py_func); nlr_pop(); return module_obj; } else { mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); // uncaught exception return 0; } }
mp_obj_t py_imlib_load_cascade(mp_obj_t path_obj) { py_cascade_obj_t *o =NULL; /* detection parameters */ struct cascade cascade = { .step = 2, .scale_factor = 1.25f, }; const char *path = mp_obj_str_get_str(path_obj); int res = imlib_load_cascade(&cascade, path); if (res != FR_OK) { nlr_jump(mp_obj_new_exception_msg(qstr_from_str("Imlib"), ffs_strerror(res))); } o = m_new_obj(py_cascade_obj_t); o->base.type = &py_cascade_type; o->_cobj = cascade; return o; } mp_obj_t py_imlib_load_template(mp_obj_t path_obj) { mp_obj_t image_obj =NULL; struct image *image; const char *path = mp_obj_str_get_str(path_obj); image_obj = py_image(0, 0, 0, 0); /* get image pointer */ image = py_image_cobj(image_obj); int res = imlib_load_template(image, path); if (res != FR_OK) { nlr_jump(mp_obj_new_exception_msg(qstr_from_str("Imlib"), ffs_strerror(res))); } return image_obj; }
/* store default values so that no crash due to undefined variable */ if (v->flags & PY_FLAG_ARRAY) { v->index = MP_OBJ_NEW_SMALL_INT(0); v->list = mp_obj_new_list((mp_uint_t)v->dim, v->items); obj = v->list; } else { obj = v->items[0]; } mp_store_name(v->name, obj); if (v->flags & PY_FLAG_FLOAT) { size = dim * sizeof(mp_float_t); data = (void**)&v->data.f; } else { size = dim * sizeof(mp_int_t); data = (void**)&v->data.i; } *data = malloc(size); if (*data == NULL) goto on_error_2; return v; on_error_2: free(v->items); on_error_1: free(v); on_error_0: return NULL; } static py_var_t* py_create_scalar (py_handle_t* py, const char* name, uint32_t flags) { return py_create_var(py, name, 1, flags); } static py_var_t* py_create_array (py_handle_t* py, const char* name, size_t dim, uint32_t flags) { return py_create_var(py, name, dim, flags | PY_FLAG_ARRAY); } static void py_destroy_var(py_var_t* v) { void* data; if (v->flags & PY_FLAG_FLOAT) data = (void*)v->data.f; else data = (void*)v->data.i; free(data); free(v->items); free(v); } static void py_print_var(py_var_t* v) { size_t i; for (i = 0; i != v->dim; ++i) { if (v->flags & PY_FLAG_INT) printf(" %d", v->data.i[i]); else printf(" %lf", v->data.f[i]); } printf("\n"); } static void py_print_out_vars(py_handle_t* py) { size_t i; for (i = 0; i != py->nvar; ++i) { py_var_t* const v = py->vars[i]; if ((v->flags & PY_FLAG_OUT) == 0) continue ; py_print_var(v); } } static int py_compile(py_handle_t* py, const char* s) { static const mp_parse_input_kind_t input_kind = MP_PARSE_FILE_INPUT; static const uint emit_opt = MP_EMIT_OPT_NATIVE_PYTHON; nlr_buf_t nlr; int err = -1; if (nlr_push(&nlr)) return -1; py->lex = mp_lexer_new_from_str_len (MP_QSTR__lt_stdin_gt_, s, strlen(s), false); if (py->lex == NULL) goto on_error_0; py->parse_tree = mp_parse(py->lex, input_kind); py->module_fun = mp_compile (&py->parse_tree, py->lex->source_name, emit_opt, false); err = 0; on_error_0: nlr_pop(); return err; } static int py_open(py_handle_t* py) { py->lex = NULL; py->nvar = 0; return 0; } static int py_close(py_handle_t* py) { size_t i; for (i = 0; i != py->nvar; ++i) py_destroy_var(py->vars[i]); return 0; } #if 0 /* does not work, should recompile entirely */ static int py_collect(py_handle_t* py) { mp_obj_t obj; size_t i; size_t j; gc_collect(); for (i = 0; i != py->nvar; ++i) { py_var_t* const v = py->vars[i]; v->name = qstr_from_str(v->_name); if (v->flags & PY_FLAG_INT) { for (j = 0; j != v->dim; ++j) { if (v->flags & PY_FLAG_IN) obj = MP_OBJ_NEW_SMALL_INT(v->in.i[j]); else obj = MP_OBJ_NEW_SMALL_INT(v->data.i[j]); v->items[j] = obj; } } else { for (j = 0; j != v->dim; ++j) { if (v->flags & PY_FLAG_IN) obj = mp_obj_new_float(v->in.f[j]); else obj = mp_obj_new_float(v->data.f[j]); v->items[j] = obj; } } /* store default values so that no crash due to undefined variable */ if (v->flags & PY_FLAG_ARRAY) { v->index = MP_OBJ_NEW_SMALL_INT(0); v->list = mp_obj_new_list((mp_uint_t)v->dim, v->items); obj = v->list; } else { obj = v->items[0]; } mp_store_name(v->name, obj); } return 0; }
static mp_obj_t py_image_median(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { int ksize = 1; /* get image pointer */ image_t *image = py_image_cobj(args[0]); mp_map_elem_t *kw_ksize = mp_map_lookup(kw_args, MP_OBJ_NEW_QSTR(qstr_from_str("size")), MP_MAP_LOOKUP); if (kw_ksize != NULL) { ksize = mp_obj_get_int(kw_ksize->value); } imlib_median_filter(image, ksize); return mp_const_none; }
mp_obj_t micropy_call_1(mp_obj_t module_obj, const char* func, const char* _arg0) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_obj_t py_func = mp_load_attr(module_obj, qstr_from_str(func)); mp_obj_t arg0 = mp_obj_new_str(_arg0, strnlen(_arg0,256)); mp_obj_t ret = mp_call_function_1(py_func, arg0); nlr_pop(); return ret; } else { mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); // uncaught exception return 0; } }
mp_obj_t py_file_write(py_file_obj_t *file, mp_obj_t buf) { uint len; const byte *str; FRESULT res; str = mp_obj_str_get_data(buf, &len); res = f_write(&file->fp, str, len, &len); if (res != FR_OK) { nlr_jump(mp_obj_new_exception_msg(qstr_from_str("File"), ffs_strerror(res))); } return mp_obj_new_int(len); }
void pyb_usb_dev_init(void) { #ifdef USE_DEVICE_MODE if (!dev_is_enabled) { // only init USB once in the device's power-lifetime USBD_Init(&USB_OTG_Core, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_PYB_cb, &USR_cb); //USBD_Init(&USB_OTG_Core, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_PYB_HID_cb, &USR_cb); } rx_buf_in = 0; rx_buf_out = 0; interrupt_char = VCP_CHAR_NONE; dev_is_enabled = 1; // create an exception object for interrupting by VCP mp_const_vcp_interrupt = mp_obj_new_exception(qstr_from_str("VCPInterrupt")); #endif }
mp_lexer_t *mp_lexer_new_from_file(const char *filename) { mp_lexer_file_buf_t *fb = m_new_obj_maybe(mp_lexer_file_buf_t); if (fb == NULL) { return NULL; } FRESULT res = f_open(&fb->fp, filename, FA_READ); if (res != FR_OK) { m_del_obj(mp_lexer_file_buf_t, fb); return NULL; } UINT n; f_read(&fb->fp, fb->buf, sizeof(fb->buf), &n); fb->len = n; fb->pos = 0; return mp_lexer_new(qstr_from_str(filename), fb, (mp_lexer_stream_next_byte_t)file_buf_next_byte, (mp_lexer_stream_close_t)file_buf_close); }
mp_obj_t micropy_call_2(mp_obj_t module_obj, const char *func, uint64_t code, uint64_t type) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_obj_t py_func = mp_load_attr(module_obj, qstr_from_str(func)); mp_obj_t arg0 = mp_obj_new_int_from_ll((long long)code); mp_obj_t arg1 = mp_obj_new_int_from_ll((long long)type); mp_obj_t ret = mp_call_function_2(py_func, arg0, arg1); nlr_pop(); return ret; } else { mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); // uncaught exception return 0; } }
STATIC mp_obj_t mod_socket_getaddrinfo(uint n_args, const mp_obj_t *args) { // TODO: Implement all args assert(n_args == 2); assert(MP_OBJ_IS_STR(args[0])); const char *host = mp_obj_str_get_str(args[0]); const char *serv = NULL; // getaddrinfo accepts port in string notation, so however // it may seem stupid, we need to convert int to str if (MP_OBJ_IS_SMALL_INT(args[1])) { int port = (short)MP_OBJ_SMALL_INT_VALUE(args[1]); char buf[6]; sprintf(buf, "%d", port); serv = buf; } else { serv = mp_obj_str_get_str(args[1]); } struct addrinfo hints; struct addrinfo *addr; memset(&hints, 0, sizeof(hints)); int res = getaddrinfo(host, serv, NULL/*&hints*/, &addr); if (res != 0) { // CPython: socket.gaierror nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[addrinfo error %d]", res)); } assert(addr); mp_obj_t list = mp_obj_new_list(0, NULL); for (; addr; addr = addr->ai_next) { mp_obj_tuple_t *t = mp_obj_new_tuple(5, NULL); t->items[0] = MP_OBJ_NEW_SMALL_INT((machine_int_t)addr->ai_family); t->items[1] = MP_OBJ_NEW_SMALL_INT((machine_int_t)addr->ai_socktype); t->items[2] = MP_OBJ_NEW_SMALL_INT((machine_int_t)addr->ai_protocol); // "canonname will be a string representing the canonical name of the host // if AI_CANONNAME is part of the flags argument; else canonname will be empty." ?? if (addr->ai_canonname) { t->items[3] = MP_OBJ_NEW_QSTR(qstr_from_str(addr->ai_canonname)); } else { t->items[3] = mp_const_none; } t->items[4] = mp_obj_new_bytearray(addr->ai_addrlen, addr->ai_addr); mp_obj_list_append(list, t); } return list; }
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; } }
mp_lexer_t *mp_lexer_new_from_file(const char *filename) { int fd = open(filename, O_RDONLY); if (fd < 0) { return NULL; } uint size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); char *data = m_new(char, size); int read_size = read(fd, data, size); close(fd); if (read_size != size) { printf("error reading file %s\n", filename); m_del(char, data, size); return NULL; } return mp_lexer_new_from_str_len(qstr_from_str(filename), data, size, size); }
//mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) int compile_and_save_to_buffer(const char* src_name, const char *src_buffer, size_t src_size, char* buffer, size_t size) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { // mp_lexer_t *lex = mp_lexer_new_from_file(file); mp_lexer_t *lex = mp_lexer_new_from_str_len(qstr_from_str(src_name), src_buffer, src_size, false); qstr source_name; source_name = lex->source_name; 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); int length = mp_raw_code_save_to_buffer(rc, buffer, size); nlr_pop(); return length; } else { // uncaught exception mp_obj_print_exception(&mp_stderr_print, (mp_obj_t)nlr.ret_val); return 0; } }
STATIC void set_sys_argv(char *argv[], int argc, int start_arg) { for (int i = start_arg; i < argc; i++) { mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i]))); } }
STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { // TODO: Implement 5th and 6th args const char *host = mp_obj_str_get_str(args[0]); const char *serv = NULL; struct addrinfo hints; char buf[6]; memset(&hints, 0, sizeof(hints)); // getaddrinfo accepts port in string notation, so however // it may seem stupid, we need to convert int to str if (MP_OBJ_IS_SMALL_INT(args[1])) { unsigned port = (unsigned short)MP_OBJ_SMALL_INT_VALUE(args[1]); snprintf(buf, sizeof(buf), "%u", port); serv = buf; hints.ai_flags = AI_NUMERICSERV; #ifdef __UCLIBC_MAJOR__ #if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32)) // "warning" requires -Wno-cpp which is a relatively new gcc option, so we choose not to use it. //#warning Working around uClibc bug with numeric service name // Older versions og uClibc have bugs when numeric ports in service // arg require also hints.ai_socktype (or hints.ai_protocol) != 0 // This actually was fixed in 0.9.32.1, but uClibc doesn't allow to // test for that. // http://git.uclibc.org/uClibc/commit/libc/inet/getaddrinfo.c?id=bc3be18145e4d5 // Note that this is crude workaround, precluding UDP socket addresses // to be returned. TODO: set only if not set by Python args. hints.ai_socktype = SOCK_STREAM; #endif #endif } else { serv = mp_obj_str_get_str(args[1]); } if (n_args > 2) { hints.ai_family = MP_OBJ_SMALL_INT_VALUE(args[2]); if (n_args > 3) { hints.ai_socktype = MP_OBJ_SMALL_INT_VALUE(args[3]); } } struct addrinfo *addr_list; int res = getaddrinfo(host, serv, &hints, &addr_list); if (res != 0) { // CPython: socket.gaierror nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[addrinfo error %d]", res)); } assert(addr_list); mp_obj_t list = mp_obj_new_list(0, NULL); for (struct addrinfo *addr = addr_list; addr; addr = addr->ai_next) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(addr->ai_family); t->items[1] = MP_OBJ_NEW_SMALL_INT(addr->ai_socktype); t->items[2] = MP_OBJ_NEW_SMALL_INT(addr->ai_protocol); // "canonname will be a string representing the canonical name of the host // if AI_CANONNAME is part of the flags argument; else canonname will be empty." ?? if (addr->ai_canonname) { t->items[3] = MP_OBJ_NEW_QSTR(qstr_from_str(addr->ai_canonname)); } else { t->items[3] = mp_const_none; } t->items[4] = mp_obj_new_bytearray(addr->ai_addrlen, addr->ai_addr); mp_obj_list_append(list, MP_OBJ_FROM_PTR(t)); } freeaddrinfo(addr_list); return list; }
mp_lexer_t *mp_lexer_new_from_file(const char *filename) { mp_reader_t reader; mp_reader_new_file(&reader, filename); return mp_lexer_new(qstr_from_str(filename), reader); }
int main(int argc, char **argv) { mp_stack_set_limit(32768); pre_process_options(argc, argv); #if MICROPY_ENABLE_GC char *heap = malloc(heap_size); gc_init(heap, heap + heap_size); #endif mp_init(); char *home = getenv("HOME"); char *path = getenv("MICROPYPATH"); if (path == NULL) { path = "~/.micropython/lib:/usr/lib/micropython"; } 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 (int 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, 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); mp_store_name(qstr_from_str("mem_info"), (mp_obj_t*)&mem_info_obj); mp_store_name(qstr_from_str("qstr_info"), (mp_obj_t*)&qstr_info_obj); // 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]); a += 1; } 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_optimise_value = argv[a][2] & 0xf; } else { mp_optimise_value = 0; for (char *p = argv[a] + 1; *p && *p == 'O'; p++, 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); for (int i = a; i < argc; i++) { mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i]))); } ret = do_file(argv[a]); break; } } if (ret == NOTHING_EXECUTED) { do_repl(); ret = 0; } mp_deinit(); //printf("total bytes = %d\n", m_get_total_bytes_allocated()); return ret; }
int pyexec_friendly_repl(void) { vstr_t line; vstr_init(&line, 32); #if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD // in host mode, we enable the LCD for the repl mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD"))); mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true); #endif friendly_repl_reset: mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n"); #if MICROPY_PY_BUILTINS_HELP mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n"); #endif // to test ctrl-C /* { uint32_t x[4] = {0x424242, 0xdeaddead, 0x242424, 0xdeadbeef}; for (;;) { nlr_buf_t nlr; printf("pyexec_repl: %p\n", x); mp_hal_set_interrupt_char(CHAR_CTRL_C); if (nlr_push(&nlr) == 0) { for (;;) { } } else { printf("break\n"); } } } */ for (;;) { input_restart: #if defined(USE_DEVICE_MODE) if (usb_vcp_is_enabled()) { // If the user gets to here and interrupts are disabled then // they'll never see the prompt, traceback etc. The USB REPL needs // interrupts to be enabled or no transfers occur. So we try to // do the user a favor and reenable interrupts. if (query_irq() == IRQ_STATE_DISABLED) { enable_irq(IRQ_STATE_ENABLED); mp_hal_stdout_tx_str("PYB: enabling IRQs\r\n"); } } #endif vstr_reset(&line); int ret = readline(&line, ">>> "); mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT; if (ret == CHAR_CTRL_A) { // change to raw REPL mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); pyexec_mode_kind = PYEXEC_MODE_RAW_REPL; return 0; } else if (ret == CHAR_CTRL_B) { // reset friendly REPL mp_hal_stdout_tx_str("\r\n"); goto friendly_repl_reset; } else if (ret == CHAR_CTRL_C) { // break mp_hal_stdout_tx_str("\r\n"); continue; } else if (ret == CHAR_CTRL_D) { // exit for a soft reset mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); return PYEXEC_FORCED_EXIT; } else if (ret == CHAR_CTRL_E) { // paste mode mp_hal_stdout_tx_str("\r\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\r\n=== "); vstr_reset(&line); for (;;) { char c = mp_hal_stdin_rx_chr(); if (c == CHAR_CTRL_C) { // cancel everything mp_hal_stdout_tx_str("\r\n"); goto input_restart; } else if (c == CHAR_CTRL_D) { // end of input mp_hal_stdout_tx_str("\r\n"); break; } else { // add char to buffer and echo vstr_add_byte(&line, c); if (c == '\r') { mp_hal_stdout_tx_str("\r\n=== "); } else { mp_hal_stdout_tx_strn(&c, 1); } } } parse_input_kind = MP_PARSE_FILE_INPUT; } else if (vstr_len(&line) == 0) { continue; } else { // got a line with non-zero length, see if it needs continuing while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) { vstr_add_byte(&line, '\n'); ret = readline(&line, "... "); if (ret == CHAR_CTRL_C) { // cancel everything mp_hal_stdout_tx_str("\r\n"); goto input_restart; } else if (ret == CHAR_CTRL_D) { // stop entering compound statement break; } } } ret = parse_compile_execute(&line, parse_input_kind, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR); if (ret & PYEXEC_FORCED_EXIT) { return ret; } } }
void main_netload(int argc, char **argv) { bool restart = true; while (restart) { int ret = run_file("romfs:/netload.py", argc, argv, true); if (ret == ERR_PARSE) { restart = fatal_error(false); } else if (ret == ERR_NETLOAD) { restart = false; } else { mp_obj_dict_t *globals = mp_globals_get(); qstr filename_qstr = qstr_from_str("monty_filename"); qstr filetype_qstr = qstr_from_str("monty_filetype"); qstr cancel_qstr = qstr_from_str("monty_cancel"); mp_obj_t monty_filename = MP_OBJ_NEW_QSTR(filename_qstr); mp_obj_t monty_filetype = MP_OBJ_NEW_QSTR(filetype_qstr); mp_obj_t monty_cancel = MP_OBJ_NEW_QSTR(cancel_qstr); mp_map_elem_t *filename_item = mp_map_lookup(&globals->map, monty_filename, MP_MAP_LOOKUP); mp_map_elem_t *filetype_item = mp_map_lookup(&globals->map, monty_filetype, MP_MAP_LOOKUP); mp_map_elem_t *cancel_item = mp_map_lookup(&globals->map, monty_cancel, MP_MAP_LOOKUP); if (cancel_item != NULL && mp_obj_is_true(cancel_item->value)) { restart = false; break; } const char *filename = ""; if (filename_item != NULL) { filename = mp_obj_str_get_str(filename_item->value); } char file_path[PATH_MAX]; sprintf(file_path, "sdmc:/monty3ds/%s", filename); int type = TYPE_NONE; if (filetype_item != NULL) { type = mp_obj_get_int(filetype_item->value); } switch (type) { case TYPE_PY: { ret = run_file(file_path, argc, argv, true); break; } case TYPE_ZIP: { zipfs_handle_t handle = zipfs_mount(file_path, "zip"); zipfs_set_default(handle); ret = boot_file("zip:/", "boot", argc, argv, true); zipfs_unmount(handle); break; } default: continue; } if (ret) { restart = fatal_error(true); } } } mod_citrus_exit_all(); }
int main(int argc, char **argv) { volatile int stack_dummy; stack_top = (void*)&stack_dummy; pre_process_options(argc, argv); #if MICROPY_ENABLE_GC char *heap = malloc(heap_size); gc_init(heap, heap + heap_size); #endif qstr_init(); mp_init(); char *home = getenv("HOME"); char *path = getenv("MICROPYPATH"); if (path == NULL) { path = "~/.micropython/lib:/usr/lib/micropython"; } uint path_num = 1; // [0] is for current dir (or base dir of the script) for (char *p = path; p != NULL; p = strchr(p, ':')) { 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 (int i = 1; i < path_num; i++) { char *p1 = strchr(p, ':'); 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, 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); mp_store_name(qstr_from_str("test"), test_obj_new(42)); mp_store_name(qstr_from_str("mem_info"), mp_make_function_n(0, mem_info)); mp_store_name(qstr_from_str("qstr_info"), mp_make_function_n(0, qstr_info)); #if MICROPY_ENABLE_GC mp_store_name(qstr_from_str("gc"), (mp_obj_t)&pyb_gc_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()); */ bool executed = false; for (int a = 1; a < argc; a++) { if (argv[a][0] == '-') { if (strcmp(argv[a], "-c") == 0) { if (a + 1 >= argc) { return usage(argv); } do_str(argv[a + 1]); executed = true; a += 1; } else if (strcmp(argv[a], "-X") == 0) { a += 1; } else { return usage(argv); } } else { char *basedir = realpath(argv[a], NULL); if (basedir == NULL) { fprintf(stderr, "%s: can't open file '%s': [Errno %d] ", argv[0], argv[1], errno); perror(""); // CPython exits with 2 in such case exit(2); } // 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(basedir); for (int i = a; i < argc; i++) { mp_obj_list_append(mp_sys_argv, MP_OBJ_NEW_QSTR(qstr_from_str(argv[i]))); } do_file(argv[a]); executed = true; break; } } if (!executed) { do_repl(); } mp_deinit(); //printf("total bytes = %d\n", m_get_total_bytes_allocated()); return 0; }
static py_var_t* py_create_var (py_handle_t* py, const char* name, size_t dim, uint32_t flags) { py_var_t* v; mp_obj_t obj; size_t i; size_t size; void** data; v = malloc(sizeof(py_var_t)); if (v == NULL) goto on_error_0; py->vars[py->nvar] = v; ++py->nvar; v->name = qstr_from_str(name); v->flags = flags; v->dim = dim; v->items = malloc(dim * sizeof(mp_obj_t)); if (v->items == NULL) goto on_error_1; if (v->flags & PY_FLAG_INT) { for (i = 0; i != dim; ++i) v->items[i] = MP_OBJ_NEW_SMALL_INT(0); } else { for (i = 0; i != dim; ++i) v->items[i] = mp_obj_new_float(0.0); } /* store default values so that no crash due to undefined variable */ if (v->flags & PY_FLAG_ARRAY) { v->index = MP_OBJ_NEW_SMALL_INT(0); v->list = mp_obj_new_list((mp_uint_t)v->dim, v->items); obj = v->list; } else { obj = v->items[0]; } mp_store_name(v->name, obj); if (v->flags & PY_FLAG_FLOAT) { size = dim * sizeof(mp_float_t); data = (void**)&v->data.f; } else { size = dim * sizeof(mp_int_t); data = (void**)&v->data.i; } *data = malloc(size); if (*data == NULL) goto on_error_2; return v; on_error_2: free(v->items); on_error_1: free(v); on_error_0: return NULL; }
int pyexec_friendly_repl(void) { vstr_t line; vstr_init(&line, 32); #if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD // in host mode, we enable the LCD for the repl mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD"))); mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true); #endif friendly_repl_reset: mp_hal_stdout_tx_str("Micro Python " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n"); mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n"); // to test ctrl-C /* { uint32_t x[4] = {0x424242, 0xdeaddead, 0x242424, 0xdeadbeef}; for (;;) { nlr_buf_t nlr; printf("pyexec_repl: %p\n", x); mp_hal_set_interrupt_char(CHAR_CTRL_C); if (nlr_push(&nlr) == 0) { for (;;) { } } else { printf("break\n"); } } } */ for (;;) { input_restart: vstr_reset(&line); int ret = readline(&line, ">>> "); if (ret == CHAR_CTRL_A) { // change to raw REPL mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); pyexec_mode_kind = PYEXEC_MODE_RAW_REPL; return 0; } else if (ret == CHAR_CTRL_B) { // reset friendly REPL mp_hal_stdout_tx_str("\r\n"); goto friendly_repl_reset; } else if (ret == CHAR_CTRL_C) { // break mp_hal_stdout_tx_str("\r\n"); continue; } else if (ret == CHAR_CTRL_D) { // exit for a soft reset mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); return PYEXEC_FORCED_EXIT; } else if (vstr_len(&line) == 0) { continue; } while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) { vstr_add_byte(&line, '\n'); ret = readline(&line, "... "); if (ret == CHAR_CTRL_C) { // cancel everything mp_hal_stdout_tx_str("\r\n"); goto input_restart; } else if (ret == CHAR_CTRL_D) { // stop entering compound statement break; } } mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr_str(&line), vstr_len(&line), 0); if (lex == NULL) { printf("MemoryError\n"); } else { ret = parse_compile_execute(lex, MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL); if (ret & PYEXEC_FORCED_EXIT) { return ret; } } } }