void mp_arg_parse_all(uint n_pos, const mp_obj_t *pos, mp_map_t *kws, uint n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals) { uint pos_found = 0, kws_found = 0; for (uint i = 0; i < n_allowed; i++) { mp_obj_t given_arg; if (i < n_pos) { if (allowed[i].flags & MP_ARG_KW_ONLY) { goto extra_positional; } pos_found++; given_arg = pos[i]; } else { mp_map_elem_t *kw = mp_map_lookup(kws, MP_OBJ_NEW_QSTR(allowed[i].qstr), MP_MAP_LOOKUP); if (kw == NULL) { if (allowed[i].flags & MP_ARG_REQUIRED) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "'%s' argument required", qstr_str(allowed[i].qstr))); } out_vals[i] = allowed[i].defval; continue; } else { kws_found++; given_arg = kw->value; } } if ((allowed[i].flags & MP_ARG_KIND_MASK) == MP_ARG_BOOL) { out_vals[i].u_bool = mp_obj_is_true(given_arg); } else if ((allowed[i].flags & MP_ARG_KIND_MASK) == MP_ARG_INT) { out_vals[i].u_int = mp_obj_get_int(given_arg); } else if ((allowed[i].flags & MP_ARG_KIND_MASK) == MP_ARG_OBJ) { out_vals[i].u_obj = given_arg; } else { assert(0); } } if (pos_found < n_pos) { // TODO better error message extra_positional: nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "extra positional arguments given")); } if (kws_found < kws->used) { // TODO better error message nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "extra keyword arguments given")); } }
STATIC mp_obj_t fdfile_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { mp_obj_fdfile_t *o = m_new_obj(mp_obj_fdfile_t); o->base.type = type_in; if (MP_OBJ_IS_SMALL_INT(args[0])) { o->fd = MP_OBJ_SMALL_INT_VALUE(args[0]); return o; } const char *fname = mp_obj_str_get_str(args[0]); const char *mode_s; if (n_args > 1) { mode_s = mp_obj_str_get_str(args[1]); } else { mode_s = "r"; } int mode = 0; while (*mode_s) { switch (*mode_s++) { // Note: these assume O_RDWR = O_RDONLY | O_WRONLY case 'r': mode |= O_RDONLY; break; case 'w': mode |= O_WRONLY | O_CREAT | O_TRUNC; break; case 'a': mode |= O_APPEND; break; case '+': mode |= O_RDWR; break; } } int fd = open(fname, mode, 0644); if (fd == -1) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[Errno %d]", errno)); } return fdfile_new(fd); }
/** * Remove given empty directory. * * def rename(src, dst) */ static mp_obj_t os_rename(mp_obj_t path_src_in, mp_obj_t path_dst_in) { const char *src_path_p; const char *dst_path_p; int res; src_path_p = mp_obj_str_get_str(path_src_in); dst_path_p = mp_obj_str_get_str(path_dst_in); res = -1; mp_not_implemented("os_rename()"); if (res != 0) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "Error renaming file '%s' to '%s'", src_path_p, dst_path_p)); } return (mp_const_none); }
/** * def read_block(self, block) */ static mp_obj_t class_sd_read_block(mp_obj_t self_in, mp_obj_t block_in) { struct class_sd_t *self_p; vstr_t vstr; uint32_t block; self_p = MP_OBJ_TO_PTR(self_in); block = mp_obj_get_int(block_in); vstr_init_len(&vstr, SD_BLOCK_SIZE); if (sd_read_block(&self_p->drv, vstr.buf, block) != SD_BLOCK_SIZE) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "sd_read_block(%d) failed", block)); } return (mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr)); }
/// \classmethod \constructor(id) /// Create a servo object. `id` is 1-4. STATIC mp_obj_t pyb_servo_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { // check arguments mp_arg_check_num(n_args, n_kw, 1, 1, false); // get servo number mp_int_t servo_id = mp_obj_get_int(args[0]) - 1; // check servo number if (!(0 <= servo_id && servo_id < PYB_SERVO_NUM)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Servo(%d) doesn't exist", servo_id + 1)); } // get and init servo object pyb_servo_obj_t *s = &pyb_servo_obj[servo_id]; s->pulse_dest = s->pulse_cur; s->time_left = 0; servo_init_channel(s); return s; }
/// \classmethod \constructor(bus, ...) /// /// Construct a UART object on the given bus. `bus` can be 1-6, or 'XA', 'XB', 'YA', or 'YB'. /// With no additional parameters, the UART object is created but not /// initialised (it has the settings from the last initialisation of /// the bus, if any). If extra arguments are given, the bus is initialised. /// See `init` for parameters of initialisation. /// /// The physical pins of the UART busses are: /// /// - `UART(4)` is on `XA`: `(TX, RX) = (X1, X2) = (PA0, PA1)` /// - `UART(1)` is on `XB`: `(TX, RX) = (X9, X10) = (PB6, PB7)` /// - `UART(6)` is on `YA`: `(TX, RX) = (Y1, Y2) = (PC6, PC7)` /// - `UART(3)` is on `YB`: `(TX, RX) = (Y9, Y10) = (PB10, PB11)` /// - `UART(2)` is on: `(TX, RX) = (X3, X4) = (PA2, PA3)` STATIC mp_obj_t pyb_uart_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { // check arguments mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true); // create object pyb_uart_obj_t *o = m_new_obj(pyb_uart_obj_t); o->base.type = &pyb_uart_type; // work out port o->uart_id = 0; #if 0 if (MP_OBJ_IS_STR(args[0])) { const char *port = mp_obj_str_get_str(args[0]); if (0) { #if defined(PYBV10) } else if (strcmp(port, "XA") == 0) { o->uart_id = PYB_UART_XA; } else if (strcmp(port, "XB") == 0) { o->uart_id = PYB_UART_XB; } else if (strcmp(port, "YA") == 0) { o->uart_id = PYB_UART_YA; } else if (strcmp(port, "YB") == 0) { o->uart_id = PYB_UART_YB; #endif } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "UART port %s does not exist", port)); } } else { o->uart_id = mp_obj_get_int(args[0]); } #endif if (n_args > 1 || n_kw > 0) { // start the peripheral mp_map_t kw_args; mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); pyb_uart_init_helper(o, n_args - 1, args + 1, &kw_args); } return o; }
STATIC mp_obj_t tuple_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { // TODO check n_kw == 0 switch (n_args) { case 0: // return a empty tuple return mp_const_empty_tuple; case 1: { // 1 argument, an iterable from which we make a new tuple if (MP_OBJ_IS_TYPE(args[0], &tuple_type)) { return args[0]; } // TODO optimise for cases where we know the length of the iterator uint alloc = 4; uint len = 0; mp_obj_t *items = m_new(mp_obj_t, alloc); mp_obj_t iterable = rt_getiter(args[0]); mp_obj_t item; while ((item = rt_iternext(iterable)) != mp_const_stop_iteration) { if (len >= alloc) { items = m_renew(mp_obj_t, items, alloc, alloc * 2); alloc *= 2; } items[len++] = item; } mp_obj_t tuple = mp_obj_new_tuple(len, items); m_free(items, alloc); return tuple; } default: nlr_jump(mp_obj_new_exception_msg_varg(MP_QSTR_TypeError, "tuple takes at most 1 argument, %d given", n_args)); } }
STATIC bool get_arg_addr(emit_inline_asm_t *emit, const char *op, mp_parse_node_t pn, mp_parse_node_t *pn_base, mp_parse_node_t *pn_offset) { if (!MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_bracket)) { goto bad_arg; } mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; if (!MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { goto bad_arg; } pns = (mp_parse_node_struct_t*)pns->nodes[0]; if (MP_PARSE_NODE_STRUCT_NUM_NODES(pns) != 2) { goto bad_arg; } *pn_base = pns->nodes[0]; *pn_offset = pns->nodes[1]; return true; bad_arg: emit_inline_thumb_error_exc(emit, mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, "'%s' expects an address of the form [a, b]", op)); return false; }
mp_obj_t mp_obj_exception_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) { mp_obj_type_t *type = type_in; if (n_kw != 0) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "%s does not take keyword arguments", mp_obj_get_type_str(type_in))); } mp_obj_exception_t *o = m_new_obj_var_maybe(mp_obj_exception_t, mp_obj_t, 0); if (o == NULL) { // Couldn't allocate heap memory; use local data instead. o = &mp_emergency_exception_obj; // We can't store any args. n_args = 0; o->args = mp_const_empty_tuple; } else { o->args = mp_obj_new_tuple(n_args, args); } o->base.type = type; o->traceback = MP_OBJ_NULL; return o; }
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) { mp_raise_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))); } } }
STATIC mp_obj_t list_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { // TODO check n_kw == 0 switch (n_args) { case 0: // return a new, empty list return mp_obj_new_list(0, NULL); case 1: { // make list from iterable // TODO: optimize list/tuple mp_obj_t list = mp_obj_new_list(0, NULL); return list_extend_from_iter(list, args[0]); } default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "list takes at most 1 argument, %d given", n_args)); } return NULL; }
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))); } }
STATIC void adc_init_single(pyb_obj_adc_t *adc_obj) { if (!is_adcx_channel(adc_obj->channel)) { return; } if (ADC_FIRST_GPIO_CHANNEL <= adc_obj->channel && adc_obj->channel <= ADC_LAST_GPIO_CHANNEL) { // Channels 0-16 correspond to real pins. Configure the GPIO pin in ADC mode. const pin_obj_t *pin = pin_adc_table[adc_obj->channel]; mp_hal_pin_config(pin, MP_HAL_PIN_MODE_ADC, MP_HAL_PIN_PULL_NONE, 0); } adcx_init_periph(&adc_obj->handle, ADC_RESOLUTION_12B); #if defined(STM32L4) && defined(ADC_DUALMODE_REGSIMULT_INJECSIMULT) ADC_MultiModeTypeDef multimode; multimode.Mode = ADC_MODE_INDEPENDENT; if (HAL_ADCEx_MultiModeConfigChannel(&adc_obj->handle, &multimode) != HAL_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Can not set multimode on ADC1 channel: %d", adc_obj->channel)); } #endif }
void mp_obj_get_complex(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) { if (arg == mp_const_false) { *real = 0; *imag = 0; } else if (arg == mp_const_true) { *real = 1; *imag = 0; } else if (MP_OBJ_IS_SMALL_INT(arg)) { *real = MP_OBJ_SMALL_INT_VALUE(arg); *imag = 0; } else if (MP_OBJ_IS_TYPE(arg, &mp_type_int)) { *real = mp_obj_int_as_float(arg); *imag = 0; } else if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) { *real = mp_obj_float_get(arg); *imag = 0; } else if (MP_OBJ_IS_TYPE(arg, &mp_type_complex)) { mp_obj_complex_get(arg, real, imag); } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "can't convert %s to complex", mp_obj_get_type_str(arg))); } }
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); } }
STATIC void do_load(mp_obj_t module_obj, vstr_t *file) { #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_ENABLE_COMPILER char *file_str = vstr_null_terminated_str(file); #endif #if MICROPY_PERSISTENT_CODE_LOAD if (file_str[file->len - 3] == 'm') { mp_raw_code_t *raw_code = mp_raw_code_load_file(file_str); do_execute_raw_code(module_obj, raw_code); return; } #endif #if MICROPY_ENABLE_COMPILER { mp_lexer_t *lex = mp_lexer_new_from_file(file_str); do_load_from_lexer(module_obj, lex, file_str); } #else nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, "script compilation not supported")); #endif }
mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, mp_uint_t len) { struct _mp_obj_base_t *o = (struct _mp_obj_base_t *)self_in; if (o->type->stream_p == NULL || o->type->stream_p->write == NULL) { // CPython: io.UnsupportedOperation, OSError subclass nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Operation not supported")); } int error; mp_uint_t out_sz = o->type->stream_p->write(self_in, buf, len, &error); if (out_sz == MP_STREAM_ERROR) { if (is_nonblocking_error(error)) { // http://docs.python.org/3/library/io.html#io.RawIOBase.write // "None is returned if the raw stream is set not to block and // no single byte could be readily written to it." // This is for consistency with read() behavior, still weird, // see abobe. return mp_const_none; } nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[Errno %d]", error)); } else { return MP_OBJ_NEW_SMALL_INT(out_sz); } }
STATIC mp_obj_t stream_read(uint n_args, const mp_obj_t *args) { struct _mp_obj_base_t *o = (struct _mp_obj_base_t *)args[0]; if (o->type->stream_p == NULL || o->type->stream_p->read == NULL) { // CPython: io.UnsupportedOperation, OSError subclass nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Operation not supported")); } mp_int_t sz; if (n_args == 1 || ((sz = mp_obj_get_int(args[1])) == -1)) { return stream_readall(args[0]); } #if MICROPY_PY_BUILTINS_STR_UNICODE if (!o->type->stream_p->is_bytes) { mp_not_implemented("Reading from unicode text streams by character count"); } #endif byte *buf = m_new(byte, sz); int error; mp_int_t out_sz = o->type->stream_p->read(o, buf, sz, &error); if (out_sz == -1) { if (is_nonblocking_error(error)) { // https://docs.python.org/3.4/library/io.html#io.RawIOBase.read // "If the object is in non-blocking mode and no bytes are available, // None is returned." // This is actually very weird, as naive truth check will treat // this as EOF. return mp_const_none; } nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_OSError, "[Errno %d]", error)); } else { mp_obj_t s = mp_obj_new_str_of_type(STREAM_CONTENT_TYPE(o->type->stream_p), buf, out_sz); // will reallocate to use exact size m_free(buf, sz); return s; } }
STATIC mp_obj_t dict_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { mp_obj_t dict; switch (n_args) { case 0: dict = mp_obj_new_dict(0); break; case 1: { if (MP_OBJ_IS_TYPE(args[0], &mp_type_dict)) { return dict_copy(args[0]); } // TODO create dict from an arbitrary mapping! // Make dict from iterable of pairs mp_obj_t iterable = mp_getiter(args[0]); mp_obj_t dict = mp_obj_new_dict(0); // TODO: support arbitrary seq as a pair mp_obj_t item; while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { mp_obj_t *sub_items; mp_obj_get_array_fixed_n(item, 2, &sub_items); mp_obj_dict_store(dict, sub_items[0], sub_items[1]); } return dict; } default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "dict takes at most 1 argument")); } // add to the new dict any keyword args for (const mp_obj_t *a = args + n_args; n_kw > 0; n_kw--, a += 2) { mp_obj_dict_store(dict, a[0], a[1]); } return dict; }
STATIC mp_obj_t pyb_uart_send(uint n_args, const mp_obj_t *args, mp_map_t *kw_args) { // TODO assumes transmission size is 8-bits wide pyb_uart_obj_t *self = args[0]; // parse args mp_arg_val_t vals[PYB_UART_SEND_NUM_ARGS]; mp_arg_parse_all(n_args - 1, args + 1, kw_args, PYB_UART_SEND_NUM_ARGS, pyb_uart_send_args, vals); // get the buffer to send from mp_buffer_info_t bufinfo; uint8_t data[1]; pyb_buf_get_for_send(vals[0].u_obj, &bufinfo, data); // send the data HAL_StatusTypeDef status = HAL_UART_Transmit(&self->uart, bufinfo.buf, bufinfo.len, vals[1].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_UART_Transmit failed with code %d", status)); } return mp_const_none; }
/// \classmethod \constructor(bus, ...) /// /// Construct an I2C object on the given bus. `bus` can be 1 or 2. /// With no additional parameters, the I2C object is created but not /// initialised (it has the settings from the last initialisation of /// the bus, if any). If extra arguments are given, the bus is initialised. /// See `init` for parameters of initialisation. /// /// The physical pins of the I2C busses are: /// /// - `I2C(1)` is on the X position: `(SCL, SDA) = (X9, X10) = (PB6, PB7)` /// - `I2C(2)` is on the Y position: `(SCL, SDA) = (Y9, Y10) = (PB10, PB11)` STATIC mp_obj_t pyb_i2c_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { // check arguments mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true); // get i2c number mp_int_t i2c_id = mp_obj_get_int(args[0]) - 1; // check i2c number if (!(0 <= i2c_id && i2c_id < MP_ARRAY_SIZE(pyb_i2c_obj) && pyb_i2c_obj[i2c_id].i2c != NULL)) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "I2C bus %d does not exist", i2c_id + 1)); } // get I2C object const pyb_i2c_obj_t *i2c_obj = &pyb_i2c_obj[i2c_id]; if (n_args > 1 || n_kw > 0) { // start the peripheral mp_map_t kw_args; mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); pyb_i2c_init_helper(i2c_obj, n_args - 1, args + 1, &kw_args); } return (mp_obj_t)i2c_obj; }
STATIC mp_obj_t set_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) { // TODO check n_kw == 0 switch (n_args) { case 0: // return a new, empty set return mp_obj_new_set(0, NULL); case 1: { // 1 argument, an iterable from which we make a new set mp_obj_t set = mp_obj_new_set(0, NULL); mp_obj_t iterable = mp_getiter(args[0]); mp_obj_t item; while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { mp_obj_set_store(set, item); } return set; } default: nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "set takes at most 1 argument, %d given", n_args)); } }
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; }
// Set override_callback_obj to true if you want to unconditionally set the // callback function. uint extint_register(mp_obj_t pin_obj, uint32_t mode, uint32_t pull, mp_obj_t callback_obj, bool override_callback_obj) { const pin_obj_t *pin = NULL; uint v_line; if (MP_OBJ_IS_INT(pin_obj)) { // If an integer is passed in, then use it to identify lines 16 thru 22 // We expect lines 0 thru 15 to be passed in as a pin, so that we can // get both the port number and line number. v_line = mp_obj_get_int(pin_obj); if (v_line < 16) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "ExtInt vector %d < 16, use a Pin object", v_line)); } if (v_line >= EXTI_NUM_VECTORS) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "ExtInt vector %d >= max of %d", v_line, EXTI_NUM_VECTORS)); } } else { pin = pin_find(pin_obj); v_line = pin->pin; } if (mode != GPIO_MODE_IT_RISING && mode != GPIO_MODE_IT_FALLING && mode != GPIO_MODE_IT_RISING_FALLING && mode != GPIO_MODE_EVT_RISING && mode != GPIO_MODE_EVT_FALLING && mode != GPIO_MODE_EVT_RISING_FALLING) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid ExtInt Mode: %d", mode)); } if (pull != GPIO_NOPULL && pull != GPIO_PULLUP && pull != GPIO_PULLDOWN) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid ExtInt Pull: %d", pull)); } mp_obj_t *cb = &MP_STATE_PORT(pyb_extint_callback)[v_line]; if (!override_callback_obj && *cb != mp_const_none && callback_obj != mp_const_none) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "ExtInt vector %d is already in use", v_line)); } // We need to update callback atomically, so we disable the line // before we update anything. extint_disable(v_line); *cb = callback_obj; pyb_extint_mode[v_line] = (mode & 0x00010000) ? // GPIO_MODE_IT == 0x00010000 EXTI_Mode_Interrupt : EXTI_Mode_Event; if (*cb != mp_const_none) { mp_hal_gpio_clock_enable(pin->gpio); GPIO_InitTypeDef exti; exti.Pin = pin->pin_mask; exti.Mode = mode; exti.Pull = pull; exti.Speed = GPIO_SPEED_FAST; HAL_GPIO_Init(pin->gpio, &exti); // Calling HAL_GPIO_Init does an implicit extint_enable /* Enable and set NVIC Interrupt to the lowest priority */ HAL_NVIC_SetPriority(nvic_irq_channel[v_line], IRQ_PRI_EXTINT, IRQ_SUBPRI_EXTINT); HAL_NVIC_EnableIRQ(nvic_irq_channel[v_line]); } return v_line; }
mp_obj_t mp_obj_new_exception_msg_2_args(qstr id, const char *fmt, const char *a1, const char *a2) { return mp_obj_new_exception_msg_varg(id, fmt, a1, a2); }
mp_obj_t mp_obj_new_exception_msg_1_arg(qstr id, const char *fmt, const char *a1) { return mp_obj_new_exception_msg_varg(id, fmt, a1); }
mp_obj_t mp_obj_new_exception_msg(qstr id, const char *msg) { return mp_obj_new_exception_msg_varg(id, msg); }
mp_obj_t mp_obj_new_exception(qstr id) { return mp_obj_new_exception_msg_varg(id, NULL); }