/** * def write(self, mask) */ static mp_obj_t class_queue_write(mp_obj_t self_in, mp_obj_t buf_in) { struct class_queue_t *self_p; mp_buffer_info_t bufinfo; ssize_t res; self_p = MP_OBJ_TO_PTR(self_in); mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); res = queue_write(&self_p->queue, bufinfo.buf, bufinfo.len); if (res <= 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "failed to write to queue")); } return (MP_OBJ_NEW_SMALL_INT(res)); }
/// \function repl_uart(uart) /// Get or set the UART object that the REPL is repeated on. STATIC mp_obj_t pyb_repl_uart(mp_uint_t n_args, const mp_obj_t *args) { if (n_args == 0) { if (pyb_stdio_uart == NULL) { return mp_const_none; } else { return pyb_stdio_uart; } } else { if (args[0] == mp_const_none) { pyb_stdio_uart = NULL; } else if (mp_obj_get_type(args[0]) == &pyb_uart_type) { pyb_stdio_uart = args[0]; } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "need a UART object")); } return mp_const_none; } }
mp_obj_t mp_obj_new_int_from_float(mp_float_t val) { int cl = fpclassify(val); if (cl == FP_INFINITE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OverflowError, "can't convert inf to int")); } else if (cl == FP_NAN) { mp_raise_ValueError("can't convert NaN to int"); } else { mp_fp_as_int_class_t icl = mp_classify_fp_as_int(val); if (icl == MP_FP_CLASS_FIT_SMALLINT) { return MP_OBJ_NEW_SMALL_INT((mp_int_t)val); #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ } else { mp_obj_int_t *o = mp_obj_int_new_mpz(); mpz_set_from_float(&o->mpz, val); return MP_OBJ_FROM_PTR(o); } #else #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG } else if (icl == MP_FP_CLASS_FIT_LONGINT) {
STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value) { if (value == MP_OBJ_NULL) { // delete item // TODO implement // TODO: confirmed that both bytearray and array.array support // slice deletion return MP_OBJ_NULL; // op not supported } else { mp_obj_array_t *o = self_in; if (0) { #if MICROPY_PY_BUILTINS_SLICE } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { if (value != MP_OBJ_SENTINEL) { // Only getting a slice is suported so far, not assignment // TODO: confirmed that both bytearray and array.array support // slice assignment (incl. of different size) return MP_OBJ_NULL; // op not supported } mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, "only slices with step=1 (aka None) are supported")); } mp_obj_array_t *res = array_new(o->typecode, slice.stop - slice.start); int sz = mp_binary_get_size('@', o->typecode, NULL); assert(sz > 0); byte *p = o->items; memcpy(res->items, p + slice.start * sz, (slice.stop - slice.start) * sz); return res; #endif } else { uint index = mp_get_index(o->base.type, o->len, index_in, false); if (value == MP_OBJ_SENTINEL) { // load return mp_binary_get_val_array(o->typecode, o->items, index); } else { // store mp_binary_set_val_array(o->typecode, o->items, index, value); return mp_const_none; } } } }
/** * def read(self, mask) */ static mp_obj_t class_queue_read(mp_obj_t self_in, mp_obj_t size_in) { struct class_queue_t *self_p; vstr_t vstr; size_t size; self_p = MP_OBJ_TO_PTR(self_in); size = mp_obj_get_int(size_in); vstr_init_len(&vstr, size); size = queue_read(&self_p->queue, vstr.buf, size); if (size <= 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "failed to read from queue")); } return (mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr)); }
STATIC mp_obj_array_t *array_new(char typecode, mp_uint_t n) { int typecode_size = mp_binary_get_size('@', typecode, NULL); if (typecode_size == 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad typecode")); } mp_obj_array_t *o = m_new_obj(mp_obj_array_t); #if MICROPY_PY_BUILTINS_BYTEARRAY && MICROPY_PY_ARRAY o->base.type = (typecode == BYTEARRAY_TYPECODE) ? &mp_type_bytearray : &mp_type_array; #elif MICROPY_PY_BUILTINS_BYTEARRAY o->base.type = &mp_type_bytearray; #else o->base.type = &mp_type_array; #endif o->typecode = typecode; o->free = 0; o->len = n; o->items = m_new(byte, typecode_size * o->len); return o; }
STATIC mp_obj_t list_pop(uint n_args, const mp_obj_t *args) { assert(1 <= n_args && n_args <= 2); assert(MP_OBJ_IS_TYPE(args[0], &mp_type_list)); mp_obj_list_t *self = args[0]; if (self->len == 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "pop from empty list")); } uint index = mp_get_index(self->base.type, self->len, n_args == 1 ? MP_OBJ_NEW_SMALL_INT(-1) : args[1], false); mp_obj_t ret = self->items[index]; self->len -= 1; memcpy(self->items + index, self->items + index + 1, (self->len - index) * sizeof(mp_obj_t)); // Clear stale pointer from slot which just got freed to prevent GC issues self->items[self->len] = MP_OBJ_NULL; if (self->alloc > LIST_MIN_ALLOC && self->alloc > 2 * self->len) { self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc/2); self->alloc /= 2; } return ret; }
STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) { #if MICROPY_CPYTHON_COMPAT if (n_kw != 0) { mp_arg_error_unimpl_kw(); } #endif switch (n_args) { case 0: return MP_OBJ_NEW_QSTR(MP_QSTR_); case 1: { vstr_t *vstr = vstr_new(); mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR); mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false); vstr_free(vstr); return s; } case 2: case 3: { // TODO: validate 2nd/3rd args if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) { GET_STR_DATA_LEN(args[0], str_data, str_len); GET_STR_HASH(args[0], str_hash); mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len); o->data = str_data; o->hash = str_hash; return o; } else { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); return mp_obj_new_str(bufinfo.buf, bufinfo.len, false); } } default: nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments")); } }
void mp_arg_check_num(mp_uint_t n_args, mp_uint_t n_kw, mp_uint_t n_args_min, mp_uint_t n_args_max, bool takes_kw) { // TODO maybe take the function name as an argument so we can print nicer error messages if (n_kw && !takes_kw) { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_arg_error_terse_mismatch(); } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "function does not take keyword arguments")); } } if (n_args_min == n_args_max) { if (n_args != n_args_min) { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_arg_error_terse_mismatch(); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function takes %d positional arguments but %d were given", n_args_min, n_args)); } } } else { if (n_args < n_args_min) { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_arg_error_terse_mismatch(); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function missing %d required positional arguments", n_args_min - n_args)); } } else if (n_args > n_args_max) { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { mp_arg_error_terse_mismatch(); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "function expected at most %d arguments, got %d", n_args_max, n_args)); } } } }
STATIC mp_obj_t usart_obj_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { // check arguments if (!(n_args == 2 && n_kw == 0)) { nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "Usart accepts 2 arguments")); } if (mp_obj_get_int(args[0]) > PYB_USART_MAX) { return mp_const_none; } pyb_usart_obj_t *o = m_new_obj(pyb_usart_obj_t); o->base.type = &pyb_usart_type; o->usart_id = mp_obj_get_int(args[0]); o->is_enabled = true; /* init USART */ usart_init(o, mp_obj_get_int(args[1])); return o; }
STATIC mp_obj_t dict_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_NULL) { // delete mp_obj_dict_delete(self_in, index); return mp_const_none; } else if (value == MP_OBJ_SENTINEL) { // load mp_obj_dict_t *self = self_in; mp_map_elem_t *elem = mp_map_lookup(&self->map, index, MP_MAP_LOOKUP); if (elem == NULL) { nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "<value>")); } else { return elem->value; } } else { // store mp_obj_dict_store(self_in, index, value); return mp_const_none; } }
STATIC mp_obj_t gen_instance_close(mp_obj_t self_in) { mp_obj_t ret; switch (mp_obj_gen_resume(self_in, mp_const_none, (mp_obj_t)&mp_const_GeneratorExit_obj, &ret)) { case MP_VM_RETURN_YIELD: nlr_raise(mp_obj_new_exception_msg(&mp_type_RuntimeError, "generator ignored GeneratorExit")); // Swallow StopIteration & GeneratorExit (== successful close), and re-raise any other case MP_VM_RETURN_EXCEPTION: // ret should always be an instance of an exception class if (mp_obj_is_subclass_fast(mp_obj_get_type(ret), &mp_type_GeneratorExit) || mp_obj_is_subclass_fast(mp_obj_get_type(ret), &mp_type_StopIteration)) { return mp_const_none; } nlr_raise(ret); default: // The only choice left is MP_VM_RETURN_NORMAL which is successful close return mp_const_none; } }
// method socket.connect(address) STATIC mp_obj_t esp_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { esp_socket_obj_t *s = self_in; if (s->espconn == NULL || s->espconn->state != ESPCONN_NONE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "transport endpoint is already connected or closed")); } espconn_regist_connectcb(s->espconn, esp_socket_connect_callback_client); espconn_regist_recvcb(s->espconn, esp_socket_recv_callback); espconn_regist_sentcb(s->espconn, esp_socket_sent_callback); espconn_regist_disconcb(s->espconn, esp_socket_disconnect_callback); s->espconn->proto.tcp->remote_port = netutils_parse_inet_addr(addr_in, s->espconn->proto.tcp->remote_ip, NETUTILS_BIG); espconn_connect(s->espconn); return mp_const_none; }
// method socket.recv(bufsize) STATIC mp_obj_t socket_recv(mp_obj_t self_in, mp_obj_t len_in) { mod_network_socket_obj_t *self = self_in; mp_int_t len = mp_obj_get_int(len_in); vstr_t vstr; vstr_init_len(&vstr, len); int _errno; mp_int_t ret = wlan_socket_recv(self, (byte*)vstr.buf, len, &_errno); if (ret < 0) { if (_errno == EAGAIN && self->sock_base.has_timeout) { nlr_raise(mp_obj_new_exception_msg(&mp_type_TimeoutError, "timed out")); } nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(-_errno))); } if (ret == 0) { return mp_const_empty_bytes; } vstr.len = ret; vstr.buf[vstr.len] = '\0'; return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); }
STATIC mp_obj_t dict_get_helper(mp_map_t *self, mp_obj_t key, mp_obj_t deflt, mp_map_lookup_kind_t lookup_kind) { mp_map_elem_t *elem = mp_map_lookup(self, key, lookup_kind); mp_obj_t value; if (elem == NULL || elem->value == NULL) { if (deflt == NULL) { if (lookup_kind == MP_MAP_LOOKUP_REMOVE_IF_FOUND) { nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "<value>")); } else { value = mp_const_none; } } else { value = deflt; } } else { value = elem->value; } if (lookup_kind == MP_MAP_LOOKUP_ADD_IF_NOT_FOUND) { elem->value = value; } return value; }
/// \method scan() /// Scan all I2C addresses from 0x01 to 0x7f and return a list of those that respond. /// Only valid when in master mode. STATIC mp_obj_t pyb_i2c_scan(mp_obj_t self_in) { pyb_i2c_obj_t *self = self_in; if (!in_master_mode(self)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "I2C must be a master")); } mp_obj_t list = mp_obj_new_list(0, NULL); for (uint addr = 1; addr <= 127; addr++) { for (int i = 0; i < 10; i++) { HAL_StatusTypeDef status = HAL_I2C_IsDeviceReady(self->i2c, addr << 1, 10, 200); if (status == HAL_OK) { mp_obj_list_append(list, mp_obj_new_int(addr)); break; } } } return list; }
STATIC mp_obj_t network_server_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *all_args) { // parse args mp_map_t kw_args; mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); mp_arg_val_t args[MP_ARRAY_SIZE(network_server_args)]; mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), network_server_args, args); // check the server id if (args[0].u_obj != MP_OBJ_NULL) { if (mp_obj_get_int(args[0].u_obj) != 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_resource_not_avaliable)); } } // setup the object and initialize it network_server_obj_t *self = &network_server_obj; self->base.type = &network_server_type; network_server_init_helper(self, &args[1]); return (mp_obj_t)self; }
STATIC void do_load_from_lexer(mp_obj_t module_obj, mp_lexer_t *lex, const char *fname) { if (lex == NULL) { // we verified the file exists using stat, but lexer could still fail if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ImportError, "module not found")); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "no module named '%s'", fname)); } } #if MICROPY_PY___FILE__ qstr source_name = lex->source_name; mp_store_attr(module_obj, MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); #endif // parse, compile and execute the module in its context mp_obj_dict_t *mod_globals = mp_obj_module_get_globals(module_obj); mp_parse_compile_execute(lex, MP_PARSE_FILE_INPUT, mod_globals, mod_globals); }
mp_float_t mp_obj_get_float(mp_obj_t arg) { if (arg == mp_const_false) { return 0; } else if (arg == mp_const_true) { return 1; } else if (MP_OBJ_IS_SMALL_INT(arg)) { return MP_OBJ_SMALL_INT_VALUE(arg); } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { return mp_obj_int_as_float(arg); } else if (mp_obj_is_float(arg)) { return mp_obj_float_get(arg); } else { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "can't convert to float")); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "can't convert %s to float", mp_obj_get_type_str(arg))); } } }
mp_int_t mp_obj_hash(mp_obj_t o_in) { if (o_in == mp_const_false) { return 0; // needs to hash to same as the integer 0, since False==0 } else if (o_in == mp_const_true) { return 1; // needs to hash to same as the integer 1, since True==1 } else if (MP_OBJ_IS_SMALL_INT(o_in)) { return MP_OBJ_SMALL_INT_VALUE(o_in); } else if (MP_OBJ_IS_TYPE(o_in, &mp_type_int)) { return mp_obj_int_hash(o_in); } else if (MP_OBJ_IS_STR(o_in) || MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) { return mp_obj_str_get_hash(o_in); } else if (MP_OBJ_IS_TYPE(o_in, &mp_type_NoneType)) { return (mp_int_t)o_in; } else if (MP_OBJ_IS_FUN(o_in)) { return (mp_int_t)o_in; } else if (MP_OBJ_IS_TYPE(o_in, &mp_type_tuple)) { return mp_obj_tuple_hash(o_in); } else if (MP_OBJ_IS_TYPE(o_in, &mp_type_type)) { return (mp_int_t)o_in; } else if (MP_OBJ_IS_OBJ(o_in)) { // if a valid __hash__ method exists, use it mp_obj_t hash_method[2]; mp_load_method_maybe(o_in, MP_QSTR___hash__, hash_method); if (hash_method[0] != MP_OBJ_NULL) { mp_obj_t hash_val = mp_call_method_n_kw(0, 0, hash_method); if (MP_OBJ_IS_INT(hash_val)) { return mp_obj_int_get_truncated(hash_val); } } } // TODO hash class and instances - in CPython by default user created classes' __hash__ resolves to their id if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "unhashable type")); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "unhashable type: '%s'", mp_obj_get_type_str(o_in))); } }
void pyb_usb_dev_init(usbd_device_kind_t device_kind, usbd_storage_medium_kind_t medium_kind) { #ifdef USE_DEVICE_MODE if (!dev_is_enabled) { // only init USB once in the device's power-lifetime switch (device_kind) { case USBD_DEVICE_CDC: // XXX USBD_CDC_Init (called by one of these functions below) uses malloc, // so the memory is invalid after a soft reset (which resets the GC). USBD_Init(&hUSBDDevice, &VCP_Desc, 0); USBD_RegisterClass(&hUSBDDevice, &USBD_CDC); USBD_CDC_RegisterInterface(&hUSBDDevice, (USBD_CDC_ItfTypeDef*)&USBD_CDC_fops); USBD_Start(&hUSBDDevice); //USBD_Init(&USB_OTG_Core, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_PYB_cb, &USR_cb); break; case USBD_DEVICE_MSC: // XXX USBD_CDC_Init (called by one of these functions below) uses malloc, // so the memory is invalid after a soft reset (which resets the GC). USBD_Init(&hUSBDDevice, &MSC_Desc, 0); USBD_RegisterClass(&hUSBDDevice, &USBD_MSC); if (medium_kind == USBD_STORAGE_MEDIUM_FLASH) { USBD_MSC_RegisterStorage(&hUSBDDevice, (USBD_StorageTypeDef*)&USBD_FLASH_STORAGE_fops); } else { USBD_MSC_RegisterStorage(&hUSBDDevice, (USBD_StorageTypeDef*)&USBD_SDCARD_STORAGE_fops); } USBD_Start(&hUSBDDevice); break; case USBD_DEVICE_HID: //USBD_Init(&USB_OTG_Core, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_PYB_HID_cb, &USR_cb); // TODO break; } } dev_is_enabled = 1; // create an exception object for interrupting by VCP mp_const_vcp_interrupt = mp_obj_new_exception_msg(&mp_type_OSError, "VCPInterrupt"); #endif }
STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *self, mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { // parse args mp_arg_val_t vals[PYB_TIMER_INIT_NUM_ARGS]; mp_arg_parse_all(n_args, args, kw_args, PYB_TIMER_INIT_NUM_ARGS, pyb_timer_init_args, vals); // set the TIM configuration values TIM_Base_InitTypeDef *init = &self->tim.Init; if (vals[0].u_int != 0xffffffff) { // set prescaler and period from frequency if (vals[0].u_int == 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't have 0 frequency")); } // work out TIM's clock source uint tim_clock; if (self->tim_id == 1 || (8 <= self->tim_id && self->tim_id <= 11)) { // TIM{1,8,9,10,11} are on APB2 tim_clock = HAL_RCC_GetPCLK2Freq(); } else { // TIM{2,3,4,5,6,7,12,13,14} are on APB1 tim_clock = HAL_RCC_GetPCLK1Freq(); } // Compute the prescaler value so TIM triggers at freq-Hz // On STM32F405/407/415/417 there are 2 cases for how the clock freq is set. // If the APB prescaler is 1, then the timer clock is equal to its respective // APB clock. Otherwise (APB prescaler > 1) the timer clock is twice its // respective APB clock. See DM00031020 Rev 4, page 115. uint32_t period = MAX(1, 2 * tim_clock / vals[0].u_int); uint32_t prescaler = 1; while (period > TIMER_CNT_MASK(self)) { period >>= 1; prescaler <<= 1; } init->Prescaler = prescaler - 1; init->Period = period - 1; } else if (vals[1].u_int != 0xffffffff && vals[2].u_int != 0xffffffff) {
STATIC mp_obj_t mod_re_compile(mp_uint_t n_args, const mp_obj_t *args) { const char *re_str = mp_obj_str_get_str(args[0]); int size = re1_5_sizecode(re_str); if (size == -1) { goto error; } mp_obj_re_t *o = m_new_obj_var(mp_obj_re_t, char, size); o->base.type = &re_type; int flags = 0; if (n_args > 1) { flags = mp_obj_get_int(args[1]); } int error = re1_5_compilecode(&o->re, re_str); if (error != 0) { error: nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Error in regex")); } if (flags & FLAG_DEBUG) { re1_5_dumpcode(&o->re); } return MP_OBJ_FROM_PTR(o); }
// method socket.recv(bufsize) STATIC mp_obj_t esp_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { esp_socket_obj_t *s = self_in; if (s->recvbuf == NULL) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "no data available")); } mp_uint_t mxl = mp_obj_get_int(len_in); if (mxl >= s->recvbuf_len) { mp_obj_t trt = mp_obj_new_bytes(s->recvbuf, s->recvbuf_len); gc_free(s->recvbuf); s->recvbuf = NULL; return trt; } else { mp_obj_t trt = mp_obj_new_bytes(s->recvbuf, mxl); memmove(s->recvbuf, &s->recvbuf[mxl], s->recvbuf_len - mxl); s->recvbuf_len -= mxl; s->recvbuf = gc_realloc(s->recvbuf, s->recvbuf_len, true); return trt; } }
// Special-case of index() which searches for mp_obj_t mp_obj_t mp_seq_index_obj(const mp_obj_t *items, uint len, uint n_args, const mp_obj_t *args) { mp_obj_type_t *type = mp_obj_get_type(args[0]); mp_obj_t *value = args[1]; uint start = 0; uint stop = len; if (n_args >= 3) { start = mp_get_index(type, len, args[2]); if (n_args >= 4) { stop = mp_get_index(type, len, args[3]); } } for (machine_uint_t i = start; i < stop; i++) { if (mp_obj_equal(items[i], value)) { // Common sense says this cannot overflow small int return MP_OBJ_NEW_SMALL_INT(i); } } nlr_jump(mp_obj_new_exception_msg(MP_QSTR_ValueError, "object not in sequence")); }
mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_SENTINEL) { // load mp_obj_tuple_t *self = self_in; #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, "only slices with step=1 (aka None) are supported")); } mp_obj_tuple_t *res = mp_obj_new_tuple(slice.stop - slice.start, NULL); mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); return res; } #endif uint index_value = mp_get_index(self->base.type, self->len, index, false); return self->items[index_value]; } else { return MP_OBJ_NULL; // op not supported } }
mp_int_t mp_obj_get_int(mp_const_obj_t arg) { // This function essentially performs implicit type conversion to int // Note that Python does NOT provide implicit type conversion from // float to int in the core expression language, try some_list[1.0]. if (arg == mp_const_false) { return 0; } else if (arg == mp_const_true) { return 1; } else if (MP_OBJ_IS_SMALL_INT(arg)) { return MP_OBJ_SMALL_INT_VALUE(arg); } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { return mp_obj_int_get_checked(arg); } else { if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "can't convert to int")); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "can't convert %s to int", mp_obj_get_type_str(arg))); } } }
/// \classmethod \constructor(spi, pin_cs, pin_en, pin_irq) /// Initialise the CC3000 using the given SPI bus and pins and return a CC3k object. // // Note: pins were originally hard-coded to: // PYBv1.0: init(pyb.SPI(2), pyb.Pin.board.Y5, pyb.Pin.board.Y4, pyb.Pin.board.Y3) // [SPI on Y position; Y6=B13=SCK, Y7=B14=MISO, Y8=B15=MOSI] // // STM32F4DISC: init(pyb.SPI(2), pyb.Pin.cpu.A15, pyb.Pin.cpu.B10, pyb.Pin.cpu.B11) STATIC mp_obj_t cc3k_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) { // check arguments mp_arg_check_num(n_args, n_kw, 4, 4, false); // set the pins to use SpiInit( spi_get_handle(args[0]), pin_find(args[1]), pin_find(args[2]), pin_find(args[3]) ); // initialize and start the module wlan_init(cc3k_callback, NULL, NULL, NULL, ReadWlanInterruptPin, SpiResumeSpi, SpiPauseSpi, WriteWlanPin); if (wlan_start(0) != 0) { nlr_raise(mp_obj_new_exception_msg( &mp_type_OSError, "Failed to init wlan module")); } // set connection policy. this should be called explicitly by the user // wlan_ioctl_set_connection_policy(0, 0, 0); // Mask out all non-required events from the CC3000 wlan_set_event_mask(HCI_EVNT_WLAN_KEEPALIVE| HCI_EVNT_WLAN_UNSOL_INIT| HCI_EVNT_WLAN_ASYNC_PING_REPORT| HCI_EVNT_WLAN_ASYNC_SIMPLE_CONFIG_DONE); cc3k_obj_t *cc3k = m_new_obj(cc3k_obj_t); cc3k->base.type = (mp_obj_type_t*)&mod_network_nic_type_cc3k; // register with network module mod_network_register_nic(cc3k); return cc3k; }
STATIC mp_obj_t pyb_i2c_mem_read(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { pyb_i2c_obj_t *self = args[0]; if (!in_master_mode(self)) { nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "I2C must be a master")); } // parse args mp_arg_val_t vals[PYB_I2C_MEM_READ_NUM_ARGS]; mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_I2C_MEM_READ_NUM_ARGS, pyb_i2c_mem_read_args, vals); // get the buffer to read into mp_buffer_info_t bufinfo; mp_obj_t o_ret = pyb_buf_get_for_recv(vals[0].u_obj, &bufinfo); // get the addresses mp_uint_t i2c_addr = vals[1].u_int << 1; mp_uint_t mem_addr = vals[2].u_int; // determine width of mem_addr; default is 8 bits, entering any other value gives 16 bit width mp_uint_t mem_addr_size = I2C_MEMADD_SIZE_8BIT; if (vals[4].u_int != 8) { mem_addr_size = I2C_MEMADD_SIZE_16BIT; } HAL_StatusTypeDef status = HAL_I2C_Mem_Read(self->i2c, i2c_addr, mem_addr, mem_addr_size, bufinfo.buf, bufinfo.len, vals[3].u_int); if (status != HAL_OK) { // TODO really need a HardwareError object, or something nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_Exception, "HAL_I2C_Mem_Read failed with code %d", status)); } // return the read data if (o_ret == MP_OBJ_NULL) { return vals[0].u_obj; } else { return mp_obj_str_builder_end(o_ret); } }
mp_obj_t file_obj_seek(mp_uint_t n_args, const mp_obj_t *args) { pyb_file_obj_t *self = args[0]; mp_int_t offset = mp_obj_get_int(args[1]); mp_int_t whence = 0; if (n_args == 3) { whence = mp_obj_get_int(args[2]); } switch (whence) { case 0: // SEEK_SET f_lseek(&self->fp, offset); break; case 1: // SEEK_CUR if (offset != 0) { goto error; } // no-operation break; case 2: // SEEK_END if (offset != 0) { goto error; } f_lseek(&self->fp, f_size(&self->fp)); break; default: goto error; } return mp_obj_new_int_from_uint(f_tell(&self->fp)); error: // A bad whence is a ValueError, while offset!=0 is an io.UnsupportedOperation. // But the latter inherits ValueError (as well as IOError), so we just raise ValueError. nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "invalid whence and/or offset")); }