code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H #define MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H #include "py/obj.h" #include "py/mphal.h" mp_uint_t machine_time_pulse_us(mp_hal_pin_obj_t pin, int pulse_level, mp_uint_t timeout_us); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(machine_time_pulse_us_obj); #endif // MICROPY_INCLUDED_EXTMOD_MACHINE_PULSE_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/machine_pulse.h
C
apache-2.0
1,576
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_PY_MACHINE #include <string.h> #include "py/obj.h" #include "py/runtime.h" #include "extmod/virtpin.h" #include "extmod/machine_signal.h" // Signal class typedef struct _machine_signal_t { mp_obj_base_t base; mp_obj_t pin; bool invert; } machine_signal_t; STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_obj_t pin; bool invert = false; #if defined(MICROPY_PY_MACHINE_PIN_MAKE_NEW) mp_pin_p_t *pin_p = NULL; if (n_args > 0 && mp_obj_is_obj(args[0])) { mp_obj_base_t *pin_base = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); pin_p = (mp_pin_p_t *)pin_base->type->protocol; } if (pin_p == NULL) { // If first argument isn't a Pin-like object, we filter out "invert" // from keyword arguments and pass them all to the exported Pin // constructor to create one. mp_obj_t *pin_args = mp_local_alloc((n_args + n_kw * 2) * sizeof(mp_obj_t)); memcpy(pin_args, args, n_args * sizeof(mp_obj_t)); const mp_obj_t *src = args + n_args; mp_obj_t *dst = pin_args + n_args; mp_obj_t *sig_value = NULL; for (size_t cnt = n_kw; cnt; cnt--) { if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { invert = mp_obj_is_true(src[1]); n_kw--; } else { *dst++ = *src; *dst++ = src[1]; } if (*src == MP_OBJ_NEW_QSTR(MP_QSTR_value)) { // Value is pertained to Signal, so we should invert // it for Pin if needed, and we should do it only when // inversion status is guaranteedly known. sig_value = dst - 1; } src += 2; } if (invert && sig_value != NULL) { *sig_value = mp_obj_is_true(*sig_value) ? MP_OBJ_NEW_SMALL_INT(0) : MP_OBJ_NEW_SMALL_INT(1); } // Here we pass NULL as a type, hoping that mp_pin_make_new() // will just ignore it as set a concrete type. If not, we'd need // to expose port's "default" pin type too. pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); mp_local_free(pin_args); } else #endif // Otherwise there should be 1 or 2 args { if (n_args == 1) { pin = args[0]; if (n_kw == 0) { } else if (n_kw == 1 && args[1] == MP_OBJ_NEW_QSTR(MP_QSTR_invert)) { invert = mp_obj_is_true(args[2]); } else { goto error; } } else { error: mp_raise_TypeError(NULL); } } machine_signal_t *o = m_new_obj(machine_signal_t); o->base.type = type; o->pin = pin; o->invert = invert; return MP_OBJ_FROM_PTR(o); } STATIC mp_uint_t signal_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { (void)errcode; machine_signal_t *self = MP_OBJ_TO_PTR(self_in); switch (request) { case MP_PIN_READ: { return mp_virtual_pin_read(self->pin) ^ self->invert; } case MP_PIN_WRITE: { mp_virtual_pin_write(self->pin, arg ^ self->invert); return 0; } } return -1; } // fast method for getting/setting signal value STATIC mp_obj_t signal_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); if (n_args == 0) { // get pin return MP_OBJ_NEW_SMALL_INT(mp_virtual_pin_read(self_in)); } else { // set pin mp_virtual_pin_write(self_in, mp_obj_is_true(args[0])); return mp_const_none; } } STATIC mp_obj_t signal_value(size_t n_args, const mp_obj_t *args) { return signal_call(args[0], n_args - 1, 0, args + 1); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(signal_value_obj, 1, 2, signal_value); STATIC mp_obj_t signal_on(mp_obj_t self_in) { mp_virtual_pin_write(self_in, 1); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_on_obj, signal_on); STATIC mp_obj_t signal_off(mp_obj_t self_in) { mp_virtual_pin_write(self_in, 0); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(signal_off_obj, signal_off); STATIC const mp_rom_map_elem_t signal_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&signal_value_obj) }, { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&signal_on_obj) }, { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&signal_off_obj) }, }; STATIC MP_DEFINE_CONST_DICT(signal_locals_dict, signal_locals_dict_table); STATIC const mp_pin_p_t signal_pin_p = { .ioctl = signal_ioctl, }; const mp_obj_type_t machine_signal_type = { { &mp_type_type }, .name = MP_QSTR_Signal, .make_new = signal_make_new, .call = signal_call, .protocol = &signal_pin_p, .locals_dict = (void *)&signal_locals_dict, }; #endif // MICROPY_PY_MACHINE
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/machine_signal.c
C
apache-2.0
6,230
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H #define MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H #include "py/obj.h" extern const mp_obj_type_t machine_signal_type; #endif // MICROPY_INCLUDED_EXTMOD_MACHINE_SIGNAL_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/machine_signal.h
C
apache-2.0
1,444
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "extmod/machine_spi.h" #if MICROPY_PY_MACHINE_SPI // if a port didn't define MSB/LSB constants then provide them #ifndef MICROPY_PY_MACHINE_SPI_MSB #define MICROPY_PY_MACHINE_SPI_MSB (0) #define MICROPY_PY_MACHINE_SPI_LSB (1) #endif /******************************************************************************/ // MicroPython bindings for generic machine.SPI STATIC mp_obj_t machine_spi_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]); mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol; spi_p->init(s, n_args - 1, args + 1, kw_args); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_spi_init_obj, 1, machine_spi_init); STATIC mp_obj_t machine_spi_deinit(mp_obj_t self) { mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self); mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol; if (spi_p->deinit != NULL) { spi_p->deinit(s); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_spi_deinit_obj, machine_spi_deinit); STATIC void mp_machine_spi_transfer(mp_obj_t self, size_t len, const void *src, void *dest) { mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(self); mp_machine_spi_p_t *spi_p = (mp_machine_spi_p_t *)s->type->protocol; spi_p->transfer(s, len, src, dest); } STATIC mp_obj_t mp_machine_spi_read(size_t n_args, const mp_obj_t *args) { vstr_t vstr; vstr_init_len(&vstr, mp_obj_get_int(args[1])); memset(vstr.buf, n_args == 3 ? mp_obj_get_int(args[2]) : 0, vstr.len); mp_machine_spi_transfer(args[0], vstr.len, vstr.buf, vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_read_obj, 2, 3, mp_machine_spi_read); STATIC mp_obj_t mp_machine_spi_readinto(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE); memset(bufinfo.buf, n_args == 3 ? mp_obj_get_int(args[2]) : 0, bufinfo.len); mp_machine_spi_transfer(args[0], bufinfo.len, bufinfo.buf, bufinfo.buf); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_readinto_obj, 2, 3, mp_machine_spi_readinto); STATIC mp_obj_t mp_machine_spi_write(mp_obj_t self, mp_obj_t wr_buf) { mp_buffer_info_t src; mp_get_buffer_raise(wr_buf, &src, MP_BUFFER_READ); mp_machine_spi_transfer(self, src.len, (const uint8_t *)src.buf, NULL); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(mp_machine_spi_write_obj, mp_machine_spi_write); STATIC mp_obj_t mp_machine_spi_write_readinto(mp_obj_t self, mp_obj_t wr_buf, mp_obj_t rd_buf) { mp_buffer_info_t src; mp_get_buffer_raise(wr_buf, &src, MP_BUFFER_READ); mp_buffer_info_t dest; mp_get_buffer_raise(rd_buf, &dest, MP_BUFFER_WRITE); if (src.len != dest.len) { mp_raise_ValueError(MP_ERROR_TEXT("buffers must be the same length")); } mp_machine_spi_transfer(self, src.len, src.buf, dest.buf); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(mp_machine_spi_write_readinto_obj, mp_machine_spi_write_readinto); STATIC const mp_rom_map_elem_t machine_spi_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_spi_init_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_spi_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_machine_spi_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_machine_spi_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_machine_spi_write_obj) }, { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&mp_machine_spi_write_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_MSB), MP_ROM_INT(MICROPY_PY_MACHINE_SPI_MSB) }, { MP_ROM_QSTR(MP_QSTR_LSB), MP_ROM_INT(MICROPY_PY_MACHINE_SPI_LSB) }, }; MP_DEFINE_CONST_DICT(mp_machine_spi_locals_dict, machine_spi_locals_dict_table); /******************************************************************************/ // Implementation of soft SPI STATIC uint32_t baudrate_from_delay_half(uint32_t delay_half) { #ifdef MICROPY_HW_SOFTSPI_MIN_DELAY if (delay_half == MICROPY_HW_SOFTSPI_MIN_DELAY) { return MICROPY_HW_SOFTSPI_MAX_BAUDRATE; } else #endif { return 500000 / delay_half; } } STATIC uint32_t baudrate_to_delay_half(uint32_t baudrate) { #ifdef MICROPY_HW_SOFTSPI_MIN_DELAY if (baudrate >= MICROPY_HW_SOFTSPI_MAX_BAUDRATE) { return MICROPY_HW_SOFTSPI_MIN_DELAY; } else #endif { uint32_t delay_half = 500000 / baudrate; // round delay_half up so that: actual_baudrate <= requested_baudrate if (500000 % baudrate != 0) { delay_half += 1; } return delay_half; } } STATIC void mp_machine_soft_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { mp_machine_soft_spi_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "SoftSPI(baudrate=%u, polarity=%u, phase=%u," " sck=" MP_HAL_PIN_FMT ", mosi=" MP_HAL_PIN_FMT ", miso=" MP_HAL_PIN_FMT ")", baudrate_from_delay_half(self->spi.delay_half), self->spi.polarity, self->spi.phase, mp_hal_pin_name(self->spi.sck), mp_hal_pin_name(self->spi.mosi), mp_hal_pin_name(self->spi.miso)); } STATIC mp_obj_t mp_machine_soft_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit, ARG_sck, ARG_mosi, ARG_miso }; static const mp_arg_t allowed_args[] = { { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 500000} }, { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_phase, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, { MP_QSTR_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = MICROPY_PY_MACHINE_SPI_MSB} }, { MP_QSTR_sck, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_mosi, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_miso, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // create new object mp_machine_soft_spi_obj_t *self = m_new_obj(mp_machine_soft_spi_obj_t); self->base.type = &mp_machine_soft_spi_type; // set parameters self->spi.delay_half = baudrate_to_delay_half(args[ARG_baudrate].u_int); self->spi.polarity = args[ARG_polarity].u_int; self->spi.phase = args[ARG_phase].u_int; if (args[ARG_bits].u_int != 8) { mp_raise_ValueError(MP_ERROR_TEXT("bits must be 8")); } if (args[ARG_firstbit].u_int != MICROPY_PY_MACHINE_SPI_MSB) { mp_raise_ValueError(MP_ERROR_TEXT("firstbit must be MSB")); } if (args[ARG_sck].u_obj == MP_OBJ_NULL || args[ARG_mosi].u_obj == MP_OBJ_NULL || args[ARG_miso].u_obj == MP_OBJ_NULL) { mp_raise_ValueError(MP_ERROR_TEXT("must specify all of sck/mosi/miso")); } self->spi.sck = mp_hal_get_pin_obj(args[ARG_sck].u_obj); self->spi.mosi = mp_hal_get_pin_obj(args[ARG_mosi].u_obj); self->spi.miso = mp_hal_get_pin_obj(args[ARG_miso].u_obj); // configure bus mp_soft_spi_ioctl(&self->spi, MP_SPI_IOCTL_INIT); return MP_OBJ_FROM_PTR(self); } STATIC void mp_machine_soft_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in; enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_sck, ARG_mosi, ARG_miso }; static const mp_arg_t allowed_args[] = { { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = -1} }, { MP_QSTR_polarity, MP_ARG_INT, {.u_int = -1} }, { MP_QSTR_phase, MP_ARG_INT, {.u_int = -1} }, { MP_QSTR_sck, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_mosi, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_miso, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); if (args[ARG_baudrate].u_int != -1) { self->spi.delay_half = baudrate_to_delay_half(args[ARG_baudrate].u_int); } if (args[ARG_polarity].u_int != -1) { self->spi.polarity = args[ARG_polarity].u_int; } if (args[ARG_phase].u_int != -1) { self->spi.phase = args[ARG_phase].u_int; } if (args[ARG_sck].u_obj != MP_OBJ_NULL) { self->spi.sck = mp_hal_get_pin_obj(args[ARG_sck].u_obj); } if (args[ARG_mosi].u_obj != MP_OBJ_NULL) { self->spi.mosi = mp_hal_get_pin_obj(args[ARG_mosi].u_obj); } if (args[ARG_miso].u_obj != MP_OBJ_NULL) { self->spi.miso = mp_hal_get_pin_obj(args[ARG_miso].u_obj); } // configure bus mp_soft_spi_ioctl(&self->spi, MP_SPI_IOCTL_INIT); } STATIC void mp_machine_soft_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) { mp_machine_soft_spi_obj_t *self = (mp_machine_soft_spi_obj_t *)self_in; mp_soft_spi_transfer(&self->spi, len, src, dest); } const mp_machine_spi_p_t mp_machine_soft_spi_p = { .init = mp_machine_soft_spi_init, .deinit = NULL, .transfer = mp_machine_soft_spi_transfer, }; const mp_obj_type_t mp_machine_soft_spi_type = { { &mp_type_type }, .name = MP_QSTR_SoftSPI, .print = mp_machine_soft_spi_print, .make_new = mp_machine_soft_spi_make_new, .protocol = &mp_machine_soft_spi_p, .locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict, }; #endif // MICROPY_PY_MACHINE_SPI
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/machine_spi.c
C
apache-2.0
11,190
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_MACHINE_SPI_H #define MICROPY_INCLUDED_EXTMOD_MACHINE_SPI_H #include "py/obj.h" #include "py/mphal.h" #include "drivers/bus/spi.h" // Temporary support for legacy construction of SoftSPI via SPI type. #define MP_MACHINE_SPI_CHECK_FOR_LEGACY_SOFTSPI_CONSTRUCTION(n_args, n_kw, all_args) \ do { \ if (n_args == 0 || all_args[0] == MP_OBJ_NEW_SMALL_INT(-1)) { \ mp_print_str(MICROPY_ERROR_PRINTER, "Warning: SPI(-1, ...) is deprecated, use SoftSPI(...) instead\n"); \ if (n_args != 0) { \ --n_args; \ ++all_args; \ } \ return mp_machine_soft_spi_type.make_new(&mp_machine_soft_spi_type, n_args, n_kw, all_args); \ } \ } while (0) // SPI protocol typedef struct _mp_machine_spi_p_t { void (*init)(mp_obj_base_t *obj, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); void (*deinit)(mp_obj_base_t *obj); // can be NULL void (*transfer)(mp_obj_base_t *obj, size_t len, const uint8_t *src, uint8_t *dest); } mp_machine_spi_p_t; typedef struct _mp_machine_soft_spi_obj_t { mp_obj_base_t base; mp_soft_spi_obj_t spi; } mp_machine_soft_spi_obj_t; extern const mp_machine_spi_p_t mp_machine_soft_spi_p; extern const mp_obj_type_t mp_machine_soft_spi_type; extern const mp_obj_dict_t mp_machine_spi_locals_dict; mp_obj_t mp_machine_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_read_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_machine_spi_readinto_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_machine_spi_write_obj); MP_DECLARE_CONST_FUN_OBJ_3(mp_machine_spi_write_readinto_obj); #endif // MICROPY_INCLUDED_EXTMOD_MACHINE_SPI_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/machine_spi.h
C
apache-2.0
3,006
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014-2016 Damien P. George * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_MISC_H #define MICROPY_INCLUDED_EXTMOD_MISC_H // This file contains cumulative declarations for extmod/ . #include <stddef.h> #include "py/runtime.h" MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_uos_dupterm_obj); #if MICROPY_PY_OS_DUPTERM bool mp_uos_dupterm_is_builtin_stream(mp_const_obj_t stream); uintptr_t mp_uos_dupterm_poll(uintptr_t poll_flags); int mp_uos_dupterm_rx_chr(void); void mp_uos_dupterm_tx_strn(const char *str, size_t len); void mp_uos_deactivate(size_t dupterm_idx, const char *msg, mp_obj_t exc); #else #define mp_uos_dupterm_tx_strn(s, l) #endif #endif // MICROPY_INCLUDED_EXTMOD_MISC_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/misc.h
C
apache-2.0
1,911
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018 Ayke van Laethem * Copyright (c) 2019-2020 Jim Mussared * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/binary.h" #include "py/gc.h" #include "py/misc.h" #include "py/mperrno.h" #include "py/mphal.h" #include "py/obj.h" #include "py/objarray.h" #include "py/qstr.h" #include "py/runtime.h" #include "extmod/modbluetooth.h" #include <string.h> #if MICROPY_PY_BLUETOOTH #if !MICROPY_ENABLE_SCHEDULER #error modbluetooth requires MICROPY_ENABLE_SCHEDULER #endif #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS && !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS #error l2cap channels require synchronous modbluetooth events #endif #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING && !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS #error pairing and bonding require synchronous modbluetooth events #endif #define MP_BLUETOOTH_CONNECT_DEFAULT_SCAN_DURATION_MS 2000 #define MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_TUPLE_LEN 5 #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS // This formula is intended to allow queuing the data of a large characteristic // while still leaving room for a couple of normal (small, fixed size) events. #define MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_BYTES_LEN(ringbuf_size) (MAX((int)((ringbuf_size) / 2), (int)(ringbuf_size) - 64)) #endif // bluetooth.BLE type. This is currently a singleton, however in the future // this could allow having multiple BLE interfaces on different UARTs. typedef struct { mp_obj_base_t base; mp_obj_t irq_handler; #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS bool irq_scheduled; mp_obj_t irq_data_tuple; uint8_t irq_data_addr_bytes[6]; uint16_t irq_data_data_alloc; mp_obj_array_t irq_data_addr; mp_obj_array_t irq_data_data; mp_obj_bluetooth_uuid_t irq_data_uuid; ringbuf_t ringbuf; #endif } mp_obj_bluetooth_ble_t; STATIC const mp_obj_type_t mp_type_bluetooth_ble; // TODO: this seems like it could be generic? STATIC mp_obj_t bluetooth_handle_errno(int err) { if (err != 0) { mp_raise_OSError(err); } return mp_const_none; } // ---------------------------------------------------------------------------- // UUID object // ---------------------------------------------------------------------------- STATIC mp_obj_t bluetooth_uuid_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { (void)type; mp_arg_check_num(n_args, n_kw, 1, 1, false); mp_obj_bluetooth_uuid_t *self = m_new_obj(mp_obj_bluetooth_uuid_t); self->base.type = &mp_type_bluetooth_uuid; if (mp_obj_is_int(all_args[0])) { self->type = MP_BLUETOOTH_UUID_TYPE_16; mp_int_t value = mp_obj_get_int(all_args[0]); if (value > 65535) { mp_raise_ValueError(MP_ERROR_TEXT("invalid UUID")); } self->data[0] = value & 0xff; self->data[1] = (value >> 8) & 0xff; } else { mp_buffer_info_t uuid_bufinfo = {0}; mp_get_buffer_raise(all_args[0], &uuid_bufinfo, MP_BUFFER_READ); if (uuid_bufinfo.len == 2 || uuid_bufinfo.len == 4 || uuid_bufinfo.len == 16) { // Bytes data -- infer UUID type from length and copy data. self->type = uuid_bufinfo.len; memcpy(self->data, uuid_bufinfo.buf, self->type); } else { // Assume UUID string (e.g. '6E400001-B5A3-F393-E0A9-E50E24DCCA9E') self->type = MP_BLUETOOTH_UUID_TYPE_128; int uuid_i = 32; for (size_t i = 0; i < uuid_bufinfo.len; i++) { char c = ((char *)uuid_bufinfo.buf)[i]; if (c == '-') { continue; } if (!unichar_isxdigit(c)) { mp_raise_ValueError(MP_ERROR_TEXT("invalid char in UUID")); } c = unichar_xdigit_value(c); uuid_i--; if (uuid_i < 0) { mp_raise_ValueError(MP_ERROR_TEXT("UUID too long")); } if (uuid_i % 2 == 0) { // lower nibble self->data[uuid_i / 2] |= c; } else { // upper nibble self->data[uuid_i / 2] = c << 4; } } if (uuid_i > 0) { mp_raise_ValueError(MP_ERROR_TEXT("UUID too short")); } } } return MP_OBJ_FROM_PTR(self); } STATIC mp_obj_t bluetooth_uuid_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_bluetooth_uuid_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_HASH: { // Use the QSTR hash function. return MP_OBJ_NEW_SMALL_INT(qstr_compute_hash(self->data, self->type)); } default: return MP_OBJ_NULL; // op not supported } } STATIC mp_obj_t bluetooth_uuid_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { if (!mp_obj_is_type(rhs_in, &mp_type_bluetooth_uuid)) { return MP_OBJ_NULL; } mp_obj_bluetooth_uuid_t *lhs = MP_OBJ_TO_PTR(lhs_in); mp_obj_bluetooth_uuid_t *rhs = MP_OBJ_TO_PTR(rhs_in); switch (op) { case MP_BINARY_OP_EQUAL: case MP_BINARY_OP_LESS: case MP_BINARY_OP_LESS_EQUAL: case MP_BINARY_OP_MORE: case MP_BINARY_OP_MORE_EQUAL: if (lhs->type == rhs->type) { return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs->data, lhs->type, rhs->data, rhs->type)); } else { return mp_binary_op(op, MP_OBJ_NEW_SMALL_INT(lhs->type), MP_OBJ_NEW_SMALL_INT(rhs->type)); } default: return MP_OBJ_NULL; // op not supported } } STATIC void bluetooth_uuid_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_bluetooth_uuid_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "UUID(%s", self->type <= 4 ? "0x" : "'"); for (int i = 0; i < self->type; ++i) { if (i == 4 || i == 6 || i == 8 || i == 10) { mp_printf(print, "-"); } mp_printf(print, "%02x", self->data[self->type - 1 - i]); } if (self->type == MP_BLUETOOTH_UUID_TYPE_128) { mp_printf(print, "'"); } mp_printf(print, ")"); } STATIC mp_int_t bluetooth_uuid_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { mp_obj_bluetooth_uuid_t *self = MP_OBJ_TO_PTR(self_in); if (flags != MP_BUFFER_READ) { return 1; } bufinfo->buf = self->data; bufinfo->len = self->type; bufinfo->typecode = 'B'; return 0; } #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS && MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE STATIC void ringbuf_put_uuid(ringbuf_t *ringbuf, mp_obj_bluetooth_uuid_t *uuid) { assert(ringbuf_free(ringbuf) >= (size_t)uuid->type + 1); ringbuf_put(ringbuf, uuid->type); for (int i = 0; i < uuid->type; ++i) { ringbuf_put(ringbuf, uuid->data[i]); } } STATIC void ringbuf_get_uuid(ringbuf_t *ringbuf, mp_obj_bluetooth_uuid_t *uuid) { assert(ringbuf_avail(ringbuf) >= 1); uuid->type = ringbuf_get(ringbuf); assert(ringbuf_avail(ringbuf) >= uuid->type); for (int i = 0; i < uuid->type; ++i) { uuid->data[i] = ringbuf_get(ringbuf); } } #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE const mp_obj_type_t mp_type_bluetooth_uuid = { { &mp_type_type }, .name = MP_QSTR_UUID, .make_new = bluetooth_uuid_make_new, .unary_op = bluetooth_uuid_unary_op, .binary_op = bluetooth_uuid_binary_op, .locals_dict = NULL, .print = bluetooth_uuid_print, .buffer_p = { .get_buffer = bluetooth_uuid_get_buffer }, }; // ---------------------------------------------------------------------------- // Bluetooth object: General // ---------------------------------------------------------------------------- STATIC mp_obj_t bluetooth_ble_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { (void)type; (void)n_args; (void)n_kw; (void)all_args; if (MP_STATE_VM(bluetooth) == MP_OBJ_NULL) { mp_obj_bluetooth_ble_t *o = m_new0(mp_obj_bluetooth_ble_t, 1); o->base.type = &mp_type_bluetooth_ble; o->irq_handler = mp_const_none; #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS // Pre-allocate the event data tuple to prevent needing to allocate in the IRQ handler. o->irq_data_tuple = mp_obj_new_tuple(MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_TUPLE_LEN, NULL); // Pre-allocated buffers for address, payload and uuid. mp_obj_memoryview_init(&o->irq_data_addr, 'B', 0, 0, o->irq_data_addr_bytes); o->irq_data_data_alloc = MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_BYTES_LEN(MICROPY_PY_BLUETOOTH_RINGBUF_SIZE); mp_obj_memoryview_init(&o->irq_data_data, 'B', 0, 0, m_new(uint8_t, o->irq_data_data_alloc)); o->irq_data_uuid.base.type = &mp_type_bluetooth_uuid; // Allocate the default ringbuf. ringbuf_alloc(&o->ringbuf, MICROPY_PY_BLUETOOTH_RINGBUF_SIZE); #endif MP_STATE_VM(bluetooth) = MP_OBJ_FROM_PTR(o); } return MP_STATE_VM(bluetooth); } STATIC mp_obj_t bluetooth_ble_active(size_t n_args, const mp_obj_t *args) { if (n_args == 2) { // Boolean enable/disable argument supplied, set current state. if (mp_obj_is_true(args[1])) { int err = mp_bluetooth_init(); bluetooth_handle_errno(err); } else { mp_bluetooth_deinit(); } } // Return current state. return mp_obj_new_bool(mp_bluetooth_is_active()); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_active_obj, 1, 2, bluetooth_ble_active); STATIC mp_obj_t bluetooth_ble_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { if (kwargs->used == 0) { // Get config value if (n_args != 2) { mp_raise_TypeError(MP_ERROR_TEXT("must query one param")); } switch (mp_obj_str_get_qstr(args[1])) { case MP_QSTR_gap_name: { const uint8_t *buf; size_t len = mp_bluetooth_gap_get_device_name(&buf); return mp_obj_new_bytes(buf, len); } case MP_QSTR_mac: { uint8_t addr_type; uint8_t addr[6]; mp_bluetooth_get_current_address(&addr_type, addr); mp_obj_t items[] = { MP_OBJ_NEW_SMALL_INT(addr_type), mp_obj_new_bytes(addr, MP_ARRAY_SIZE(addr)) }; return mp_obj_new_tuple(2, items); } #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS case MP_QSTR_rxbuf: { mp_obj_bluetooth_ble_t *self = MP_OBJ_TO_PTR(args[0]); return mp_obj_new_int(self->ringbuf.size); } #endif case MP_QSTR_mtu: return mp_obj_new_int(mp_bluetooth_get_preferred_mtu()); default: mp_raise_ValueError(MP_ERROR_TEXT("unknown config param")); } } else { // Set config value(s) if (n_args != 1) { mp_raise_TypeError(MP_ERROR_TEXT("can't specify pos and kw args")); } for (size_t i = 0; i < kwargs->alloc; ++i) { if (MP_MAP_SLOT_IS_FILLED(kwargs, i)) { mp_map_elem_t *e = &kwargs->table[i]; switch (mp_obj_str_get_qstr(e->key)) { case MP_QSTR_gap_name: { mp_buffer_info_t bufinfo; mp_get_buffer_raise(e->value, &bufinfo, MP_BUFFER_READ); bluetooth_handle_errno(mp_bluetooth_gap_set_device_name(bufinfo.buf, bufinfo.len)); break; } #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS case MP_QSTR_rxbuf: { // Determine new buffer sizes mp_int_t ringbuf_alloc = mp_obj_get_int(e->value); if (ringbuf_alloc < 16 || ringbuf_alloc > 0xffff) { mp_raise_ValueError(NULL); } size_t irq_data_alloc = MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_BYTES_LEN(ringbuf_alloc); // Allocate new buffers uint8_t *ringbuf = m_new(uint8_t, ringbuf_alloc); uint8_t *irq_data = m_new(uint8_t, irq_data_alloc); // Get old buffer sizes and pointers mp_obj_bluetooth_ble_t *self = MP_OBJ_TO_PTR(args[0]); uint8_t *old_ringbuf_buf = self->ringbuf.buf; size_t old_ringbuf_alloc = self->ringbuf.size; uint8_t *old_irq_data_buf = (uint8_t *)self->irq_data_data.items; size_t old_irq_data_alloc = self->irq_data_data_alloc; // Atomically update the ringbuf and irq data MICROPY_PY_BLUETOOTH_ENTER self->ringbuf.size = ringbuf_alloc; self->ringbuf.buf = ringbuf; self->ringbuf.iget = 0; self->ringbuf.iput = 0; self->irq_data_data_alloc = irq_data_alloc; self->irq_data_data.items = irq_data; MICROPY_PY_BLUETOOTH_EXIT // Free old buffers m_del(uint8_t, old_ringbuf_buf, old_ringbuf_alloc); m_del(uint8_t, old_irq_data_buf, old_irq_data_alloc); break; } #endif case MP_QSTR_mtu: { mp_int_t mtu = mp_obj_get_int(e->value); bluetooth_handle_errno(mp_bluetooth_set_preferred_mtu(mtu)); break; } case MP_QSTR_addr_mode: { mp_int_t addr_mode = mp_obj_get_int(e->value); mp_bluetooth_set_address_mode(addr_mode); break; } #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING case MP_QSTR_bond: { bool bonding_enabled = mp_obj_is_true(e->value); mp_bluetooth_set_bonding(bonding_enabled); break; } case MP_QSTR_mitm: { bool mitm_protection = mp_obj_is_true(e->value); mp_bluetooth_set_mitm_protection(mitm_protection); break; } case MP_QSTR_io: { mp_int_t io_capability = mp_obj_get_int(e->value); mp_bluetooth_set_io_capability(io_capability); break; } case MP_QSTR_le_secure: { bool le_secure_required = mp_obj_is_true(e->value); mp_bluetooth_set_le_secure(le_secure_required); break; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING default: mp_raise_ValueError(MP_ERROR_TEXT("unknown config param")); } } } return mp_const_none; } } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bluetooth_ble_config_obj, 1, bluetooth_ble_config); STATIC mp_obj_t bluetooth_ble_irq(mp_obj_t self_in, mp_obj_t handler_in) { (void)self_in; if (handler_in != mp_const_none && !mp_obj_is_callable(handler_in)) { mp_raise_ValueError(MP_ERROR_TEXT("invalid handler")); } // Update the callback. MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); o->irq_handler = handler_in; MICROPY_PY_BLUETOOTH_EXIT return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_irq_obj, bluetooth_ble_irq); // ---------------------------------------------------------------------------- // Bluetooth object: GAP // ---------------------------------------------------------------------------- STATIC mp_obj_t bluetooth_ble_gap_advertise(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_interval_us, ARG_adv_data, ARG_resp_data, ARG_connectable }; static const mp_arg_t allowed_args[] = { { MP_QSTR_interval_us, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_SMALL_INT(500000)} }, { MP_QSTR_adv_data, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_resp_data, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_connectable, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = MP_ROM_TRUE} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); if (args[ARG_interval_us].u_obj == mp_const_none) { mp_bluetooth_gap_advertise_stop(); return mp_const_none; } mp_int_t interval_us = mp_obj_get_int(args[ARG_interval_us].u_obj); bool connectable = mp_obj_is_true(args[ARG_connectable].u_obj); mp_buffer_info_t adv_bufinfo = {0}; if (args[ARG_adv_data].u_obj != mp_const_none) { mp_get_buffer_raise(args[ARG_adv_data].u_obj, &adv_bufinfo, MP_BUFFER_READ); } mp_buffer_info_t resp_bufinfo = {0}; if (args[ARG_resp_data].u_obj != mp_const_none) { mp_get_buffer_raise(args[ARG_resp_data].u_obj, &resp_bufinfo, MP_BUFFER_READ); } return bluetooth_handle_errno(mp_bluetooth_gap_advertise_start(connectable, interval_us, adv_bufinfo.buf, adv_bufinfo.len, resp_bufinfo.buf, resp_bufinfo.len)); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bluetooth_ble_gap_advertise_obj, 1, bluetooth_ble_gap_advertise); STATIC int bluetooth_gatts_register_service(mp_obj_t uuid_in, mp_obj_t characteristics_in, uint16_t **handles, size_t *num_handles) { if (!mp_obj_is_type(uuid_in, &mp_type_bluetooth_uuid)) { mp_raise_ValueError(MP_ERROR_TEXT("invalid service UUID")); } mp_obj_bluetooth_uuid_t *service_uuid = MP_OBJ_TO_PTR(uuid_in); mp_obj_t len_in = mp_obj_len(characteristics_in); size_t len = mp_obj_get_int(len_in); mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(characteristics_in, &iter_buf); mp_obj_t characteristic_obj; // Lists of characteristic uuids and flags. mp_obj_bluetooth_uuid_t **characteristic_uuids = m_new(mp_obj_bluetooth_uuid_t *, len); uint16_t *characteristic_flags = m_new(uint16_t, len); // Flattened list of descriptor uuids and flags. Grows (realloc) as more descriptors are encountered. mp_obj_bluetooth_uuid_t **descriptor_uuids = NULL; uint16_t *descriptor_flags = NULL; // How many descriptors in the flattened list per characteristic. uint8_t *num_descriptors = m_new(uint8_t, len); // Inititally allocate enough room for the number of characteristics. // Will be grown to accommodate descriptors as necessary. *num_handles = len; *handles = m_new(uint16_t, *num_handles); // Extract out characteristic uuids & flags. int characteristic_index = 0; // characteristic index. int handle_index = 0; // handle index. int descriptor_index = 0; // descriptor index. while ((characteristic_obj = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { // (uuid, flags, (optional descriptors),) size_t characteristic_len; mp_obj_t *characteristic_items; mp_obj_get_array(characteristic_obj, &characteristic_len, &characteristic_items); if (characteristic_len < 2 || characteristic_len > 3) { mp_raise_ValueError(MP_ERROR_TEXT("invalid characteristic tuple")); } mp_obj_t uuid_obj = characteristic_items[0]; if (!mp_obj_is_type(uuid_obj, &mp_type_bluetooth_uuid)) { mp_raise_ValueError(MP_ERROR_TEXT("invalid characteristic UUID")); } (*handles)[handle_index++] = 0xffff; // Optional third element, iterable of descriptors. if (characteristic_len >= 3) { mp_obj_t descriptors_len_in = mp_obj_len(characteristic_items[2]); num_descriptors[characteristic_index] = mp_obj_get_int(descriptors_len_in); if (num_descriptors[characteristic_index] == 0) { continue; } // Grow the flattened uuids and flags arrays with this many more descriptors. descriptor_uuids = m_renew(mp_obj_bluetooth_uuid_t *, descriptor_uuids, descriptor_index, descriptor_index + num_descriptors[characteristic_index]); descriptor_flags = m_renew(uint16_t, descriptor_flags, descriptor_index, descriptor_index + num_descriptors[characteristic_index]); // Also grow the handles array. *handles = m_renew(uint16_t, *handles, *num_handles, *num_handles + num_descriptors[characteristic_index]); mp_obj_iter_buf_t iter_buf_desc; mp_obj_t iterable_desc = mp_getiter(characteristic_items[2], &iter_buf_desc); mp_obj_t descriptor_obj; // Extract out descriptors for this characteristic. while ((descriptor_obj = mp_iternext(iterable_desc)) != MP_OBJ_STOP_ITERATION) { // (uuid, flags,) mp_obj_t *descriptor_items; mp_obj_get_array_fixed_n(descriptor_obj, 2, &descriptor_items); mp_obj_t desc_uuid_obj = descriptor_items[0]; if (!mp_obj_is_type(desc_uuid_obj, &mp_type_bluetooth_uuid)) { mp_raise_ValueError(MP_ERROR_TEXT("invalid descriptor UUID")); } descriptor_uuids[descriptor_index] = MP_OBJ_TO_PTR(desc_uuid_obj); descriptor_flags[descriptor_index] = mp_obj_get_int(descriptor_items[1]); ++descriptor_index; (*handles)[handle_index++] = 0xffff; } // Reflect that we've grown the handles array. *num_handles += num_descriptors[characteristic_index]; } characteristic_uuids[characteristic_index] = MP_OBJ_TO_PTR(uuid_obj); characteristic_flags[characteristic_index] = mp_obj_get_int(characteristic_items[1]); ++characteristic_index; } // Add service. return mp_bluetooth_gatts_register_service(service_uuid, characteristic_uuids, characteristic_flags, descriptor_uuids, descriptor_flags, num_descriptors, *handles, len); } STATIC mp_obj_t bluetooth_ble_gatts_register_services(mp_obj_t self_in, mp_obj_t services_in) { (void)self_in; mp_obj_t len_in = mp_obj_len(services_in); size_t len = mp_obj_get_int(len_in); mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(services_in, &iter_buf); mp_obj_t service_tuple_obj; mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(len, NULL)); uint16_t **handles = m_new0(uint16_t *, len); size_t *num_handles = m_new0(size_t, len); // TODO: Add a `append` kwarg (defaulting to False) to make this behavior optional. bool append = false; int err = mp_bluetooth_gatts_register_service_begin(append); if (err != 0) { return bluetooth_handle_errno(err); } size_t i = 0; while ((service_tuple_obj = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { // (uuid, chars) mp_obj_t *service_items; mp_obj_get_array_fixed_n(service_tuple_obj, 2, &service_items); err = bluetooth_gatts_register_service(service_items[0], service_items[1], &handles[i], &num_handles[i]); if (err != 0) { return bluetooth_handle_errno(err); } ++i; } // On Nimble, this will actually perform the registration, making the handles valid. err = mp_bluetooth_gatts_register_service_end(); if (err != 0) { return bluetooth_handle_errno(err); } // Return tuple of tuple of value handles. // TODO: Also the Generic Access service characteristics? for (i = 0; i < len; ++i) { mp_obj_tuple_t *service_handles = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_handles[i], NULL)); for (size_t j = 0; j < num_handles[i]; ++j) { service_handles->items[j] = MP_OBJ_NEW_SMALL_INT(handles[i][j]); } result->items[i] = MP_OBJ_FROM_PTR(service_handles); } // Free temporary arrays. m_del(uint16_t *, handles, len); m_del(size_t, num_handles, len); return MP_OBJ_FROM_PTR(result); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gatts_register_services_obj, bluetooth_ble_gatts_register_services); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE STATIC mp_obj_t bluetooth_ble_gap_connect(size_t n_args, const mp_obj_t *args) { uint8_t addr_type = mp_obj_get_int(args[1]); mp_buffer_info_t bufinfo = {0}; mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ); if (bufinfo.len != 6) { mp_raise_ValueError(MP_ERROR_TEXT("invalid addr")); } mp_int_t scan_duration_ms = MP_BLUETOOTH_CONNECT_DEFAULT_SCAN_DURATION_MS; if (n_args == 4) { scan_duration_ms = mp_obj_get_int(args[3]); } int err = mp_bluetooth_gap_peripheral_connect(addr_type, bufinfo.buf, scan_duration_ms); return bluetooth_handle_errno(err); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gap_connect_obj, 3, 4, bluetooth_ble_gap_connect); STATIC mp_obj_t bluetooth_ble_gap_scan(size_t n_args, const mp_obj_t *args) { // Default is indefinite scan, with the NimBLE "background scan" interval and window. mp_int_t duration_ms = 0; mp_int_t interval_us = 1280000; mp_int_t window_us = 11250; bool active_scan = false; if (n_args > 1) { if (args[1] == mp_const_none) { // scan(None) --> stop scan. return bluetooth_handle_errno(mp_bluetooth_gap_scan_stop()); } duration_ms = mp_obj_get_int(args[1]); if (n_args > 2) { interval_us = mp_obj_get_int(args[2]); if (n_args > 3) { window_us = mp_obj_get_int(args[3]); if (n_args > 4) { active_scan = mp_obj_is_true(args[4]); } } } } return bluetooth_handle_errno(mp_bluetooth_gap_scan_start(duration_ms, interval_us, window_us, active_scan)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gap_scan_obj, 1, 5, bluetooth_ble_gap_scan); #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE STATIC mp_obj_t bluetooth_ble_gap_disconnect(mp_obj_t self_in, mp_obj_t conn_handle_in) { (void)self_in; uint16_t conn_handle = mp_obj_get_int(conn_handle_in); int err = mp_bluetooth_gap_disconnect(conn_handle); if (err == 0) { return mp_const_true; } else if (err == MP_ENOTCONN) { return mp_const_false; } else { return bluetooth_handle_errno(err); } } STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gap_disconnect_obj, bluetooth_ble_gap_disconnect); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING STATIC mp_obj_t bluetooth_ble_gap_pair(mp_obj_t self_in, mp_obj_t conn_handle_in) { (void)self_in; uint16_t conn_handle = mp_obj_get_int(conn_handle_in); return bluetooth_handle_errno(mp_bluetooth_gap_pair(conn_handle)); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gap_pair_obj, bluetooth_ble_gap_pair); STATIC mp_obj_t bluetooth_ble_gap_passkey(size_t n_args, const mp_obj_t *args) { uint16_t conn_handle = mp_obj_get_int(args[1]); uint8_t action = mp_obj_get_int(args[2]); mp_int_t passkey = mp_obj_get_int(args[3]); return bluetooth_handle_errno(mp_bluetooth_gap_passkey(conn_handle, action, passkey)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gap_passkey_obj, 4, 4, bluetooth_ble_gap_passkey); #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // ---------------------------------------------------------------------------- // Bluetooth object: GATTS (Peripheral/Advertiser role) // ---------------------------------------------------------------------------- STATIC mp_obj_t bluetooth_ble_gatts_read(mp_obj_t self_in, mp_obj_t value_handle_in) { (void)self_in; size_t len = 0; uint8_t *buf; mp_bluetooth_gatts_read(mp_obj_get_int(value_handle_in), &buf, &len); return mp_obj_new_bytes(buf, len); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gatts_read_obj, bluetooth_ble_gatts_read); STATIC mp_obj_t bluetooth_ble_gatts_write(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo = {0}; mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ); bool send_update = false; if (n_args > 3) { send_update = mp_obj_is_true(args[3]); } bluetooth_handle_errno(mp_bluetooth_gatts_write(mp_obj_get_int(args[1]), bufinfo.buf, bufinfo.len, send_update)); return MP_OBJ_NEW_SMALL_INT(bufinfo.len); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gatts_write_obj, 3, 4, bluetooth_ble_gatts_write); STATIC mp_obj_t bluetooth_ble_gatts_notify(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t value_handle = mp_obj_get_int(args[2]); if (n_args == 4 && args[3] != mp_const_none) { mp_buffer_info_t bufinfo = {0}; mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); int err = mp_bluetooth_gatts_notify_send(conn_handle, value_handle, bufinfo.buf, bufinfo.len); bluetooth_handle_errno(err); return mp_const_none; } else { int err = mp_bluetooth_gatts_notify(conn_handle, value_handle); return bluetooth_handle_errno(err); } } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gatts_notify_obj, 3, 4, bluetooth_ble_gatts_notify); STATIC mp_obj_t bluetooth_ble_gatts_indicate(mp_obj_t self_in, mp_obj_t conn_handle_in, mp_obj_t value_handle_in) { (void)self_in; mp_int_t conn_handle = mp_obj_get_int(conn_handle_in); mp_int_t value_handle = mp_obj_get_int(value_handle_in); int err = mp_bluetooth_gatts_indicate(conn_handle, value_handle); return bluetooth_handle_errno(err); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_gatts_indicate_obj, bluetooth_ble_gatts_indicate); STATIC mp_obj_t bluetooth_ble_gatts_set_buffer(size_t n_args, const mp_obj_t *args) { mp_int_t value_handle = mp_obj_get_int(args[1]); mp_int_t len = mp_obj_get_int(args[2]); bool append = n_args >= 4 && mp_obj_is_true(args[3]); return bluetooth_handle_errno(mp_bluetooth_gatts_set_buffer(value_handle, len, append)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gatts_set_buffer_obj, 3, 4, bluetooth_ble_gatts_set_buffer); // ---------------------------------------------------------------------------- // Bluetooth object: GATTC (Central/Scanner role) // ---------------------------------------------------------------------------- #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT STATIC mp_obj_t bluetooth_ble_gattc_discover_services(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_obj_bluetooth_uuid_t *uuid = NULL; if (n_args == 3 && args[2] != mp_const_none) { if (!mp_obj_is_type(args[2], &mp_type_bluetooth_uuid)) { mp_raise_TypeError(MP_ERROR_TEXT("UUID")); } uuid = MP_OBJ_TO_PTR(args[2]); } return bluetooth_handle_errno(mp_bluetooth_gattc_discover_primary_services(conn_handle, uuid)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gattc_discover_services_obj, 2, 3, bluetooth_ble_gattc_discover_services); STATIC mp_obj_t bluetooth_ble_gattc_discover_characteristics(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t start_handle = mp_obj_get_int(args[2]); mp_int_t end_handle = mp_obj_get_int(args[3]); mp_obj_bluetooth_uuid_t *uuid = NULL; if (n_args == 5 && args[4] != mp_const_none) { if (!mp_obj_is_type(args[4], &mp_type_bluetooth_uuid)) { mp_raise_TypeError(MP_ERROR_TEXT("UUID")); } uuid = MP_OBJ_TO_PTR(args[4]); } return bluetooth_handle_errno(mp_bluetooth_gattc_discover_characteristics(conn_handle, start_handle, end_handle, uuid)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gattc_discover_characteristics_obj, 4, 5, bluetooth_ble_gattc_discover_characteristics); STATIC mp_obj_t bluetooth_ble_gattc_discover_descriptors(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t start_handle = mp_obj_get_int(args[2]); mp_int_t end_handle = mp_obj_get_int(args[3]); return bluetooth_handle_errno(mp_bluetooth_gattc_discover_descriptors(conn_handle, start_handle, end_handle)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gattc_discover_descriptors_obj, 4, 4, bluetooth_ble_gattc_discover_descriptors); STATIC mp_obj_t bluetooth_ble_gattc_read(mp_obj_t self_in, mp_obj_t conn_handle_in, mp_obj_t value_handle_in) { (void)self_in; mp_int_t conn_handle = mp_obj_get_int(conn_handle_in); mp_int_t value_handle = mp_obj_get_int(value_handle_in); return bluetooth_handle_errno(mp_bluetooth_gattc_read(conn_handle, value_handle)); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_gattc_read_obj, bluetooth_ble_gattc_read); STATIC mp_obj_t bluetooth_ble_gattc_write(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t value_handle = mp_obj_get_int(args[2]); mp_obj_t data = args[3]; mp_buffer_info_t bufinfo = {0}; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); size_t len = bufinfo.len; unsigned int mode = MP_BLUETOOTH_WRITE_MODE_NO_RESPONSE; if (n_args == 5) { mode = mp_obj_get_int(args[4]); } return bluetooth_handle_errno(mp_bluetooth_gattc_write(conn_handle, value_handle, bufinfo.buf, &len, mode)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_gattc_write_obj, 4, 5, bluetooth_ble_gattc_write); STATIC mp_obj_t bluetooth_ble_gattc_exchange_mtu(mp_obj_t self_in, mp_obj_t conn_handle_in) { (void)self_in; uint16_t conn_handle = mp_obj_get_int(conn_handle_in); return bluetooth_handle_errno(mp_bluetooth_gattc_exchange_mtu(conn_handle)); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(bluetooth_ble_gattc_exchange_mtu_obj, bluetooth_ble_gattc_exchange_mtu); #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS STATIC mp_obj_t bluetooth_ble_l2cap_listen(mp_obj_t self_in, mp_obj_t psm_in, mp_obj_t mtu_in) { (void)self_in; mp_int_t psm = mp_obj_get_int(psm_in); mp_int_t mtu = MAX(32, MIN(UINT16_MAX, mp_obj_get_int(mtu_in))); return bluetooth_handle_errno(mp_bluetooth_l2cap_listen(psm, mtu)); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_l2cap_listen_obj, bluetooth_ble_l2cap_listen); STATIC mp_obj_t bluetooth_ble_l2cap_connect(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t psm = mp_obj_get_int(args[2]); mp_int_t mtu = MAX(32, MIN(UINT16_MAX, mp_obj_get_int(args[3]))); return bluetooth_handle_errno(mp_bluetooth_l2cap_connect(conn_handle, psm, mtu)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_l2cap_connect_obj, 4, 4, bluetooth_ble_l2cap_connect); STATIC mp_obj_t bluetooth_ble_l2cap_disconnect(mp_obj_t self_in, mp_obj_t conn_handle_in, mp_obj_t cid_in) { (void)self_in; mp_int_t conn_handle = mp_obj_get_int(conn_handle_in); mp_int_t cid = mp_obj_get_int(cid_in); return bluetooth_handle_errno(mp_bluetooth_l2cap_disconnect(conn_handle, cid)); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(bluetooth_ble_l2cap_disconnect_obj, bluetooth_ble_l2cap_disconnect); STATIC mp_obj_t bluetooth_ble_l2cap_send(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t cid = mp_obj_get_int(args[2]); mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); bool stalled = false; bluetooth_handle_errno(mp_bluetooth_l2cap_send(conn_handle, cid, bufinfo.buf, bufinfo.len, &stalled)); // Return True if the channel is still ready to send. return mp_obj_new_bool(!stalled); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_l2cap_send_obj, 4, 4, bluetooth_ble_l2cap_send); STATIC mp_obj_t bluetooth_ble_l2cap_recvinto(size_t n_args, const mp_obj_t *args) { mp_int_t conn_handle = mp_obj_get_int(args[1]); mp_int_t cid = mp_obj_get_int(args[2]); mp_buffer_info_t bufinfo = {0}; if (args[3] != mp_const_none) { mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_WRITE); } bluetooth_handle_errno(mp_bluetooth_l2cap_recvinto(conn_handle, cid, bufinfo.buf, &bufinfo.len)); return MP_OBJ_NEW_SMALL_INT(bufinfo.len); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_l2cap_recvinto_obj, 4, 4, bluetooth_ble_l2cap_recvinto); #endif // MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS #if MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD STATIC mp_obj_t bluetooth_ble_hci_cmd(size_t n_args, const mp_obj_t *args) { mp_int_t ogf = mp_obj_get_int(args[1]); mp_int_t ocf = mp_obj_get_int(args[2]); mp_buffer_info_t bufinfo_request = {0}; mp_buffer_info_t bufinfo_response = {0}; mp_get_buffer_raise(args[3], &bufinfo_request, MP_BUFFER_READ); mp_get_buffer_raise(args[4], &bufinfo_response, MP_BUFFER_WRITE); uint8_t status = 0; bluetooth_handle_errno(mp_bluetooth_hci_cmd(ogf, ocf, bufinfo_request.buf, bufinfo_request.len, bufinfo_response.buf, bufinfo_response.len, &status)); return MP_OBJ_NEW_SMALL_INT(status); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bluetooth_ble_hci_cmd_obj, 5, 5, bluetooth_ble_hci_cmd); #endif // MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD // ---------------------------------------------------------------------------- // Bluetooth object: Definition // ---------------------------------------------------------------------------- STATIC const mp_rom_map_elem_t bluetooth_ble_locals_dict_table[] = { // General { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&bluetooth_ble_active_obj) }, { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&bluetooth_ble_config_obj) }, { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&bluetooth_ble_irq_obj) }, // GAP { MP_ROM_QSTR(MP_QSTR_gap_advertise), MP_ROM_PTR(&bluetooth_ble_gap_advertise_obj) }, #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE { MP_ROM_QSTR(MP_QSTR_gap_connect), MP_ROM_PTR(&bluetooth_ble_gap_connect_obj) }, { MP_ROM_QSTR(MP_QSTR_gap_scan), MP_ROM_PTR(&bluetooth_ble_gap_scan_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_gap_disconnect), MP_ROM_PTR(&bluetooth_ble_gap_disconnect_obj) }, #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING { MP_ROM_QSTR(MP_QSTR_gap_pair), MP_ROM_PTR(&bluetooth_ble_gap_pair_obj) }, { MP_ROM_QSTR(MP_QSTR_gap_passkey), MP_ROM_PTR(&bluetooth_ble_gap_passkey_obj) }, #endif // GATT Server { MP_ROM_QSTR(MP_QSTR_gatts_register_services), MP_ROM_PTR(&bluetooth_ble_gatts_register_services_obj) }, { MP_ROM_QSTR(MP_QSTR_gatts_read), MP_ROM_PTR(&bluetooth_ble_gatts_read_obj) }, { MP_ROM_QSTR(MP_QSTR_gatts_write), MP_ROM_PTR(&bluetooth_ble_gatts_write_obj) }, { MP_ROM_QSTR(MP_QSTR_gatts_notify), MP_ROM_PTR(&bluetooth_ble_gatts_notify_obj) }, { MP_ROM_QSTR(MP_QSTR_gatts_indicate), MP_ROM_PTR(&bluetooth_ble_gatts_indicate_obj) }, { MP_ROM_QSTR(MP_QSTR_gatts_set_buffer), MP_ROM_PTR(&bluetooth_ble_gatts_set_buffer_obj) }, #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT // GATT Client { MP_ROM_QSTR(MP_QSTR_gattc_discover_services), MP_ROM_PTR(&bluetooth_ble_gattc_discover_services_obj) }, { MP_ROM_QSTR(MP_QSTR_gattc_discover_characteristics), MP_ROM_PTR(&bluetooth_ble_gattc_discover_characteristics_obj) }, { MP_ROM_QSTR(MP_QSTR_gattc_discover_descriptors), MP_ROM_PTR(&bluetooth_ble_gattc_discover_descriptors_obj) }, { MP_ROM_QSTR(MP_QSTR_gattc_read), MP_ROM_PTR(&bluetooth_ble_gattc_read_obj) }, { MP_ROM_QSTR(MP_QSTR_gattc_write), MP_ROM_PTR(&bluetooth_ble_gattc_write_obj) }, { MP_ROM_QSTR(MP_QSTR_gattc_exchange_mtu), MP_ROM_PTR(&bluetooth_ble_gattc_exchange_mtu_obj) }, #endif #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS { MP_ROM_QSTR(MP_QSTR_l2cap_listen), MP_ROM_PTR(&bluetooth_ble_l2cap_listen_obj) }, { MP_ROM_QSTR(MP_QSTR_l2cap_connect), MP_ROM_PTR(&bluetooth_ble_l2cap_connect_obj) }, { MP_ROM_QSTR(MP_QSTR_l2cap_disconnect), MP_ROM_PTR(&bluetooth_ble_l2cap_disconnect_obj) }, { MP_ROM_QSTR(MP_QSTR_l2cap_send), MP_ROM_PTR(&bluetooth_ble_l2cap_send_obj) }, { MP_ROM_QSTR(MP_QSTR_l2cap_recvinto), MP_ROM_PTR(&bluetooth_ble_l2cap_recvinto_obj) }, #endif #if MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD { MP_ROM_QSTR(MP_QSTR_hci_cmd), MP_ROM_PTR(&bluetooth_ble_hci_cmd_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(bluetooth_ble_locals_dict, bluetooth_ble_locals_dict_table); STATIC const mp_obj_type_t mp_type_bluetooth_ble = { { &mp_type_type }, .name = MP_QSTR_BLE, .make_new = bluetooth_ble_make_new, .locals_dict = (void *)&bluetooth_ble_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_bluetooth_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ubluetooth) }, { MP_ROM_QSTR(MP_QSTR_BLE), MP_ROM_PTR(&mp_type_bluetooth_ble) }, { MP_ROM_QSTR(MP_QSTR_UUID), MP_ROM_PTR(&mp_type_bluetooth_uuid) }, // TODO: Deprecate these flags (recommend copying the constants from modbluetooth.h instead). { MP_ROM_QSTR(MP_QSTR_FLAG_READ), MP_ROM_INT(MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ) }, { MP_ROM_QSTR(MP_QSTR_FLAG_WRITE), MP_ROM_INT(MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE) }, { MP_ROM_QSTR(MP_QSTR_FLAG_NOTIFY), MP_ROM_INT(MP_BLUETOOTH_CHARACTERISTIC_FLAG_NOTIFY) }, { MP_ROM_QSTR(MP_QSTR_FLAG_INDICATE), MP_ROM_INT(MP_BLUETOOTH_CHARACTERISTIC_FLAG_INDICATE) }, { MP_ROM_QSTR(MP_QSTR_FLAG_WRITE_NO_RESPONSE), MP_ROM_INT(MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE_NO_RESPONSE) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_bluetooth_globals, mp_module_bluetooth_globals_table); const mp_obj_module_t mp_module_ubluetooth = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_bluetooth_globals, }; // Helpers #if !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS STATIC void ringbuf_extract(ringbuf_t *ringbuf, mp_obj_tuple_t *data_tuple, size_t n_u16, size_t n_u8, mp_obj_array_t *bytes_addr, size_t n_i8, mp_obj_bluetooth_uuid_t *uuid, mp_obj_array_t *bytes_data) { assert(ringbuf_avail(ringbuf) >= n_u16 * 2 + n_u8 + (bytes_addr ? 6 : 0) + n_i8 + (uuid ? 1 : 0) + (bytes_data ? 1 : 0)); size_t j = 0; for (size_t i = 0; i < n_u16; ++i) { data_tuple->items[j++] = MP_OBJ_NEW_SMALL_INT(ringbuf_get16(ringbuf)); } for (size_t i = 0; i < n_u8; ++i) { data_tuple->items[j++] = MP_OBJ_NEW_SMALL_INT(ringbuf_get(ringbuf)); } if (bytes_addr) { bytes_addr->len = 6; for (size_t i = 0; i < bytes_addr->len; ++i) { ((uint8_t *)bytes_addr->items)[i] = ringbuf_get(ringbuf); } data_tuple->items[j++] = MP_OBJ_FROM_PTR(bytes_addr); } for (size_t i = 0; i < n_i8; ++i) { // Note the int8_t got packed into the ringbuf as a uint8_t. data_tuple->items[j++] = MP_OBJ_NEW_SMALL_INT((int8_t)ringbuf_get(ringbuf)); } #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE if (uuid) { ringbuf_get_uuid(ringbuf, uuid); data_tuple->items[j++] = MP_OBJ_FROM_PTR(uuid); } #endif // The code that enqueues into the ringbuf should ensure that it doesn't // put more than bt->irq_data_data_alloc bytes into the ringbuf, because // that's what's available here. if (bytes_data) { bytes_data->len = ringbuf_get16(ringbuf); for (size_t i = 0; i < bytes_data->len; ++i) { ((uint8_t *)bytes_data->items)[i] = ringbuf_get(ringbuf); } data_tuple->items[j++] = MP_OBJ_FROM_PTR(bytes_data); } data_tuple->len = j; } STATIC mp_obj_t bluetooth_ble_invoke_irq(mp_obj_t none_in) { (void)none_in; // This is always executing in schedule context. mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); o->irq_scheduled = false; for (;;) { MICROPY_PY_BLUETOOTH_ENTER mp_int_t event = ringbuf_get(&o->ringbuf); if (event < 0) { // Nothing available in ringbuf. MICROPY_PY_BLUETOOTH_EXIT break; } // Although we're in schedule context, this code still avoids using any allocations: // - IRQs are disabled (to protect the ringbuf), and we need to avoid triggering GC // - The user's handler might not alloc, so we shouldn't either. mp_obj_t handler = handler = o->irq_handler; mp_obj_tuple_t *data_tuple = MP_OBJ_TO_PTR(o->irq_data_tuple); if (event == MP_BLUETOOTH_IRQ_CENTRAL_CONNECT || event == MP_BLUETOOTH_IRQ_PERIPHERAL_CONNECT || event == MP_BLUETOOTH_IRQ_CENTRAL_DISCONNECT || event == MP_BLUETOOTH_IRQ_PERIPHERAL_DISCONNECT) { // conn_handle, addr_type, addr ringbuf_extract(&o->ringbuf, data_tuple, 1, 1, &o->irq_data_addr, 0, NULL, NULL); } else if (event == MP_BLUETOOTH_IRQ_CONNECTION_UPDATE) { // conn_handle, conn_interval, conn_latency, supervision_timeout, status ringbuf_extract(&o->ringbuf, data_tuple, 5, 0, NULL, 0, NULL, NULL); } else if (event == MP_BLUETOOTH_IRQ_GATTS_WRITE) { // conn_handle, value_handle ringbuf_extract(&o->ringbuf, data_tuple, 2, 0, NULL, 0, NULL, NULL); } else if (event == MP_BLUETOOTH_IRQ_GATTS_INDICATE_DONE) { // conn_handle, value_handle, status ringbuf_extract(&o->ringbuf, data_tuple, 2, 1, NULL, 0, NULL, NULL); } else if (event == MP_BLUETOOTH_IRQ_MTU_EXCHANGED) { // conn_handle, mtu ringbuf_extract(&o->ringbuf, data_tuple, 2, 0, NULL, 0, NULL, NULL); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE } else if (event == MP_BLUETOOTH_IRQ_SCAN_RESULT) { // addr_type, addr, adv_type, rssi, adv_data ringbuf_extract(&o->ringbuf, data_tuple, 0, 1, &o->irq_data_addr, 2, NULL, &o->irq_data_data); } else if (event == MP_BLUETOOTH_IRQ_SCAN_DONE) { // No params required. data_tuple->len = 0; #endif #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT } else if (event == MP_BLUETOOTH_IRQ_GATTC_SERVICE_RESULT) { // conn_handle, start_handle, end_handle, uuid ringbuf_extract(&o->ringbuf, data_tuple, 3, 0, NULL, 0, &o->irq_data_uuid, NULL); } else if (event == MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_RESULT) { // conn_handle, def_handle, value_handle, properties, uuid ringbuf_extract(&o->ringbuf, data_tuple, 3, 1, NULL, 0, &o->irq_data_uuid, NULL); } else if (event == MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_RESULT) { // conn_handle, handle, uuid ringbuf_extract(&o->ringbuf, data_tuple, 2, 0, NULL, 0, &o->irq_data_uuid, NULL); } else if (event == MP_BLUETOOTH_IRQ_GATTC_SERVICE_DONE || event == MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_DONE || event == MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_DONE) { // conn_handle, status ringbuf_extract(&o->ringbuf, data_tuple, 2, 0, NULL, 0, NULL, NULL); } else if (event == MP_BLUETOOTH_IRQ_GATTC_READ_RESULT || event == MP_BLUETOOTH_IRQ_GATTC_NOTIFY || event == MP_BLUETOOTH_IRQ_GATTC_INDICATE) { // conn_handle, value_handle, data ringbuf_extract(&o->ringbuf, data_tuple, 2, 0, NULL, 0, NULL, &o->irq_data_data); } else if (event == MP_BLUETOOTH_IRQ_GATTC_READ_DONE || event == MP_BLUETOOTH_IRQ_GATTC_WRITE_DONE) { // conn_handle, value_handle, status ringbuf_extract(&o->ringbuf, data_tuple, 3, 0, NULL, 0, NULL, NULL); #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT } MICROPY_PY_BLUETOOTH_EXIT mp_call_function_2(handler, MP_OBJ_NEW_SMALL_INT(event), MP_OBJ_FROM_PTR(data_tuple)); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(bluetooth_ble_invoke_irq_obj, bluetooth_ble_invoke_irq); #endif // !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS // ---------------------------------------------------------------------------- // Port API // ---------------------------------------------------------------------------- #if MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS STATIC mp_obj_t invoke_irq_handler(uint16_t event, const mp_int_t *numeric, size_t n_unsigned, size_t n_signed, const uint8_t *addr, const mp_obj_bluetooth_uuid_t *uuid, const uint8_t **data, size_t *data_len, size_t n_data) { mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (o->irq_handler == mp_const_none) { return mp_const_none; } mp_obj_array_t mv_addr; mp_obj_array_t mv_data[2]; assert(n_data <= 2); mp_obj_tuple_t *data_tuple = mp_local_alloc(sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) * MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_TUPLE_LEN); data_tuple->base.type = &mp_type_tuple; data_tuple->len = 0; for (size_t i = 0; i < n_unsigned; ++i) { data_tuple->items[data_tuple->len++] = MP_OBJ_NEW_SMALL_INT(numeric[i]); } if (addr) { mp_obj_memoryview_init(&mv_addr, 'B', 0, 6, (void *)addr); data_tuple->items[data_tuple->len++] = MP_OBJ_FROM_PTR(&mv_addr); } for (size_t i = 0; i < n_signed; ++i) { data_tuple->items[data_tuple->len++] = MP_OBJ_NEW_SMALL_INT(numeric[i + n_unsigned]); } #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE if (uuid) { data_tuple->items[data_tuple->len++] = MP_OBJ_FROM_PTR(uuid); } #endif for (size_t i = 0; i < n_data; ++i) { if (data[i]) { mp_obj_memoryview_init(&mv_data[i], 'B', 0, data_len[i], (void *)data[i]); data_tuple->items[data_tuple->len++] = MP_OBJ_FROM_PTR(&mv_data[i]); } else { data_tuple->items[data_tuple->len++] = mp_const_none; } } assert(data_tuple->len <= MICROPY_PY_BLUETOOTH_MAX_EVENT_DATA_TUPLE_LEN); mp_obj_t result = mp_call_function_2(o->irq_handler, MP_OBJ_NEW_SMALL_INT(event), MP_OBJ_FROM_PTR(data_tuple)); mp_local_free(data_tuple); return result; } #define NULL_NUMERIC NULL #define NULL_ADDR NULL #define NULL_UUID NULL #define NULL_DATA NULL #define NULL_DATA_LEN NULL void mp_bluetooth_gap_on_connected_disconnected(uint8_t event, uint16_t conn_handle, uint8_t addr_type, const uint8_t *addr) { mp_int_t args[] = {conn_handle, addr_type}; invoke_irq_handler(event, args, 2, 0, addr, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gap_on_connection_update(uint16_t conn_handle, uint16_t conn_interval, uint16_t conn_latency, uint16_t supervision_timeout, uint16_t status) { mp_int_t args[] = {conn_handle, conn_interval, conn_latency, supervision_timeout, status}; invoke_irq_handler(MP_BLUETOOTH_IRQ_CONNECTION_UPDATE, args, 5, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING void mp_bluetooth_gatts_on_encryption_update(uint16_t conn_handle, bool encrypted, bool authenticated, bool bonded, uint8_t key_size) { mp_int_t args[] = {conn_handle, encrypted, authenticated, bonded, key_size}; invoke_irq_handler(MP_BLUETOOTH_IRQ_ENCRYPTION_UPDATE, args, 5, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } bool mp_bluetooth_gap_on_get_secret(uint8_t type, uint8_t index, const uint8_t *key, size_t key_len, const uint8_t **value, size_t *value_len) { mp_int_t args[] = {type, index}; mp_obj_t result = invoke_irq_handler(MP_BLUETOOTH_IRQ_GET_SECRET, args, 2, 0, NULL_ADDR, NULL_UUID, &key, &key_len, 1); if (result == mp_const_none) { return false; } mp_buffer_info_t bufinfo; mp_get_buffer_raise(result, &bufinfo, MP_BUFFER_READ); *value = bufinfo.buf; *value_len = bufinfo.len; return true; } bool mp_bluetooth_gap_on_set_secret(uint8_t type, const uint8_t *key, size_t key_len, const uint8_t *value, size_t value_len) { mp_int_t args[] = { type }; const uint8_t *data[] = {key, value}; size_t data_len[] = {key_len, value_len}; mp_obj_t result = invoke_irq_handler(MP_BLUETOOTH_IRQ_SET_SECRET, args, 1, 0, NULL_ADDR, NULL_UUID, data, data_len, 2); return mp_obj_is_true(result); } void mp_bluetooth_gap_on_passkey_action(uint16_t conn_handle, uint8_t action, mp_int_t passkey) { mp_int_t args[] = { conn_handle, action, passkey }; invoke_irq_handler(MP_BLUETOOTH_IRQ_PASSKEY_ACTION, args, 2, 1, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING void mp_bluetooth_gatts_on_write(uint16_t conn_handle, uint16_t value_handle) { mp_int_t args[] = {conn_handle, value_handle}; invoke_irq_handler(MP_BLUETOOTH_IRQ_GATTS_WRITE, args, 2, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gatts_on_indicate_complete(uint16_t conn_handle, uint16_t value_handle, uint8_t status) { mp_int_t args[] = {conn_handle, value_handle, status}; invoke_irq_handler(MP_BLUETOOTH_IRQ_GATTS_INDICATE_DONE, args, 3, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } mp_int_t mp_bluetooth_gatts_on_read_request(uint16_t conn_handle, uint16_t value_handle) { mp_int_t args[] = {conn_handle, value_handle}; mp_obj_t result = invoke_irq_handler(MP_BLUETOOTH_IRQ_GATTS_READ_REQUEST, args, 2, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); // Return non-zero from IRQ handler to fail the read. mp_int_t ret = 0; mp_obj_get_int_maybe(result, &ret); return ret; } void mp_bluetooth_gatts_on_mtu_exchanged(uint16_t conn_handle, uint16_t value) { mp_int_t args[] = {conn_handle, value}; invoke_irq_handler(MP_BLUETOOTH_IRQ_MTU_EXCHANGED, args, 2, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS mp_int_t mp_bluetooth_on_l2cap_accept(uint16_t conn_handle, uint16_t cid, uint16_t psm, uint16_t our_mtu, uint16_t peer_mtu) { mp_int_t args[] = {conn_handle, cid, psm, our_mtu, peer_mtu}; mp_obj_t result = invoke_irq_handler(MP_BLUETOOTH_IRQ_L2CAP_ACCEPT, args, 5, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); // Return non-zero from IRQ handler to fail the accept. mp_int_t ret = 0; mp_obj_get_int_maybe(result, &ret); return ret; } void mp_bluetooth_on_l2cap_connect(uint16_t conn_handle, uint16_t cid, uint16_t psm, uint16_t our_mtu, uint16_t peer_mtu) { mp_int_t args[] = {conn_handle, cid, psm, our_mtu, peer_mtu}; invoke_irq_handler(MP_BLUETOOTH_IRQ_L2CAP_CONNECT, args, 5, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_on_l2cap_disconnect(uint16_t conn_handle, uint16_t cid, uint16_t psm, uint16_t status) { mp_int_t args[] = {conn_handle, cid, psm, status}; invoke_irq_handler(MP_BLUETOOTH_IRQ_L2CAP_DISCONNECT, args, 4, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_on_l2cap_send_ready(uint16_t conn_handle, uint16_t cid, uint8_t status) { mp_int_t args[] = {conn_handle, cid, status}; invoke_irq_handler(MP_BLUETOOTH_IRQ_L2CAP_SEND_READY, args, 3, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_on_l2cap_recv(uint16_t conn_handle, uint16_t cid) { mp_int_t args[] = {conn_handle, cid}; invoke_irq_handler(MP_BLUETOOTH_IRQ_L2CAP_RECV, args, 2, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE void mp_bluetooth_gap_on_scan_complete(void) { invoke_irq_handler(MP_BLUETOOTH_IRQ_SCAN_DONE, NULL_NUMERIC, 0, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gap_on_scan_result(uint8_t addr_type, const uint8_t *addr, uint8_t adv_type, const int8_t rssi, const uint8_t *data, size_t data_len) { mp_int_t args[] = {addr_type, adv_type, rssi}; invoke_irq_handler(MP_BLUETOOTH_IRQ_SCAN_RESULT, args, 1, 2, addr, NULL_UUID, &data, &data_len, 1); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT void mp_bluetooth_gattc_on_primary_service_result(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle, mp_obj_bluetooth_uuid_t *service_uuid) { mp_int_t args[] = {conn_handle, start_handle, end_handle}; invoke_irq_handler(MP_BLUETOOTH_IRQ_GATTC_SERVICE_RESULT, args, 3, 0, NULL_ADDR, service_uuid, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gattc_on_characteristic_result(uint16_t conn_handle, uint16_t def_handle, uint16_t value_handle, uint8_t properties, mp_obj_bluetooth_uuid_t *characteristic_uuid) { mp_int_t args[] = {conn_handle, def_handle, value_handle, properties}; invoke_irq_handler(MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_RESULT, args, 4, 0, NULL_ADDR, characteristic_uuid, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gattc_on_descriptor_result(uint16_t conn_handle, uint16_t handle, mp_obj_bluetooth_uuid_t *descriptor_uuid) { mp_int_t args[] = {conn_handle, handle}; invoke_irq_handler(MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_RESULT, args, 2, 0, NULL_ADDR, descriptor_uuid, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gattc_on_discover_complete(uint8_t event, uint16_t conn_handle, uint16_t status) { mp_int_t args[] = {conn_handle, status}; invoke_irq_handler(event, args, 2, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } void mp_bluetooth_gattc_on_data_available(uint8_t event, uint16_t conn_handle, uint16_t value_handle, const uint8_t **data, uint16_t *data_len, size_t num) { const uint8_t *combined_data; size_t total_len; if (num > 1) { // Fragmented buffer, need to combine into a new heap-allocated buffer // in order to pass to Python. total_len = 0; for (size_t i = 0; i < num; ++i) { total_len += data_len[i]; } uint8_t *buf = m_new(uint8_t, total_len); uint8_t *p = buf; for (size_t i = 0; i < num; ++i) { memcpy(p, data[i], data_len[i]); p += data_len[i]; } combined_data = buf; } else { // Single buffer, use directly. combined_data = *data; total_len = *data_len; } mp_int_t args[] = {conn_handle, value_handle}; invoke_irq_handler(event, args, 2, 0, NULL_ADDR, NULL_UUID, &combined_data, &total_len, 1); if (num > 1) { m_del(uint8_t, (uint8_t *)combined_data, total_len); } } void mp_bluetooth_gattc_on_read_write_status(uint8_t event, uint16_t conn_handle, uint16_t value_handle, uint16_t status) { mp_int_t args[] = {conn_handle, value_handle, status}; invoke_irq_handler(event, args, 3, 0, NULL_ADDR, NULL_UUID, NULL_DATA, NULL_DATA_LEN, 0); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT #else // !MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS // Callbacks are called in interrupt context (i.e. can't allocate), so we need to push the data // into the ringbuf and schedule the callback via mp_sched_schedule. STATIC bool enqueue_irq(mp_obj_bluetooth_ble_t *o, size_t len, uint8_t event) { if (!o || o->irq_handler == mp_const_none) { return false; } // Check if there is enough room for <event-type><payload>. if (ringbuf_free(&o->ringbuf) < len + 1) { // Ringbuffer doesn't have room (and is therefore non-empty). // If this is another scan result, or the front of the ringbuffer isn't a scan result, then nothing to do. if (event == MP_BLUETOOTH_IRQ_SCAN_RESULT || ringbuf_peek(&o->ringbuf) != MP_BLUETOOTH_IRQ_SCAN_RESULT) { return false; } // Front of the queue is a scan result, remove it. // event, addr_type, addr, adv_type, rssi int n = 1 + 1 + 6 + 1 + 1; for (int i = 0; i < n; ++i) { ringbuf_get(&o->ringbuf); } // adv_data n = ringbuf_get(&o->ringbuf); for (int i = 0; i < n; ++i) { ringbuf_get(&o->ringbuf); } } // Append this event, the caller will then append the arguments. ringbuf_put(&o->ringbuf, event); return true; } // Must hold the atomic section before calling this (MICROPY_PY_BLUETOOTH_ENTER). STATIC void schedule_ringbuf(mp_uint_t atomic_state) { mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (!o->irq_scheduled) { o->irq_scheduled = true; MICROPY_PY_BLUETOOTH_EXIT mp_sched_schedule(MP_OBJ_FROM_PTR(&bluetooth_ble_invoke_irq_obj), mp_const_none); } else { MICROPY_PY_BLUETOOTH_EXIT } } void mp_bluetooth_gap_on_connected_disconnected(uint8_t event, uint16_t conn_handle, uint8_t addr_type, const uint8_t *addr) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 1 + 6, event)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put(&o->ringbuf, addr_type); for (int i = 0; i < 6; ++i) { ringbuf_put(&o->ringbuf, addr[i]); } } schedule_ringbuf(atomic_state); } void mp_bluetooth_gap_on_connection_update(uint16_t conn_handle, uint16_t conn_interval, uint16_t conn_latency, uint16_t supervision_timeout, uint16_t status) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2 + 2 + 2 + 2, MP_BLUETOOTH_IRQ_CONNECTION_UPDATE)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, conn_interval); ringbuf_put16(&o->ringbuf, conn_latency); ringbuf_put16(&o->ringbuf, supervision_timeout); ringbuf_put16(&o->ringbuf, status); } schedule_ringbuf(atomic_state); } void mp_bluetooth_gatts_on_write(uint16_t conn_handle, uint16_t value_handle) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2, MP_BLUETOOTH_IRQ_GATTS_WRITE)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, value_handle); } schedule_ringbuf(atomic_state); } void mp_bluetooth_gatts_on_indicate_complete(uint16_t conn_handle, uint16_t value_handle, uint8_t status) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2 + 1, MP_BLUETOOTH_IRQ_GATTS_INDICATE_DONE)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, value_handle); ringbuf_put(&o->ringbuf, status); } schedule_ringbuf(atomic_state); } mp_int_t mp_bluetooth_gatts_on_read_request(uint16_t conn_handle, uint16_t value_handle) { (void)conn_handle; (void)value_handle; // This must be handled synchronously and therefore cannot implemented with the ringbuffer. return MP_BLUETOOTH_GATTS_NO_ERROR; } void mp_bluetooth_gatts_on_mtu_exchanged(uint16_t conn_handle, uint16_t value) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2, MP_BLUETOOTH_IRQ_MTU_EXCHANGED)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, value); } schedule_ringbuf(atomic_state); } #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE void mp_bluetooth_gap_on_scan_complete(void) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 0, MP_BLUETOOTH_IRQ_SCAN_DONE)) { } schedule_ringbuf(atomic_state); } void mp_bluetooth_gap_on_scan_result(uint8_t addr_type, const uint8_t *addr, uint8_t adv_type, const int8_t rssi, const uint8_t *data, size_t data_len) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); data_len = MIN(o->irq_data_data_alloc, data_len); if (enqueue_irq(o, 1 + 6 + 1 + 1 + 2 + data_len, MP_BLUETOOTH_IRQ_SCAN_RESULT)) { ringbuf_put(&o->ringbuf, addr_type); for (int i = 0; i < 6; ++i) { ringbuf_put(&o->ringbuf, addr[i]); } // The adv_type will get extracted as an int8_t but that's ok because valid values are 0x00-0x04. ringbuf_put(&o->ringbuf, adv_type); // Note conversion of int8_t rssi to uint8_t. Must un-convert on the way out. ringbuf_put(&o->ringbuf, (uint8_t)rssi); // Length field is 16-bit. data_len = MIN(UINT16_MAX, data_len); ringbuf_put16(&o->ringbuf, data_len); for (size_t i = 0; i < data_len; ++i) { ringbuf_put(&o->ringbuf, data[i]); } } schedule_ringbuf(atomic_state); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT void mp_bluetooth_gattc_on_primary_service_result(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle, mp_obj_bluetooth_uuid_t *service_uuid) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2 + 2 + 1 + service_uuid->type, MP_BLUETOOTH_IRQ_GATTC_SERVICE_RESULT)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, start_handle); ringbuf_put16(&o->ringbuf, end_handle); ringbuf_put_uuid(&o->ringbuf, service_uuid); } schedule_ringbuf(atomic_state); } void mp_bluetooth_gattc_on_characteristic_result(uint16_t conn_handle, uint16_t def_handle, uint16_t value_handle, uint8_t properties, mp_obj_bluetooth_uuid_t *characteristic_uuid) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2 + 2 + 1 + characteristic_uuid->type, MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_RESULT)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, def_handle); ringbuf_put16(&o->ringbuf, value_handle); ringbuf_put(&o->ringbuf, properties); ringbuf_put_uuid(&o->ringbuf, characteristic_uuid); } schedule_ringbuf(atomic_state); } void mp_bluetooth_gattc_on_descriptor_result(uint16_t conn_handle, uint16_t handle, mp_obj_bluetooth_uuid_t *descriptor_uuid) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2 + 1 + descriptor_uuid->type, MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_RESULT)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, handle); ringbuf_put_uuid(&o->ringbuf, descriptor_uuid); } schedule_ringbuf(atomic_state); } void mp_bluetooth_gattc_on_discover_complete(uint8_t event, uint16_t conn_handle, uint16_t status) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2, event)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, status); } schedule_ringbuf(atomic_state); } void mp_bluetooth_gattc_on_data_available(uint8_t event, uint16_t conn_handle, uint16_t value_handle, const uint8_t **data, uint16_t *data_len, size_t num) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); // Get the total length of the fragmented buffers. uint16_t total_len = 0; for (size_t i = 0; i < num; ++i) { total_len += data_len[i]; } // Truncate the data at what we'll be able to pass to Python. total_len = MIN(o->irq_data_data_alloc, total_len); if (enqueue_irq(o, 2 + 2 + 2 + total_len, event)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, value_handle); ringbuf_put16(&o->ringbuf, total_len); // Copy total_len from the fragments to the ringbuffer. uint16_t copied_bytes = 0; for (size_t i = 0; i < num; ++i) { for (size_t j = 0; i < data_len[i] && copied_bytes < total_len; ++j) { ringbuf_put(&o->ringbuf, data[i][j]); ++copied_bytes; } } } schedule_ringbuf(atomic_state); } void mp_bluetooth_gattc_on_read_write_status(uint8_t event, uint16_t conn_handle, uint16_t value_handle, uint16_t status) { MICROPY_PY_BLUETOOTH_ENTER mp_obj_bluetooth_ble_t *o = MP_OBJ_TO_PTR(MP_STATE_VM(bluetooth)); if (enqueue_irq(o, 2 + 2 + 2, event)) { ringbuf_put16(&o->ringbuf, conn_handle); ringbuf_put16(&o->ringbuf, value_handle); ringbuf_put16(&o->ringbuf, status); } schedule_ringbuf(atomic_state); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT #endif // MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS // ---------------------------------------------------------------------------- // GATTS DB // ---------------------------------------------------------------------------- void mp_bluetooth_gatts_db_create_entry(mp_gatts_db_t db, uint16_t handle, size_t len) { mp_map_elem_t *elem = mp_map_lookup(db, MP_OBJ_NEW_SMALL_INT(handle), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); mp_bluetooth_gatts_db_entry_t *entry = m_new(mp_bluetooth_gatts_db_entry_t, 1); entry->data = m_new(uint8_t, len); entry->data_alloc = len; entry->data_len = 0; entry->append = false; elem->value = MP_OBJ_FROM_PTR(entry); } mp_bluetooth_gatts_db_entry_t *mp_bluetooth_gatts_db_lookup(mp_gatts_db_t db, uint16_t handle) { mp_map_elem_t *elem = mp_map_lookup(db, MP_OBJ_NEW_SMALL_INT(handle), MP_MAP_LOOKUP); if (!elem) { return NULL; } return MP_OBJ_TO_PTR(elem->value); } int mp_bluetooth_gatts_db_read(mp_gatts_db_t db, uint16_t handle, uint8_t **value, size_t *value_len) { MICROPY_PY_BLUETOOTH_ENTER mp_bluetooth_gatts_db_entry_t *entry = mp_bluetooth_gatts_db_lookup(db, handle); if (entry) { *value = entry->data; *value_len = entry->data_len; if (entry->append) { entry->data_len = 0; } } MICROPY_PY_BLUETOOTH_EXIT return entry ? 0 : MP_EINVAL; } int mp_bluetooth_gatts_db_write(mp_gatts_db_t db, uint16_t handle, const uint8_t *value, size_t value_len) { MICROPY_PY_BLUETOOTH_ENTER mp_bluetooth_gatts_db_entry_t *entry = mp_bluetooth_gatts_db_lookup(db, handle); if (entry) { if (value_len > entry->data_alloc) { uint8_t *data = m_new_maybe(uint8_t, value_len); if (data) { entry->data = data; entry->data_alloc = value_len; } else { MICROPY_PY_BLUETOOTH_EXIT return MP_ENOMEM; } } memcpy(entry->data, value, value_len); entry->data_len = value_len; } MICROPY_PY_BLUETOOTH_EXIT return entry ? 0 : MP_EINVAL; } int mp_bluetooth_gatts_db_resize(mp_gatts_db_t db, uint16_t handle, size_t len, bool append) { MICROPY_PY_BLUETOOTH_ENTER mp_bluetooth_gatts_db_entry_t *entry = mp_bluetooth_gatts_db_lookup(db, handle); if (entry) { uint8_t *data = m_renew_maybe(uint8_t, entry->data, entry->data_alloc, len, true); if (data) { entry->data = data; entry->data_alloc = len; entry->data_len = 0; entry->append = append; } else { MICROPY_PY_BLUETOOTH_EXIT return MP_ENOMEM; } } MICROPY_PY_BLUETOOTH_EXIT return entry ? 0 : MP_EINVAL; } #endif // MICROPY_PY_BLUETOOTH
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modbluetooth.c
C
apache-2.0
72,930
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018 Ayke van Laethem * Copyright (c) 2019-2020 Jim Mussared * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_MODBLUETOOTH_H #define MICROPY_INCLUDED_EXTMOD_MODBLUETOOTH_H #include <stdbool.h> #include "py/obj.h" #include "py/objlist.h" #include "py/ringbuf.h" // Port specific configuration. #ifndef MICROPY_PY_BLUETOOTH_RINGBUF_SIZE #define MICROPY_PY_BLUETOOTH_RINGBUF_SIZE (128) #endif #ifndef MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE #define MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE (0) #endif #ifndef MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT // Enable the client by default if we're enabling central mode. It's possible // to enable client without central though. #define MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT (MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE) #endif #ifndef MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS // This can be enabled if the BLE stack runs entirely in scheduler context // and therefore is able to call directly into the VM to run Python callbacks. #define MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS (0) #endif // A port can optionally enable support for L2CAP "Connection Oriented Channels". #ifndef MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS #define MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS (0) #endif // A port can optionally enable support for pairing and bonding. // Requires MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS. #ifndef MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING #define MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING (0) #endif // Optionally enable support for the `hci_cmd` function allowing // Python to directly low-level HCI commands. #ifndef MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD #define MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD (0) #endif // This is used to protect the ringbuffer. // A port may no-op this if MICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS is enabled. #ifndef MICROPY_PY_BLUETOOTH_ENTER #define MICROPY_PY_BLUETOOTH_ENTER mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); #define MICROPY_PY_BLUETOOTH_EXIT MICROPY_END_ATOMIC_SECTION(atomic_state); #endif // Common constants. #ifndef MP_BLUETOOTH_DEFAULT_ATTR_LEN #define MP_BLUETOOTH_DEFAULT_ATTR_LEN (20) #endif #define MP_BLUETOOTH_CCCB_LEN (2) // Advertisement packet lengths #define MP_BLUETOOTH_GAP_ADV_MAX_LEN (32) // Basic characteristic/descriptor flags. // These match the spec values for these flags so can be passed directly to the stack. #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_BROADCAST (0x0001) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ (0x0002) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE_NO_RESPONSE (0x0004) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE (0x0008) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_NOTIFY (0x0010) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_INDICATE (0x0020) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_AUTHENTICATED_SIGNED_WRITE (0x0040) // TODO: NimBLE and BlueKitchen disagree on this one. // #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_RELIABLE_WRITE (0x0080) // Extended flags for security and privacy. // These match NimBLE but might require mapping in the bindings for other stacks. #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_AUX_WRITE (0x0100) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ_ENCRYPTED (0x0200) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ_AUTHENTICATED (0x0400) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_READ_AUTHORIZED (0x0800) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE_ENCRYPTED (0x1000) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE_AUTHENTICATED (0x2000) #define MP_BLUETOOTH_CHARACTERISTIC_FLAG_WRITE_AUTHORIZED (0x4000) // Return values from _IRQ_GATTS_READ_REQUEST. #define MP_BLUETOOTH_GATTS_NO_ERROR (0x00) #define MP_BLUETOOTH_GATTS_ERROR_READ_NOT_PERMITTED (0x02) #define MP_BLUETOOTH_GATTS_ERROR_WRITE_NOT_PERMITTED (0x03) #define MP_BLUETOOTH_GATTS_ERROR_INSUFFICIENT_AUTHENTICATION (0x05) #define MP_BLUETOOTH_GATTS_ERROR_INSUFFICIENT_AUTHORIZATION (0x08) #define MP_BLUETOOTH_GATTS_ERROR_INSUFFICIENT_ENCRYPTION (0x0f) // For mp_bluetooth_gattc_write, the mode parameter #define MP_BLUETOOTH_WRITE_MODE_NO_RESPONSE (0) #define MP_BLUETOOTH_WRITE_MODE_WITH_RESPONSE (1) // Type value also doubles as length. #define MP_BLUETOOTH_UUID_TYPE_16 (2) #define MP_BLUETOOTH_UUID_TYPE_32 (4) #define MP_BLUETOOTH_UUID_TYPE_128 (16) // Event codes for the IRQ handler. #define MP_BLUETOOTH_IRQ_CENTRAL_CONNECT (1) #define MP_BLUETOOTH_IRQ_CENTRAL_DISCONNECT (2) #define MP_BLUETOOTH_IRQ_GATTS_WRITE (3) #define MP_BLUETOOTH_IRQ_GATTS_READ_REQUEST (4) #define MP_BLUETOOTH_IRQ_SCAN_RESULT (5) #define MP_BLUETOOTH_IRQ_SCAN_DONE (6) #define MP_BLUETOOTH_IRQ_PERIPHERAL_CONNECT (7) #define MP_BLUETOOTH_IRQ_PERIPHERAL_DISCONNECT (8) #define MP_BLUETOOTH_IRQ_GATTC_SERVICE_RESULT (9) #define MP_BLUETOOTH_IRQ_GATTC_SERVICE_DONE (10) #define MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_RESULT (11) #define MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_DONE (12) #define MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_RESULT (13) #define MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_DONE (14) #define MP_BLUETOOTH_IRQ_GATTC_READ_RESULT (15) #define MP_BLUETOOTH_IRQ_GATTC_READ_DONE (16) #define MP_BLUETOOTH_IRQ_GATTC_WRITE_DONE (17) #define MP_BLUETOOTH_IRQ_GATTC_NOTIFY (18) #define MP_BLUETOOTH_IRQ_GATTC_INDICATE (19) #define MP_BLUETOOTH_IRQ_GATTS_INDICATE_DONE (20) #define MP_BLUETOOTH_IRQ_MTU_EXCHANGED (21) #define MP_BLUETOOTH_IRQ_L2CAP_ACCEPT (22) #define MP_BLUETOOTH_IRQ_L2CAP_CONNECT (23) #define MP_BLUETOOTH_IRQ_L2CAP_DISCONNECT (24) #define MP_BLUETOOTH_IRQ_L2CAP_RECV (25) #define MP_BLUETOOTH_IRQ_L2CAP_SEND_READY (26) #define MP_BLUETOOTH_IRQ_CONNECTION_UPDATE (27) #define MP_BLUETOOTH_IRQ_ENCRYPTION_UPDATE (28) #define MP_BLUETOOTH_IRQ_GET_SECRET (29) #define MP_BLUETOOTH_IRQ_SET_SECRET (30) #define MP_BLUETOOTH_IRQ_PASSKEY_ACTION (31) #define MP_BLUETOOTH_ADDRESS_MODE_PUBLIC (0) #define MP_BLUETOOTH_ADDRESS_MODE_RANDOM (1) #define MP_BLUETOOTH_ADDRESS_MODE_RPA (2) #define MP_BLUETOOTH_ADDRESS_MODE_NRPA (3) // These match the spec values, can be used directly by the stack. #define MP_BLUETOOTH_IO_CAPABILITY_DISPLAY_ONLY (0) #define MP_BLUETOOTH_IO_CAPABILITY_DISPLAY_YESNO (1) #define MP_BLUETOOTH_IO_CAPABILITY_KEYBOARD_ONLY (2) #define MP_BLUETOOTH_IO_CAPABILITY_NO_INPUT_OUTPUT (3) #define MP_BLUETOOTH_IO_CAPABILITY_KEYBOARD_DISPLAY (4) // These match NimBLE BLE_SM_IOACT_. #define MP_BLUETOOTH_PASSKEY_ACTION_NONE (0) #define MP_BLUETOOTH_PASSKEY_ACTION_INPUT (2) #define MP_BLUETOOTH_PASSKEY_ACTION_DISPLAY (3) #define MP_BLUETOOTH_PASSKEY_ACTION_NUMERIC_COMPARISON (4) // These match NimBLE BLE_SM_IOACT_. #define MP_BLUETOOTH_PASSKEY_ACTION_NONE (0) #define MP_BLUETOOTH_PASSKEY_ACTION_INPUT (2) #define MP_BLUETOOTH_PASSKEY_ACTION_DISPLAY (3) #define MP_BLUETOOTH_PASSKEY_ACTION_NUMERIC_COMPARISON (4) /* These aren't included in the module for space reasons, but can be used in your Python code if necessary. from micropython import const _IRQ_CENTRAL_CONNECT = const(1) _IRQ_CENTRAL_DISCONNECT = const(2) _IRQ_GATTS_WRITE = const(3) _IRQ_GATTS_READ_REQUEST = const(4) _IRQ_SCAN_RESULT = const(5) _IRQ_SCAN_DONE = const(6) _IRQ_PERIPHERAL_CONNECT = const(7) _IRQ_PERIPHERAL_DISCONNECT = const(8) _IRQ_GATTC_SERVICE_RESULT = const(9) _IRQ_GATTC_SERVICE_DONE = const(10) _IRQ_GATTC_CHARACTERISTIC_RESULT = const(11) _IRQ_GATTC_CHARACTERISTIC_DONE = const(12) _IRQ_GATTC_DESCRIPTOR_RESULT = const(13) _IRQ_GATTC_DESCRIPTOR_DONE = const(14) _IRQ_GATTC_READ_RESULT = const(15) _IRQ_GATTC_READ_DONE = const(16) _IRQ_GATTC_WRITE_DONE = const(17) _IRQ_GATTC_NOTIFY = const(18) _IRQ_GATTC_INDICATE = const(19) _IRQ_GATTS_INDICATE_DONE = const(20) _IRQ_MTU_EXCHANGED = const(21) _IRQ_L2CAP_ACCEPT = const(22) _IRQ_L2CAP_CONNECT = const(23) _IRQ_L2CAP_DISCONNECT = const(24) _IRQ_L2CAP_RECV = const(25) _IRQ_L2CAP_SEND_READY = const(26) _IRQ_CONNECTION_UPDATE = const(27) _IRQ_ENCRYPTION_UPDATE = const(28) _IRQ_GET_SECRET = const(29) _IRQ_SET_SECRET = const(30) _IRQ_PASSKEY_ACTION = const(31) _FLAG_BROADCAST = const(0x0001) _FLAG_READ = const(0x0002) _FLAG_WRITE_NO_RESPONSE = const(0x0004) _FLAG_WRITE = const(0x0008) _FLAG_NOTIFY = const(0x0010) _FLAG_INDICATE = const(0x0020) _FLAG_AUTHENTICATED_SIGNED_WRITE = const(0x0040) _FLAG_AUX_WRITE = const(0x0100) _FLAG_READ_ENCRYPTED = const(0x0200) _FLAG_READ_AUTHENTICATED = const(0x0400) _FLAG_READ_AUTHORIZED = const(0x0800) _FLAG_WRITE_ENCRYPTED = const(0x1000) _FLAG_WRITE_AUTHENTICATED = const(0x2000) _FLAG_WRITE_AUTHORIZED = const(0x4000) _GATTS_NO_ERROR = const(0x00) _GATTS_ERROR_READ_NOT_PERMITTED = const(0x02) _GATTS_ERROR_WRITE_NOT_PERMITTED = const(0x03) _GATTS_ERROR_INSUFFICIENT_AUTHENTICATION = const(0x05) _GATTS_ERROR_INSUFFICIENT_AUTHORIZATION = const(0x08) _GATTS_ERROR_INSUFFICIENT_ENCRYPTION = const(0x0f) _IO_CAPABILITY_DISPLAY_ONLY = const(0) _IO_CAPABILITY_DISPLAY_YESNO = const(1) _IO_CAPABILITY_KEYBOARD_ONLY = const(2) _IO_CAPABILITY_NO_INPUT_OUTPUT = const(3) _IO_CAPABILITY_KEYBOARD_DISPLAY = const(4) _PASSKEY_ACTION_NONE = const(0) _PASSKEY_ACTION_INPUT = const(2) _PASSKEY_ACTION_DISPLAY = const(3) _PASSKEY_ACTION_NUMERIC_COMPARISON = const(4) */ // bluetooth.UUID type. // Ports are expected to map this to their own internal UUID types. // Internally the UUID data is little-endian, but the user should only // ever see this if they use the buffer protocol, e.g. in order to // construct an advertising payload (which needs to be in LE). // Both the constructor and the print function work in BE. typedef struct { mp_obj_base_t base; uint8_t type; uint8_t data[16]; } mp_obj_bluetooth_uuid_t; extern const mp_obj_type_t mp_type_bluetooth_uuid; ////////////////////////////////////////////////////////////// // API implemented by ports (i.e. called from modbluetooth.c): // TODO: At the moment this only allows for a single `Bluetooth` instance to be created. // Ideally in the future we'd be able to have multiple instances or to select a specific BT driver or HCI UART. // So these global methods should be replaced with a struct of function pointers (like the machine.I2C implementations). // Any method returning an int returns errno on failure, otherwise zero. // Note: All methods dealing with addresses (as 6-byte uint8 pointers) are in big-endian format. // (i.e. the same way they would be printed on a device sticker or in a UI), so the user sees // addresses in a way that looks like what they'd expect. // This means that the lower level implementation will likely need to reorder them (e.g. Nimble // works in little-endian, as does BLE itself). // Enables the Bluetooth stack. int mp_bluetooth_init(void); // Disables the Bluetooth stack. Is a no-op when not enabled. void mp_bluetooth_deinit(void); // Returns true when the Bluetooth stack is active. bool mp_bluetooth_is_active(void); // Gets the current address of this device in big-endian format. void mp_bluetooth_get_current_address(uint8_t *addr_type, uint8_t *addr); // Sets the addressing mode to use. void mp_bluetooth_set_address_mode(uint8_t addr_mode); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // Set bonding flag in pairing requests (i.e. persist security keys). void mp_bluetooth_set_bonding(bool enabled); // Require MITM protection. void mp_bluetooth_set_mitm_protection(bool enabled); // Require LE Secure pairing (rather than Legacy Pairing) void mp_bluetooth_set_le_secure(bool enabled); // I/O capabilities for authentication (see MP_BLUETOOTH_IO_CAPABILITY_*). void mp_bluetooth_set_io_capability(uint8_t capability); #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // Get or set the GAP device name that will be used by service 0x1800, characteristic 0x2a00. size_t mp_bluetooth_gap_get_device_name(const uint8_t **buf); int mp_bluetooth_gap_set_device_name(const uint8_t *buf, size_t len); // Start advertisement. Will re-start advertisement when already enabled. // Returns errno on failure. int mp_bluetooth_gap_advertise_start(bool connectable, int32_t interval_us, const uint8_t *adv_data, size_t adv_data_len, const uint8_t *sr_data, size_t sr_data_len); // Stop advertisement. No-op when already stopped. void mp_bluetooth_gap_advertise_stop(void); // Start adding services. Must be called before mp_bluetooth_register_service. int mp_bluetooth_gatts_register_service_begin(bool append); // Add a service with the given list of characteristics to the queue to be registered. // The value_handles won't be valid until after mp_bluetooth_register_service_end is called. int mp_bluetooth_gatts_register_service(mp_obj_bluetooth_uuid_t *service_uuid, mp_obj_bluetooth_uuid_t **characteristic_uuids, uint16_t *characteristic_flags, mp_obj_bluetooth_uuid_t **descriptor_uuids, uint16_t *descriptor_flags, uint8_t *num_descriptors, uint16_t *handles, size_t num_characteristics); // Register any queued services. int mp_bluetooth_gatts_register_service_end(void); // Read the value from the local gatts db (likely this has been written by a central). int mp_bluetooth_gatts_read(uint16_t value_handle, uint8_t **value, size_t *value_len); // Write a value to the local gatts db (ready to be queried by a central). Optionally send notifications/indications. int mp_bluetooth_gatts_write(uint16_t value_handle, const uint8_t *value, size_t value_len, bool send_update); // Notify the central that it should do a read. int mp_bluetooth_gatts_notify(uint16_t conn_handle, uint16_t value_handle); // Notify the central, including a data payload. (Note: does not set the gatts db value). int mp_bluetooth_gatts_notify_send(uint16_t conn_handle, uint16_t value_handle, const uint8_t *value, size_t value_len); // Indicate the central. int mp_bluetooth_gatts_indicate(uint16_t conn_handle, uint16_t value_handle); // Resize and enable/disable append-mode on a value. // Append-mode means that remote writes will append and local reads will clear after reading. int mp_bluetooth_gatts_set_buffer(uint16_t value_handle, size_t len, bool append); // Disconnect from a central or peripheral. int mp_bluetooth_gap_disconnect(uint16_t conn_handle); // Set/get the MTU that we will respond to a MTU exchange with. int mp_bluetooth_get_preferred_mtu(void); int mp_bluetooth_set_preferred_mtu(uint16_t mtu); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // Initiate pairing on the specified connection. int mp_bluetooth_gap_pair(uint16_t conn_handle); // Respond to a pairing request. int mp_bluetooth_gap_passkey(uint16_t conn_handle, uint8_t action, mp_int_t passkey); #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE // Start a discovery (scan). Set duration to zero to run continuously. int mp_bluetooth_gap_scan_start(int32_t duration_ms, int32_t interval_us, int32_t window_us, bool active_scan); // Stop discovery (if currently active). int mp_bluetooth_gap_scan_stop(void); // Connect to a found peripheral. int mp_bluetooth_gap_peripheral_connect(uint8_t addr_type, const uint8_t *addr, int32_t duration_ms); #endif #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT // Find all primary services on the connected peripheral. int mp_bluetooth_gattc_discover_primary_services(uint16_t conn_handle, const mp_obj_bluetooth_uuid_t *uuid); // Find all characteristics on the specified service on a connected peripheral. int mp_bluetooth_gattc_discover_characteristics(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle, const mp_obj_bluetooth_uuid_t *uuid); // Find all descriptors on the specified characteristic on a connected peripheral. int mp_bluetooth_gattc_discover_descriptors(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle); // Initiate read of a value from the remote peripheral. int mp_bluetooth_gattc_read(uint16_t conn_handle, uint16_t value_handle); // Write the value to the remote peripheral. int mp_bluetooth_gattc_write(uint16_t conn_handle, uint16_t value_handle, const uint8_t *value, size_t *value_len, unsigned int mode); // Initiate MTU exchange for a specific connection using the preferred MTU. int mp_bluetooth_gattc_exchange_mtu(uint16_t conn_handle); #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS int mp_bluetooth_l2cap_listen(uint16_t psm, uint16_t mtu); int mp_bluetooth_l2cap_connect(uint16_t conn_handle, uint16_t psm, uint16_t mtu); int mp_bluetooth_l2cap_disconnect(uint16_t conn_handle, uint16_t cid); int mp_bluetooth_l2cap_send(uint16_t conn_handle, uint16_t cid, const uint8_t *buf, size_t len, bool *stalled); int mp_bluetooth_l2cap_recvinto(uint16_t conn_handle, uint16_t cid, uint8_t *buf, size_t *len); #endif // MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS #if MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD int mp_bluetooth_hci_cmd(uint16_t ogf, uint16_t ocf, const uint8_t *req, size_t req_len, uint8_t *resp, size_t resp_len, uint8_t *status); #endif // MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD ///////////////////////////////////////////////////////////////////////////// // API implemented by modbluetooth (called by port-specific implementations): // Notify modbluetooth that a connection/disconnection event has occurred. void mp_bluetooth_gap_on_connected_disconnected(uint8_t event, uint16_t conn_handle, uint8_t addr_type, const uint8_t *addr); // Call this when any connection parameters have been changed. void mp_bluetooth_gap_on_connection_update(uint16_t conn_handle, uint16_t conn_interval, uint16_t conn_latency, uint16_t supervision_timeout, uint16_t status); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // Call this when any connection encryption has been changed (e.g. during pairing). void mp_bluetooth_gatts_on_encryption_update(uint16_t conn_handle, bool encrypted, bool authenticated, bool bonded, uint8_t key_size); // Call this when you need the application to manage persistent key data. // For get, if key is NULL, then the implementation must return the index'th matching key. Otherwise it should return a specific key. // For set, if value is NULL, then delete. // The "type" is stack-specific, but could also be used to implement versioning. bool mp_bluetooth_gap_on_get_secret(uint8_t type, uint8_t index, const uint8_t *key, size_t key_len, const uint8_t **value, size_t *value_len); bool mp_bluetooth_gap_on_set_secret(uint8_t type, const uint8_t *key, size_t key_len, const uint8_t *value, size_t value_len); // Call this when a passkey verification needs to be processed. void mp_bluetooth_gap_on_passkey_action(uint16_t conn_handle, uint8_t action, mp_int_t passkey); #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // Call this when a characteristic is written to. void mp_bluetooth_gatts_on_write(uint16_t conn_handle, uint16_t value_handle); // Call this when an acknowledgment is received for an indication. void mp_bluetooth_gatts_on_indicate_complete(uint16_t conn_handle, uint16_t value_handle, uint8_t status); // Call this when a characteristic is read from (giving the handler a chance to update the stored value). // Return 0 to allow the read, otherwise a non-zero rejection reason (see MP_BLUETOOTH_GATTS_ERROR_*). mp_int_t mp_bluetooth_gatts_on_read_request(uint16_t conn_handle, uint16_t value_handle); // Call this when an MTU exchange completes. void mp_bluetooth_gatts_on_mtu_exchanged(uint16_t conn_handle, uint16_t value); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE // Notify modbluetooth that scan has finished, either timeout, manually, or by some other action (e.g. connecting). void mp_bluetooth_gap_on_scan_complete(void); // Notify modbluetooth of a scan result. void mp_bluetooth_gap_on_scan_result(uint8_t addr_type, const uint8_t *addr, uint8_t adv_type, const int8_t rssi, const uint8_t *data, size_t data_len); #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT // Notify modbluetooth that a service was found (either by discover-all, or discover-by-uuid). void mp_bluetooth_gattc_on_primary_service_result(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle, mp_obj_bluetooth_uuid_t *service_uuid); // Notify modbluetooth that a characteristic was found (either by discover-all-on-service, or discover-by-uuid-on-service). void mp_bluetooth_gattc_on_characteristic_result(uint16_t conn_handle, uint16_t def_handle, uint16_t value_handle, uint8_t properties, mp_obj_bluetooth_uuid_t *characteristic_uuid); // Notify modbluetooth that a descriptor was found. void mp_bluetooth_gattc_on_descriptor_result(uint16_t conn_handle, uint16_t handle, mp_obj_bluetooth_uuid_t *descriptor_uuid); // Notify modbluetooth that service, characteristic or descriptor discovery has finished. void mp_bluetooth_gattc_on_discover_complete(uint8_t event, uint16_t conn_handle, uint16_t status); // Notify modbluetooth that a read has completed with data (or notify/indicate data available, use `event` to disambiguate). void mp_bluetooth_gattc_on_data_available(uint8_t event, uint16_t conn_handle, uint16_t value_handle, const uint8_t **data, uint16_t *data_len, size_t num); // Notify modbluetooth that a read or write operation has completed. void mp_bluetooth_gattc_on_read_write_status(uint8_t event, uint16_t conn_handle, uint16_t value_handle, uint16_t status); #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS mp_int_t mp_bluetooth_on_l2cap_accept(uint16_t conn_handle, uint16_t cid, uint16_t psm, uint16_t our_mtu, uint16_t peer_mtu); void mp_bluetooth_on_l2cap_connect(uint16_t conn_handle, uint16_t cid, uint16_t psm, uint16_t our_mtu, uint16_t peer_mtu); void mp_bluetooth_on_l2cap_disconnect(uint16_t conn_handle, uint16_t cid, uint16_t psm, uint16_t status); void mp_bluetooth_on_l2cap_send_ready(uint16_t conn_handle, uint16_t cid, uint8_t status); void mp_bluetooth_on_l2cap_recv(uint16_t conn_handle, uint16_t cid); #endif // MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS // For stacks that don't manage attribute value data (currently all of them), helpers // to store this in a map, keyed by value handle. typedef struct { // Pointer to heap-allocated data. uint8_t *data; // Allocated size of data. size_t data_alloc; // Current bytes in use. size_t data_len; // Whether new writes append or replace existing data (default false). bool append; } mp_bluetooth_gatts_db_entry_t; typedef mp_map_t *mp_gatts_db_t; STATIC inline void mp_bluetooth_gatts_db_create(mp_gatts_db_t *db) { *db = m_new(mp_map_t, 1); } STATIC inline void mp_bluetooth_gatts_db_reset(mp_gatts_db_t db) { mp_map_init(db, 0); } void mp_bluetooth_gatts_db_create_entry(mp_gatts_db_t db, uint16_t handle, size_t len); mp_bluetooth_gatts_db_entry_t *mp_bluetooth_gatts_db_lookup(mp_gatts_db_t db, uint16_t handle); int mp_bluetooth_gatts_db_read(mp_gatts_db_t db, uint16_t handle, uint8_t **value, size_t *value_len); int mp_bluetooth_gatts_db_write(mp_gatts_db_t db, uint16_t handle, const uint8_t *value, size_t value_len); int mp_bluetooth_gatts_db_resize(mp_gatts_db_t db, uint16_t handle, size_t len, bool append); #endif // MICROPY_INCLUDED_EXTMOD_MODBLUETOOTH_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modbluetooth.h
C
apache-2.0
24,915
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include <errno.h> // for declaration of global errno variable #include <fcntl.h> #include "py/runtime.h" #include "py/stream.h" #if MICROPY_PY_BTREE #include <db.h> #include <../../btree/btree.h> typedef struct _mp_obj_btree_t { mp_obj_base_t base; mp_obj_t stream; // retain a reference to prevent GC from reclaiming it DB *db; mp_obj_t start_key; mp_obj_t end_key; #define FLAG_END_KEY_INCL 1 #define FLAG_DESC 2 #define FLAG_ITER_TYPE_MASK 0xc0 #define FLAG_ITER_KEYS 0x40 #define FLAG_ITER_VALUES 0x80 #define FLAG_ITER_ITEMS 0xc0 byte flags; byte next_flags; } mp_obj_btree_t; #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_obj_type_t btree_type; #endif #define CHECK_ERROR(res) \ if (res == RET_ERROR) { \ mp_raise_OSError(errno); \ } void __dbpanic(DB *db) { mp_printf(&mp_plat_print, "__dbpanic(%p)\n", db); } STATIC mp_obj_btree_t *btree_new(DB *db, mp_obj_t stream) { mp_obj_btree_t *o = m_new_obj(mp_obj_btree_t); o->base.type = &btree_type; o->stream = stream; o->db = db; o->start_key = mp_const_none; o->end_key = mp_const_none; o->next_flags = 0; return o; } STATIC void btree_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_btree_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<btree %p>", self->db); } STATIC mp_obj_t btree_flush(mp_obj_t self_in) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(self_in); return MP_OBJ_NEW_SMALL_INT(__bt_sync(self->db, 0)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(btree_flush_obj, btree_flush); STATIC mp_obj_t btree_close(mp_obj_t self_in) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(self_in); return MP_OBJ_NEW_SMALL_INT(__bt_close(self->db)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(btree_close_obj, btree_close); STATIC mp_obj_t btree_put(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); DBT key, val; key.data = (void *)mp_obj_str_get_data(args[1], &key.size); val.data = (void *)mp_obj_str_get_data(args[2], &val.size); return MP_OBJ_NEW_SMALL_INT(__bt_put(self->db, &key, &val, 0)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put); STATIC mp_obj_t btree_get(size_t n_args, const mp_obj_t *args) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); DBT key, val; key.data = (void *)mp_obj_str_get_data(args[1], &key.size); int res = __bt_get(self->db, &key, &val, 0); if (res == RET_SPECIAL) { if (n_args > 2) { return args[2]; } else { return mp_const_none; } } CHECK_ERROR(res); return mp_obj_new_bytes(val.data, val.size); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_get_obj, 2, 3, btree_get); STATIC mp_obj_t btree_seq(size_t n_args, const mp_obj_t *args) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); int flags = MP_OBJ_SMALL_INT_VALUE(args[1]); DBT key, val; if (n_args > 2) { key.data = (void *)mp_obj_str_get_data(args[2], &key.size); } int res = __bt_seq(self->db, &key, &val, flags); CHECK_ERROR(res); if (res == RET_SPECIAL) { return mp_const_none; } mp_obj_t pair_o = mp_obj_new_tuple(2, NULL); mp_obj_tuple_t *pair = MP_OBJ_TO_PTR(pair_o); pair->items[0] = mp_obj_new_bytes(key.data, key.size); pair->items[1] = mp_obj_new_bytes(val.data, val.size); return pair_o; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_seq_obj, 2, 4, btree_seq); STATIC mp_obj_t btree_init_iter(size_t n_args, const mp_obj_t *args, byte type) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); self->next_flags = type; self->start_key = mp_const_none; self->end_key = mp_const_none; if (n_args > 1) { self->start_key = args[1]; if (n_args > 2) { self->end_key = args[2]; if (n_args > 3) { self->next_flags = type | MP_OBJ_SMALL_INT_VALUE(args[3]); } } } return args[0]; } STATIC mp_obj_t btree_keys(size_t n_args, const mp_obj_t *args) { return btree_init_iter(n_args, args, FLAG_ITER_KEYS); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_keys_obj, 1, 4, btree_keys); STATIC mp_obj_t btree_values(size_t n_args, const mp_obj_t *args) { return btree_init_iter(n_args, args, FLAG_ITER_VALUES); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_values_obj, 1, 4, btree_values); STATIC mp_obj_t btree_items(size_t n_args, const mp_obj_t *args) { return btree_init_iter(n_args, args, FLAG_ITER_ITEMS); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_items_obj, 1, 4, btree_items); STATIC mp_obj_t btree_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { (void)iter_buf; mp_obj_btree_t *self = MP_OBJ_TO_PTR(self_in); if (self->next_flags != 0) { // If we're called immediately after keys(), values(), or items(), // use their setup for iteration. self->flags = self->next_flags; self->next_flags = 0; } else { // Otherwise, iterate over all keys. self->flags = FLAG_ITER_KEYS; self->start_key = mp_const_none; self->end_key = mp_const_none; } return self_in; } STATIC mp_obj_t btree_iternext(mp_obj_t self_in) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(self_in); DBT key, val; int res; bool desc = self->flags & FLAG_DESC; if (self->start_key != MP_OBJ_NULL) { int flags = R_FIRST; if (self->start_key != mp_const_none) { key.data = (void *)mp_obj_str_get_data(self->start_key, &key.size); flags = R_CURSOR; } else if (desc) { flags = R_LAST; } res = __bt_seq(self->db, &key, &val, flags); self->start_key = MP_OBJ_NULL; } else { res = __bt_seq(self->db, &key, &val, desc ? R_PREV : R_NEXT); } if (res == RET_SPECIAL) { return MP_OBJ_STOP_ITERATION; } CHECK_ERROR(res); if (self->end_key != mp_const_none) { DBT end_key; end_key.data = (void *)mp_obj_str_get_data(self->end_key, &end_key.size); BTREE *t = self->db->internal; int cmp = t->bt_cmp(&key, &end_key); if (desc) { cmp = -cmp; } if (self->flags & FLAG_END_KEY_INCL) { cmp--; } if (cmp >= 0) { self->end_key = MP_OBJ_NULL; return MP_OBJ_STOP_ITERATION; } } switch (self->flags & FLAG_ITER_TYPE_MASK) { case FLAG_ITER_KEYS: return mp_obj_new_bytes(key.data, key.size); case FLAG_ITER_VALUES: return mp_obj_new_bytes(val.data, val.size); default: { mp_obj_t pair_o = mp_obj_new_tuple(2, NULL); mp_obj_tuple_t *pair = MP_OBJ_TO_PTR(pair_o); pair->items[0] = mp_obj_new_bytes(key.data, key.size); pair->items[1] = mp_obj_new_bytes(val.data, val.size); return pair_o; } } } STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(self_in); if (value == MP_OBJ_NULL) { // delete DBT key; key.data = (void *)mp_obj_str_get_data(index, &key.size); int res = __bt_delete(self->db, &key, 0); if (res == RET_SPECIAL) { mp_raise_type(&mp_type_KeyError); } CHECK_ERROR(res); return mp_const_none; } else if (value == MP_OBJ_SENTINEL) { // load DBT key, val; key.data = (void *)mp_obj_str_get_data(index, &key.size); int res = __bt_get(self->db, &key, &val, 0); if (res == RET_SPECIAL) { mp_raise_type(&mp_type_KeyError); } CHECK_ERROR(res); return mp_obj_new_bytes(val.data, val.size); } else { // store DBT key, val; key.data = (void *)mp_obj_str_get_data(index, &key.size); val.data = (void *)mp_obj_str_get_data(value, &val.size); int res = __bt_put(self->db, &key, &val, 0); CHECK_ERROR(res); return mp_const_none; } } STATIC mp_obj_t btree_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(lhs_in); switch (op) { case MP_BINARY_OP_CONTAINS: { DBT key, val; key.data = (void *)mp_obj_str_get_data(rhs_in, &key.size); int res = __bt_get(self->db, &key, &val, 0); CHECK_ERROR(res); return mp_obj_new_bool(res != RET_SPECIAL); } default: // op not supported return MP_OBJ_NULL; } } #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t btree_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&btree_close_obj) }, { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&btree_flush_obj) }, { MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&btree_get_obj) }, { MP_ROM_QSTR(MP_QSTR_put), MP_ROM_PTR(&btree_put_obj) }, { MP_ROM_QSTR(MP_QSTR_seq), MP_ROM_PTR(&btree_seq_obj) }, { MP_ROM_QSTR(MP_QSTR_keys), MP_ROM_PTR(&btree_keys_obj) }, { MP_ROM_QSTR(MP_QSTR_values), MP_ROM_PTR(&btree_values_obj) }, { MP_ROM_QSTR(MP_QSTR_items), MP_ROM_PTR(&btree_items_obj) }, }; STATIC MP_DEFINE_CONST_DICT(btree_locals_dict, btree_locals_dict_table); STATIC const mp_obj_type_t btree_type = { { &mp_type_type }, // Save on qstr's, reuse same as for module .name = MP_QSTR_btree, .print = btree_print, .getiter = btree_getiter, .iternext = btree_iternext, .binary_op = btree_binary_op, .subscr = btree_subscr, .locals_dict = (void *)&btree_locals_dict, }; #endif STATIC const FILEVTABLE btree_stream_fvtable = { mp_stream_posix_read, mp_stream_posix_write, mp_stream_posix_lseek, mp_stream_posix_fsync }; #if !MICROPY_ENABLE_DYNRUNTIME STATIC mp_obj_t mod_btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_flags, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_cachesize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_pagesize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_minkeypage, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, }; // Make sure we got a stream object mp_get_stream_raise(pos_args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); struct { mp_arg_val_t flags; mp_arg_val_t cachesize; mp_arg_val_t pagesize; mp_arg_val_t minkeypage; } args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); BTREEINFO openinfo = {0}; openinfo.flags = args.flags.u_int; openinfo.cachesize = args.cachesize.u_int; openinfo.psize = args.pagesize.u_int; openinfo.minkeypage = args.minkeypage.u_int; DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, /*dflags*/ 0); if (db == NULL) { mp_raise_OSError(errno); } return MP_OBJ_FROM_PTR(btree_new(db, pos_args[0])); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_btree_open_obj, 1, mod_btree_open); STATIC const mp_rom_map_elem_t mp_module_btree_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_btree) }, { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&mod_btree_open_obj) }, { MP_ROM_QSTR(MP_QSTR_INCL), MP_ROM_INT(FLAG_END_KEY_INCL) }, { MP_ROM_QSTR(MP_QSTR_DESC), MP_ROM_INT(FLAG_DESC) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_btree_globals, mp_module_btree_globals_table); const mp_obj_module_t mp_module_btree = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_btree_globals, }; #endif #endif // MICROPY_PY_BTREE
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modbtree.c
C
apache-2.0
13,136
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/objstr.h" #if MICROPY_PY_FRAMEBUF #include "font_petme128_8x8.h" typedef struct _mp_obj_framebuf_t { mp_obj_base_t base; mp_obj_t buf_obj; // need to store this to prevent GC from reclaiming buf void *buf; uint16_t width, height, stride; uint8_t format; } mp_obj_framebuf_t; typedef struct { char *font_path; FILE *fp; unsigned char font_height; unsigned char font_width; unsigned char is_cn; } font_t; // #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_obj_type_t mp_type_framebuf; // #endif typedef void (*setpixel_t)(const mp_obj_framebuf_t *, unsigned int, unsigned int, uint32_t); typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t *, unsigned int, unsigned int); typedef void (*fill_rect_t)(const mp_obj_framebuf_t *, unsigned int, unsigned int, unsigned int, unsigned int, uint32_t); typedef struct _mp_framebuf_p_t { setpixel_t setpixel; getpixel_t getpixel; fill_rect_t fill_rect; } mp_framebuf_p_t; // constants for formats #define FRAMEBUF_MVLSB (0) #define FRAMEBUF_RGB565 (1) #define FRAMEBUF_GS2_HMSB (5) #define FRAMEBUF_GS4_HMSB (2) #define FRAMEBUF_GS8 (6) #define FRAMEBUF_MHLSB (3) #define FRAMEBUF_MHMSB (4) #define FRAMEBUF_RGB888 (7) // constants for fonts // 支持中英文 12-32 #define FONT_ASC8_8 (808) #define FONT_ASC12_8 (1208) // #define FONT_PATH_ASC12_8 "/data/font/ASC12_8" #define FONT_ASC16_8 (1608) // #define FONT_PATH_ASC16_8 "/data/font/ASC16_8" #define FONT_ASC24_12 (2412) // #define FONT_PATH_ASC24_12 "/data/font/ASC24_12" #define FONT_ASC32_16 (3216) // #define FONT_PATH_ASC32_16 "/data/font/ASC32_16" // #define FONT_ASC48_24 (48) // #define FONT_PATH_ASC48_24 "./font/ASC48_24" #define FONT_HZK12 (1212) // #define FONT_PATH_HZK12 "/data/font/HZK12" #define FONT_HZK16 (1616) // #define FONT_PATH_HZK16 "/data/font/HZK16" #define FONT_HZK24 (2424) // #define FONT_PATH_HZK24 "/data/font/HZK24" #define FONT_HZK32 (3232) // #define FONT_PATH_HZK32 "/data/font/HZK32" static font_t ASC8_8 = {NULL, NULL, 8, 8, 0}; static font_t ASC12_8 = {NULL, NULL, 12, 8, 0}; static font_t ASC16_8 = {NULL, NULL, 16, 8, 0}; static font_t ASC24_12 = {NULL, NULL, 24, 12, 0}; static font_t ASC32_16 = {NULL, NULL, 32, 16, 0}; static font_t HZK12 = {NULL, NULL, 12, 12, 1}; static font_t HZK16 = {NULL, NULL, 16, 16, 1}; static font_t HZK24 = {NULL, NULL, 24, 24, 1}; static font_t HZK32 = {NULL, NULL, 32, 32, 1}; // Functions for MHLSB and MHMSB STATIC void mono_horiz_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { size_t index = (x + y * fb->stride) >> 3; unsigned int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07); ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); } STATIC uint32_t mono_horiz_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { size_t index = (x + y * fb->stride) >> 3; unsigned int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07); return (((uint8_t *)fb->buf)[index] >> (offset)) & 0x01; } STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { unsigned int reverse = fb->format == FRAMEBUF_MHMSB; unsigned int advance = fb->stride >> 3; while (w--) { uint8_t *b = &((uint8_t *)fb->buf)[(x >> 3) + y * advance]; unsigned int offset = reverse ? x & 7 : 7 - (x & 7); for (unsigned int hh = h; hh; --hh) { *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset); b += advance; } ++x; } } // Functions for MVLSB format STATIC void mvlsb_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { size_t index = (y >> 3) * fb->stride + x; uint8_t offset = y & 0x07; ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); } STATIC uint32_t mvlsb_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { return (((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01; } STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { while (h--) { uint8_t *b = &((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x]; uint8_t offset = y & 0x07; for (unsigned int ww = w; ww; --ww) { *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset); ++b; } ++y; } } // Functions for RGB565 format STATIC void rgb565_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { ((uint16_t *)fb->buf)[x + y * fb->stride] = col; } STATIC uint32_t rgb565_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { return ((uint16_t *)fb->buf)[x + y * fb->stride]; } STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { uint16_t *b = &((uint16_t *)fb->buf)[x + y * fb->stride]; while (h--) { for (unsigned int ww = w; ww; --ww) { *b++ = col; } b += fb->stride - w; } } // Functions for RGB888 format STATIC void rgb888_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { ((uint8_t *)fb->buf)[(x + y * fb->stride) * 3] = col >> 16; // r ((uint8_t *)fb->buf)[(x + y * fb->stride) * 3 + 1] = (col & 0x00ff00) >> 8; // g ((uint8_t *)fb->buf)[(x + y * fb->stride) * 3 + 2] = col & 0x0000ff; // b } STATIC uint32_t rgb888_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { return ((uint32_t *)fb->buf)[(x + y * fb->stride) * 3] >> 8; } STATIC void rgb888_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { for (unsigned int xx = x; xx < x + w; xx++) { for (unsigned int yy = y; yy < y + h; yy++) { rgb888_setpixel(fb, xx, yy, col); } } } // Functions for GS2_HMSB format STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2]; uint8_t shift = (x & 0x3) << 1; uint8_t mask = 0x3 << shift; uint8_t color = (col & 0x3) << shift; *pixel = color | (*pixel & (~mask)); } STATIC uint32_t gs2_hmsb_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { uint8_t pixel = ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2]; uint8_t shift = (x & 0x3) << 1; return (pixel >> shift) & 0x3; } STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { for (unsigned int xx = x; xx < x + w; xx++) { for (unsigned int yy = y; yy < y + h; yy++) { gs2_hmsb_setpixel(fb, xx, yy, col); } } } // Functions for GS4_HMSB format STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1]; if (x % 2) { *pixel = ((uint8_t)col & 0x0f) | (*pixel & 0xf0); } else { *pixel = ((uint8_t)col << 4) | (*pixel & 0x0f); } } STATIC uint32_t gs4_hmsb_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { if (x % 2) { return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f; } return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] >> 4; } STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { col &= 0x0f; uint8_t *pixel_pair = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1]; uint8_t col_shifted_left = col << 4; uint8_t col_pixel_pair = col_shifted_left | col; unsigned int pixel_count_till_next_line = (fb->stride - w) >> 1; bool odd_x = (x % 2 == 1); while (h--) { unsigned int ww = w; if (odd_x && ww > 0) { *pixel_pair = (*pixel_pair & 0xf0) | col; pixel_pair++; ww--; } memset(pixel_pair, col_pixel_pair, ww >> 1); pixel_pair += ww >> 1; if (ww % 2) { *pixel_pair = col_shifted_left | (*pixel_pair & 0x0f); if (!odd_x) { pixel_pair++; } } pixel_pair += pixel_count_till_next_line; } } // Functions for GS8 format STATIC void gs8_setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)]; *pixel = col & 0xff; } STATIC uint32_t gs8_getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { return ((uint8_t *)fb->buf)[(x + y * fb->stride)]; } STATIC void gs8_fill_rect(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, unsigned int w, unsigned int h, uint32_t col) { uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)]; while (h--) { memset(pixel, col, w); pixel += fb->stride; } } STATIC mp_framebuf_p_t formats[] = { [FRAMEBUF_MVLSB] = {mvlsb_setpixel, mvlsb_getpixel, mvlsb_fill_rect}, [FRAMEBUF_RGB565] = {rgb565_setpixel, rgb565_getpixel, rgb565_fill_rect}, [FRAMEBUF_GS2_HMSB] = {gs2_hmsb_setpixel, gs2_hmsb_getpixel, gs2_hmsb_fill_rect}, [FRAMEBUF_GS4_HMSB] = {gs4_hmsb_setpixel, gs4_hmsb_getpixel, gs4_hmsb_fill_rect}, [FRAMEBUF_GS8] = {gs8_setpixel, gs8_getpixel, gs8_fill_rect}, [FRAMEBUF_MHLSB] = {mono_horiz_setpixel, mono_horiz_getpixel, mono_horiz_fill_rect}, [FRAMEBUF_MHMSB] = {mono_horiz_setpixel, mono_horiz_getpixel, mono_horiz_fill_rect}, [FRAMEBUF_RGB888] = {rgb888_setpixel, rgb888_getpixel, rgb888_fill_rect}, }; static inline void setpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y, uint32_t col) { formats[fb->format].setpixel(fb, x, y, col); } static inline uint32_t getpixel(const mp_obj_framebuf_t *fb, unsigned int x, unsigned int y) { return formats[fb->format].getpixel(fb, x, y); } STATIC void fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { if (h < 1 || w < 1 || x + w <= 0 || y + h <= 0 || y >= fb->height || x >= fb->width) { // No operation needed. return; } // clip to the framebuffer int xend = MIN(fb->width, x + w); int yend = MIN(fb->height, y + h); x = MAX(x, 0); y = MAX(y, 0); formats[fb->format].fill_rect(fb, x, y, xend - x, yend - y, col); } STATIC mp_obj_t framebuf_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 4, 5, false); mp_obj_framebuf_t *o = m_new_obj(mp_obj_framebuf_t); o->base.type = type; o->buf_obj = args[0]; mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_WRITE); o->buf = bufinfo.buf; o->width = mp_obj_get_int(args[1]); o->height = mp_obj_get_int(args[2]); o->format = mp_obj_get_int(args[3]); if (n_args >= 5) { o->stride = mp_obj_get_int(args[4]); } else { o->stride = o->width; } switch (o->format) { case FRAMEBUF_MVLSB: case FRAMEBUF_RGB565: case FRAMEBUF_RGB888: break; case FRAMEBUF_MHLSB: case FRAMEBUF_MHMSB: o->stride = (o->stride + 7) & ~7; break; case FRAMEBUF_GS2_HMSB: o->stride = (o->stride + 3) & ~3; break; case FRAMEBUF_GS4_HMSB: o->stride = (o->stride + 1) & ~1; break; case FRAMEBUF_GS8: break; default: mp_raise_ValueError(MP_ERROR_TEXT("invalid format")); } return MP_OBJ_FROM_PTR(o); } STATIC mp_int_t framebuf_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { (void)flags; mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in); bufinfo->buf = self->buf; bufinfo->len = self->stride * self->height * (self->format == FRAMEBUF_RGB565 ? 2 : 1); bufinfo->typecode = 'B'; // view framebuf as bytes return 0; } STATIC mp_obj_t framebuf_fill(mp_obj_t self_in, mp_obj_t col_in) { mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t col = mp_obj_get_int(col_in); formats[self->format].fill_rect(self, 0, 0, self->width, self->height, col); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(framebuf_fill_obj, framebuf_fill); STATIC mp_obj_t framebuf_fill_rect(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t x = mp_obj_get_int(args[1]); mp_int_t y = mp_obj_get_int(args[2]); mp_int_t width = mp_obj_get_int(args[3]); mp_int_t height = mp_obj_get_int(args[4]); mp_int_t col = mp_obj_get_int(args[5]); fill_rect(self, x, y, width, height, col); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_fill_rect_obj, 6, 6, framebuf_fill_rect); STATIC mp_obj_t framebuf_pixel(size_t n_args, const mp_obj_t *args) { mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t x = mp_obj_get_int(args[1]); mp_int_t y = mp_obj_get_int(args[2]); if (0 <= x && x < self->width && 0 <= y && y < self->height) { if (n_args == 3) { // get return MP_OBJ_NEW_SMALL_INT(getpixel(self, x, y)); } else { // set setpixel(self, x, y, mp_obj_get_int(args[3])); } } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_pixel_obj, 3, 4, framebuf_pixel); STATIC mp_obj_t framebuf_hline(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t x = mp_obj_get_int(args[1]); mp_int_t y = mp_obj_get_int(args[2]); mp_int_t w = mp_obj_get_int(args[3]); mp_int_t col = mp_obj_get_int(args[4]); fill_rect(self, x, y, w, 1, col); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_hline_obj, 5, 5, framebuf_hline); STATIC mp_obj_t framebuf_vline(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t x = mp_obj_get_int(args[1]); mp_int_t y = mp_obj_get_int(args[2]); mp_int_t h = mp_obj_get_int(args[3]); mp_int_t col = mp_obj_get_int(args[4]); fill_rect(self, x, y, 1, h, col); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_vline_obj, 5, 5, framebuf_vline); STATIC mp_obj_t framebuf_rect(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t x = mp_obj_get_int(args[1]); mp_int_t y = mp_obj_get_int(args[2]); mp_int_t w = mp_obj_get_int(args[3]); mp_int_t h = mp_obj_get_int(args[4]); mp_int_t col = mp_obj_get_int(args[5]); fill_rect(self, x, y, w, 1, col); fill_rect(self, x, y + h - 1, w, 1, col); fill_rect(self, x, y, 1, h, col); fill_rect(self, x + w - 1, y, 1, h, col); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_rect_obj, 6, 6, framebuf_rect); STATIC mp_obj_t framebuf_line(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t x1 = mp_obj_get_int(args[1]); mp_int_t y1 = mp_obj_get_int(args[2]); mp_int_t x2 = mp_obj_get_int(args[3]); mp_int_t y2 = mp_obj_get_int(args[4]); mp_int_t col = mp_obj_get_int(args[5]); mp_int_t dx = x2 - x1; mp_int_t sx; if (dx > 0) { sx = 1; } else { dx = -dx; sx = -1; } mp_int_t dy = y2 - y1; mp_int_t sy; if (dy > 0) { sy = 1; } else { dy = -dy; sy = -1; } bool steep; if (dy > dx) { mp_int_t temp; temp = x1; x1 = y1; y1 = temp; temp = dx; dx = dy; dy = temp; temp = sx; sx = sy; sy = temp; steep = true; } else { steep = false; } mp_int_t e = 2 * dy - dx; for (mp_int_t i = 0; i < dx; ++i) { if (steep) { if (0 <= y1 && y1 < self->width && 0 <= x1 && x1 < self->height) { setpixel(self, y1, x1, col); } } else { if (0 <= x1 && x1 < self->width && 0 <= y1 && y1 < self->height) { setpixel(self, x1, y1, col); } } while (e >= 0) { y1 += sy; e -= 2 * dx; } x1 += sx; e += 2 * dy; } if (0 <= x2 && x2 < self->width && 0 <= y2 && y2 < self->height) { setpixel(self, x2, y2, col); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_line_obj, 6, 6, framebuf_line); STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) { mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(args[0]); mp_obj_t source_in = mp_obj_cast_to_native_base(args[1], MP_OBJ_FROM_PTR(&mp_type_framebuf)); if (source_in == MP_OBJ_NULL) { mp_raise_TypeError(NULL); } mp_obj_framebuf_t *source = MP_OBJ_TO_PTR(source_in); mp_int_t x = mp_obj_get_int(args[2]); mp_int_t y = mp_obj_get_int(args[3]); mp_int_t key = -1; if (n_args > 4) { key = mp_obj_get_int(args[4]); } if ( (x >= self->width) || (y >= self->height) || (-x >= source->width) || (-y >= source->height) ) { // Out of bounds, no-op. return mp_const_none; } // Clip. int x0 = MAX(0, x); int y0 = MAX(0, y); int x1 = MAX(0, -x); int y1 = MAX(0, -y); int x0end = MIN(self->width, x + source->width); int y0end = MIN(self->height, y + source->height); for (; y0 < y0end; ++y0) { int cx1 = x1; for (int cx0 = x0; cx0 < x0end; ++cx0) { uint32_t col = getpixel(source, cx1, y1); if (col != (uint32_t)key) { setpixel(self, cx0, y0, col); } ++cx1; } ++y1; } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(framebuf_blit_obj, 4, 5, framebuf_blit); STATIC mp_obj_t framebuf_scroll(mp_obj_t self_in, mp_obj_t xstep_in, mp_obj_t ystep_in) { mp_obj_framebuf_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t xstep = mp_obj_get_int(xstep_in); mp_int_t ystep = mp_obj_get_int(ystep_in); int sx, y, xend, yend, dx, dy; if (xstep < 0) { sx = 0; xend = self->width + xstep; dx = 1; } else { sx = self->width - 1; xend = xstep - 1; dx = -1; } if (ystep < 0) { y = 0; yend = self->height + ystep; dy = 1; } else { y = self->height - 1; yend = ystep - 1; dy = -1; } for (; y != yend; y += dy) { for (int x = sx; x != xend; x += dx) { setpixel(self, x, y, getpixel(self, x - xstep, y - ystep)); } } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(framebuf_scroll_obj, framebuf_scroll); STATIC unsigned char hz_get_mat(font_t *font, char *chr, unsigned char *mat) { unsigned char font_width; if (font == &HZK12) { font_width = 16; } else { font_width = font->font_width; } unsigned char size = font->font_height; unsigned char offset_step = (font->font_height * font_width / 8); unsigned long offset = 0; int t1 = (int) (*(chr) & 0xff); int t2 = (int) (*(chr + 1) & 0xff); if (t1 > 0xa0) { if (size == 40 || size == 48) { offset = ((t1 - 0xa1 - 0x0f) * 94 + (t2 - 0xa1)) * offset_step; } else if (size == 12 || size == 16 || size == 24 || size == 32) { offset = ((t1 - 0xa1) * 94 + (t2 - 0xa1)) * offset_step; } } else { offset = (t1 + 156 - 1) * offset_step; } if (font->fp == NULL) { font->fp = fopen(font->font_path , "rb"); if (font->fp == NULL) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("No font file %s"), font->font_path); memset(mat, 0, offset_step); return 0; } } fseek(font->fp, offset, SEEK_SET); fread(mat, offset_step, 1, font->fp); return 1; } STATIC void hz_print_mat(mp_obj_framebuf_t *self, mp_int_t x, mp_int_t y, mp_int_t col, font_t* font, unsigned char * mat, mp_int_t zoom) { char key[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; if (font->font_height == 40 || font->font_height == 48) { for (int i = 0; i < font->font_height; i++) { for (int j = 0; j < font->font_width; j++) { int index = i * font->font_width + j; int flag = mat[index / 8] & key[index % 8]; if (flag > 0) { for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom + r, y + i * zoom, col); for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom, y + i * zoom + r, col); } } } } } } else if (font->font_height == 16 || font->font_height == 24 || font->font_height == 32) { for (int i = 0; i < font->font_height; i++) { for (int j = 0; j < font->font_width; j++) { int index = j * font->font_width + i; int flag = mat[index / 8] & key[index % 8]; if (flag > 0) { for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom + r, y + i * zoom, col); for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom, y + i * zoom + r, col); } } } } } } else if (font->font_height == 12) { for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { int index = j * 16 + i; int flag = mat[index / 8] & key[index % 8]; if (flag > 0) { for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom + r, y + i * zoom, col); for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom, y + i * zoom + r, col); } } } } } } } STATIC unsigned char asc_get_mat(font_t *font, char *chr, unsigned char *mat) { int ascii = (int) (*chr); if (ascii > 127 || ascii < 32) { mp_raise_ValueError(MP_ERROR_TEXT("Input char is invaild")); return; } unsigned char offset_step = (font->font_width * font->font_height / 8); long offset = (ascii - 32) * offset_step; if (font->fp == NULL) { font->fp = fopen(font->font_path , "rb"); if (font->fp == NULL) { mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("error no font file %s"), font->font_path); memset(mat, 0, offset_step); return 0; } } fseek(font->fp, offset, SEEK_SET); fread(mat, offset_step, 1, font->fp); return 1; } STATIC void asc_print_mat(mp_obj_framebuf_t *self, mp_int_t x, mp_int_t y, mp_int_t col, font_t* font, unsigned char * mat, mp_int_t zoom) { char key[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01}; if (font->font_height == 12 || font->font_height == 48) { for (int i = 0; i < font->font_height; i++) { for (int j = 0; j < font->font_width; j++) { int index = i * font->font_width + j; int flag = mat[index / 8] & key[index % 8]; if (flag > 0) { for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom + r, y + i * zoom, col); for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom, y + i * zoom + r, col); } } } } } } else { for (int i = 0; i < font->font_height; i++) { for (int j = 0; j < font->font_width; j++) { int index = j * font->font_height + i; int flag = mat[index / 8] & key[index % 8]; if (flag > 0) { for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom + r, y + i * zoom, col); for (int r = 0; r < zoom; r++) { setpixel(self, x + j * zoom, y + i * zoom + r, col); } } } } } } } STATIC mp_obj_t framebuf_text_helper(mp_obj_framebuf_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { // extract arguments enum { ARG_s, ARG_x, ARG_y, ARG_c, ARG_size, ARG_zoom, ARG_space, ARG_font }; static const mp_arg_t allowed_args[] = { { MP_QSTR_s, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, { MP_QSTR_x, MP_ARG_INT | MP_ARG_REQUIRED, {.u_int = 0} }, { MP_QSTR_y, MP_ARG_INT | MP_ARG_REQUIRED, {.u_int = 0} }, { MP_QSTR_c, MP_ARG_INT, {.u_int = 1} }, { MP_QSTR_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = -1} }, { MP_QSTR_zoom, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1} }, { MP_QSTR_space, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_font, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = -1} }, }; // parse args mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_int_t x0 = args[ARG_x].u_int; mp_int_t y0 = args[ARG_y].u_int; mp_int_t font = args[ARG_font].u_int; mp_int_t size = args[ARG_size].u_int; mp_int_t col = args[ARG_c].u_int; mp_int_t space = args[ARG_space].u_int; mp_int_t zoom = args[ARG_zoom].u_int; mp_check_self(mp_obj_is_str_or_bytes(args[ARG_s].u_obj)); GET_STR_DATA_LEN(args[ARG_s].u_obj, str, str_len); if (str_len == 0) return mp_const_none; font_t *cn_font = NULL; font_t *en_font = NULL; if (font != -1) { switch (font) { case FONT_ASC8_8: cn_font = NULL; en_font = NULL; break; case FONT_ASC12_8: cn_font = NULL; en_font = &ASC12_8; break; case FONT_ASC16_8: cn_font = NULL; en_font = &ASC16_8; break; case FONT_ASC24_12: cn_font = NULL; en_font = &ASC24_12; break; case FONT_ASC32_16: cn_font = NULL; en_font = &ASC32_16; break; case FONT_HZK12: cn_font = &HZK12; en_font = NULL; break; case FONT_HZK16: cn_font = &HZK16; en_font = NULL; break; case FONT_HZK24: cn_font = &HZK24; en_font = NULL; break; case FONT_HZK32: cn_font = &HZK32; en_font = NULL; break; default: mp_raise_ValueError(MP_ERROR_TEXT("Wrong font")); break; } } if (size != -1) { switch (size) { case 8: cn_font = NULL; en_font = NULL; break; case 12: cn_font = &HZK12; en_font = &ASC12_8; break; case 16: cn_font = &HZK16; en_font = &ASC16_8; break; case 24: cn_font = &HZK24; en_font = &ASC24_12; break; case 32: cn_font = &HZK32; en_font = &ASC32_16; break; default: mp_raise_ValueError(MP_ERROR_TEXT("Wrong size. Only support 12 16 24 32")); break; } } if (font == -1 && size == -1) { cn_font = &HZK12; en_font = &ASC8_8; } int x = x0; // loop over chars for (int i = 0; *(str + i); ++i) { int chr = *(uint8_t *)(str + i); if (chr > 127) { // cn if (cn_font == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("Wrong chr. no cn font selected.")); // continue; } if (cn_font->font_path == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("Wrong chr. no cn font file not set. See set_font_path.")); } unsigned char *chr_data; if (cn_font == &HZK12) { chr_data = (unsigned char *)malloc(16 * cn_font->font_height / 8); } else { chr_data = (unsigned char *)malloc(cn_font->font_width * cn_font->font_height / 8); } if (hz_get_mat(cn_font, str + i, chr_data)) hz_print_mat(self, x, y0, col, cn_font, chr_data, zoom); ++i; x += cn_font->font_width * zoom + space; free(chr_data); } if (chr >= 32 && chr <= 127) { // en if (en_font == &ASC8_8) { // get char data const uint8_t *chr_data = &font_petme128_8x8[(chr - 32) * 8]; for (int j = 0; j < 8; j++, x++) { if (0 <= x && x < self->width) { uint vline_data = chr_data[j]; for (int y = y0; vline_data; vline_data >>= 1, y++) { if (vline_data & 1) { if (0 <= y && y < self->height) { setpixel(self, x, y, col); } } } } } x += space; } else { if (en_font == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("Wrong chr. no en font selected")); // continue; } if (en_font->font_path == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("Wrong chr. no en font file not set. See set_font_path.")); } unsigned char *chr_data = (unsigned char *)malloc(cn_font->font_width * cn_font->font_height / 8); if (asc_get_mat(en_font, str + i, chr_data)) asc_print_mat(self, x, y0, col, en_font, chr_data, zoom); x += en_font->font_width * zoom + space; free(chr_data); } } } if (cn_font && cn_font->fp) { fclose(cn_font->fp); cn_font->fp = NULL; } if (en_font && en_font->fp) { fclose(en_font->fp); en_font->fp = NULL; } return mp_const_none; } STATIC mp_obj_t framebuf_text(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { framebuf_text_helper(args[0], n_args - 1, args + 1, kw_args); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(framebuf_text_obj, 1, framebuf_text); font_t *get_font_obj(int font_tag) { switch (font_tag) { case FONT_ASC8_8: return &ASC8_8; break; case FONT_ASC12_8: return &ASC12_8; break; case FONT_ASC16_8: return &ASC16_8; break; case FONT_ASC24_12: return &ASC24_12; break; case FONT_ASC32_16: return &ASC32_16; break; case FONT_HZK12: return &HZK12; break; case FONT_HZK16: return &HZK16; break; case FONT_HZK24: return &HZK24; break; case FONT_HZK32: return &HZK32; break; default: return NULL; break; } } STATIC mp_obj_t framebuf_set_font_path(const mp_obj_t arg_font_tag, const mp_obj_t arg_font_path) { mp_int_t font_tag = mp_obj_get_int(arg_font_tag); const char *font_path = mp_obj_str_get_str(arg_font_path); font_t *font = get_font_obj(font_tag); if (font == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("Invalid font")); } if (font->font_path != NULL) { free(font->font_path); font->font_path = NULL; } font->font_path = malloc(strnlen(font_path, 128) + 1); memcpy(font->font_path, font_path, strnlen(font_path, 128) + 1); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(framebuf_set_font_path_obj, framebuf_set_font_path); // #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t framebuf_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_fill), MP_ROM_PTR(&framebuf_fill_obj) }, { MP_ROM_QSTR(MP_QSTR_fill_rect), MP_ROM_PTR(&framebuf_fill_rect_obj) }, { MP_ROM_QSTR(MP_QSTR_pixel), MP_ROM_PTR(&framebuf_pixel_obj) }, { MP_ROM_QSTR(MP_QSTR_hline), MP_ROM_PTR(&framebuf_hline_obj) }, { MP_ROM_QSTR(MP_QSTR_vline), MP_ROM_PTR(&framebuf_vline_obj) }, { MP_ROM_QSTR(MP_QSTR_rect), MP_ROM_PTR(&framebuf_rect_obj) }, { MP_ROM_QSTR(MP_QSTR_line), MP_ROM_PTR(&framebuf_line_obj) }, { MP_ROM_QSTR(MP_QSTR_blit), MP_ROM_PTR(&framebuf_blit_obj) }, { MP_ROM_QSTR(MP_QSTR_scroll), MP_ROM_PTR(&framebuf_scroll_obj) }, { MP_ROM_QSTR(MP_QSTR_text), MP_ROM_PTR(&framebuf_text_obj) }, }; STATIC MP_DEFINE_CONST_DICT(framebuf_locals_dict, framebuf_locals_dict_table); STATIC const mp_obj_type_t mp_type_framebuf = { { &mp_type_type }, .name = MP_QSTR_FrameBuffer, .make_new = framebuf_make_new, .buffer_p = { .get_buffer = framebuf_get_buffer }, .locals_dict = (mp_obj_dict_t *)&framebuf_locals_dict, }; // #endif // this factory function is provided for backwards compatibility with old FrameBuffer1 class STATIC mp_obj_t legacy_framebuffer1(size_t n_args, const mp_obj_t *args) { mp_obj_framebuf_t *o = m_new_obj(mp_obj_framebuf_t); o->base.type = &mp_type_framebuf; mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_WRITE); o->buf = bufinfo.buf; o->width = mp_obj_get_int(args[1]); o->height = mp_obj_get_int(args[2]); o->format = FRAMEBUF_MVLSB; if (n_args >= 4) { o->stride = mp_obj_get_int(args[3]); } else { o->stride = o->width; } return MP_OBJ_FROM_PTR(o); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(legacy_framebuffer1_obj, 3, 4, legacy_framebuffer1); // #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t framebuf_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_framebuf) }, { MP_ROM_QSTR(MP_QSTR_FrameBuffer), MP_ROM_PTR(&mp_type_framebuf) }, { MP_ROM_QSTR(MP_QSTR_FrameBuffer1), MP_ROM_PTR(&legacy_framebuffer1_obj) }, { MP_ROM_QSTR(MP_QSTR_set_font_path), MP_ROM_PTR(&framebuf_set_font_path_obj) }, { MP_ROM_QSTR(MP_QSTR_MVLSB), MP_ROM_INT(FRAMEBUF_MVLSB) }, { MP_ROM_QSTR(MP_QSTR_MONO_VLSB), MP_ROM_INT(FRAMEBUF_MVLSB) }, { MP_ROM_QSTR(MP_QSTR_RGB565), MP_ROM_INT(FRAMEBUF_RGB565) }, { MP_ROM_QSTR(MP_QSTR_RGB888), MP_ROM_INT(FRAMEBUF_RGB888) }, { MP_ROM_QSTR(MP_QSTR_GS2_HMSB), MP_ROM_INT(FRAMEBUF_GS2_HMSB) }, { MP_ROM_QSTR(MP_QSTR_GS4_HMSB), MP_ROM_INT(FRAMEBUF_GS4_HMSB) }, { MP_ROM_QSTR(MP_QSTR_GS8), MP_ROM_INT(FRAMEBUF_GS8) }, { MP_ROM_QSTR(MP_QSTR_MONO_HLSB), MP_ROM_INT(FRAMEBUF_MHLSB) }, { MP_ROM_QSTR(MP_QSTR_MONO_HMSB), MP_ROM_INT(FRAMEBUF_MHMSB) }, { MP_ROM_QSTR(MP_QSTR_FONT_ASC8_8), MP_ROM_INT(FONT_ASC8_8) }, { MP_ROM_QSTR(MP_QSTR_FONT_ASC12_8), MP_ROM_INT(FONT_ASC12_8) }, { MP_ROM_QSTR(MP_QSTR_FONT_ASC16_8), MP_ROM_INT(FONT_ASC16_8) }, { MP_ROM_QSTR(MP_QSTR_FONT_ASC24_12), MP_ROM_INT(FONT_ASC24_12) }, { MP_ROM_QSTR(MP_QSTR_FONT_ASC32_16), MP_ROM_INT(FONT_ASC32_16) }, { MP_ROM_QSTR(MP_QSTR_FONT_HZK12), MP_ROM_INT(FONT_HZK12) }, { MP_ROM_QSTR(MP_QSTR_FONT_HZK16), MP_ROM_INT(FONT_HZK16) }, { MP_ROM_QSTR(MP_QSTR_FONT_HZK24), MP_ROM_INT(FONT_HZK24) }, { MP_ROM_QSTR(MP_QSTR_FONT_HZK32), MP_ROM_INT(FONT_HZK32) }, }; STATIC MP_DEFINE_CONST_DICT(framebuf_module_globals, framebuf_module_globals_table); const mp_obj_module_t mp_module_framebuf = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&framebuf_module_globals, }; // #endif #endif // MICROPY_PY_FRAMEBUF
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modframebuf.c
C
apache-2.0
37,849
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013-2019 Damien P. George * Copyright (c) 2015 Galen Hazelwood * Copyright (c) 2015-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <string.h> #include <stdio.h> #include "py/objlist.h" #include "py/runtime.h" #include "py/stream.h" #include "py/mperrno.h" #include "py/mphal.h" #include "shared/netutils/netutils.h" #include "lwip/init.h" #include "lwip/tcp.h" #include "lwip/udp.h" #include "lwip/raw.h" #include "lwip/dns.h" #include "lwip/igmp.h" #if LWIP_VERSION_MAJOR < 2 #include "lwip/timers.h" #include "lwip/tcp_impl.h" #else #include "lwip/timeouts.h" #include "lwip/priv/tcp_priv.h" #endif #if 0 // print debugging info #define DEBUG_printf DEBUG_printf #else // don't print debugging info #define DEBUG_printf(...) (void)0 #endif // Timeout between closing a TCP socket and doing a tcp_abort on that // socket, if the connection isn't closed cleanly in that time. #define MICROPY_PY_LWIP_TCP_CLOSE_TIMEOUT_MS (10000) // All socket options should be globally distinct, // because we ignore option levels for efficiency. #define IP_ADD_MEMBERSHIP 0x400 // For compatibilily with older lwIP versions. #ifndef ip_set_option #define ip_set_option(pcb, opt) ((pcb)->so_options |= (opt)) #endif #ifndef ip_reset_option #define ip_reset_option(pcb, opt) ((pcb)->so_options &= ~(opt)) #endif // A port can define these hooks to provide concurrency protection #ifndef MICROPY_PY_LWIP_ENTER #define MICROPY_PY_LWIP_ENTER #define MICROPY_PY_LWIP_REENTER #define MICROPY_PY_LWIP_EXIT #endif #ifdef MICROPY_PY_LWIP_SLIP #include "netif/slipif.h" #include "lwip/sio.h" #endif #ifdef MICROPY_PY_LWIP_SLIP /******************************************************************************/ // Slip object for modlwip. Requires a serial driver for the port that supports // the lwip serial callback functions. typedef struct _lwip_slip_obj_t { mp_obj_base_t base; struct netif lwip_netif; } lwip_slip_obj_t; // Slip object is unique for now. Possibly can fix this later. FIXME STATIC lwip_slip_obj_t lwip_slip_obj; // Declare these early. void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg); void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg); STATIC void slip_lwip_poll(void *netif) { slipif_poll((struct netif *)netif); } STATIC const mp_obj_type_t lwip_slip_type; // lwIP SLIP callback functions sio_fd_t sio_open(u8_t dvnum) { // We support singleton SLIP interface, so just return any truish value. return (sio_fd_t)1; } void sio_send(u8_t c, sio_fd_t fd) { mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); int error; type->stream_p->write(MP_STATE_VM(lwip_slip_stream), &c, 1, &error); } u32_t sio_tryread(sio_fd_t fd, u8_t *data, u32_t len) { mp_obj_type_t *type = mp_obj_get_type(MP_STATE_VM(lwip_slip_stream)); int error; mp_uint_t out_sz = type->stream_p->read(MP_STATE_VM(lwip_slip_stream), data, len, &error); if (out_sz == MP_STREAM_ERROR) { if (mp_is_nonblocking_error(error)) { return 0; } // Can't do much else, can we? return 0; } return out_sz; } // constructor lwip.slip(device=integer, iplocal=string, ipremote=string) STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 3, 3, false); lwip_slip_obj.base.type = &lwip_slip_type; MP_STATE_VM(lwip_slip_stream) = args[0]; ip_addr_t iplocal, ipremote; if (!ipaddr_aton(mp_obj_str_get_str(args[1]), &iplocal)) { mp_raise_ValueError(MP_ERROR_TEXT("not a valid local IP")); } if (!ipaddr_aton(mp_obj_str_get_str(args[2]), &ipremote)) { mp_raise_ValueError(MP_ERROR_TEXT("not a valid remote IP")); } struct netif *n = &lwip_slip_obj.lwip_netif; if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("out of memory")); } netif_set_up(n); netif_set_default(n); mod_lwip_register_poll(slip_lwip_poll, n); return (mp_obj_t)&lwip_slip_obj; } STATIC mp_obj_t lwip_slip_status(mp_obj_t self_in) { // Null function for now. return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_slip_status_obj, lwip_slip_status); STATIC const mp_rom_map_elem_t lwip_slip_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&lwip_slip_status_obj) }, }; STATIC MP_DEFINE_CONST_DICT(lwip_slip_locals_dict, lwip_slip_locals_dict_table); STATIC const mp_obj_type_t lwip_slip_type = { { &mp_type_type }, .name = MP_QSTR_slip, .make_new = lwip_slip_make_new, .locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict, }; #endif // MICROPY_PY_LWIP_SLIP /******************************************************************************/ // Table to convert lwIP err_t codes to socket errno codes, from the lwIP // socket API. // lwIP 2 changed LWIP_VERSION and it can no longer be used in macros, // so we define our own equivalent version that can. #define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \ | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) // Extension to lwIP error codes #define _ERR_BADF -16 // TODO: We just know that change happened somewhere between 1.4.0 and 1.4.1, // investigate in more detail. #if LWIP_VERSION_MACRO < 0x01040100 static const int error_lookup_table[] = { 0, /* ERR_OK 0 No error, everything OK. */ MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ MP_EINVAL, /* ERR_VAL -6 Illegal value. */ MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ MP_ECONNABORTED, /* ERR_ABRT -8 Connection aborted. */ MP_ECONNRESET, /* ERR_RST -9 Connection reset. */ MP_ENOTCONN, /* ERR_CLSD -10 Connection closed. */ MP_ENOTCONN, /* ERR_CONN -11 Not connected. */ MP_EIO, /* ERR_ARG -12 Illegal argument. */ MP_EADDRINUSE, /* ERR_USE -13 Address in use. */ -1, /* ERR_IF -14 Low-level netif error */ MP_EALREADY, /* ERR_ISCONN -15 Already connected. */ MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ }; #elif LWIP_VERSION_MACRO < 0x02000000 static const int error_lookup_table[] = { 0, /* ERR_OK 0 No error, everything OK. */ MP_ENOMEM, /* ERR_MEM -1 Out of memory error. */ MP_ENOBUFS, /* ERR_BUF -2 Buffer error. */ MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem. */ MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ MP_EINVAL, /* ERR_VAL -6 Illegal value. */ MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block. */ MP_EADDRINUSE, /* ERR_USE -8 Address in use. */ MP_EALREADY, /* ERR_ISCONN -9 Already connected. */ MP_ECONNABORTED, /* ERR_ABRT -10 Connection aborted. */ MP_ECONNRESET, /* ERR_RST -11 Connection reset. */ MP_ENOTCONN, /* ERR_CLSD -12 Connection closed. */ MP_ENOTCONN, /* ERR_CONN -13 Not connected. */ MP_EIO, /* ERR_ARG -14 Illegal argument. */ -1, /* ERR_IF -15 Low-level netif error */ MP_EBADF, /* _ERR_BADF -16 Closed socket (null pcb) */ }; #else // Matches lwIP 2.0.3 #undef _ERR_BADF #define _ERR_BADF -17 static const int error_lookup_table[] = { 0, /* ERR_OK 0 No error, everything OK */ MP_ENOMEM, /* ERR_MEM -1 Out of memory error */ MP_ENOBUFS, /* ERR_BUF -2 Buffer error */ MP_EWOULDBLOCK, /* ERR_TIMEOUT -3 Timeout */ MP_EHOSTUNREACH, /* ERR_RTE -4 Routing problem */ MP_EINPROGRESS, /* ERR_INPROGRESS -5 Operation in progress */ MP_EINVAL, /* ERR_VAL -6 Illegal value */ MP_EWOULDBLOCK, /* ERR_WOULDBLOCK -7 Operation would block */ MP_EADDRINUSE, /* ERR_USE -8 Address in use */ MP_EALREADY, /* ERR_ALREADY -9 Already connecting */ MP_EALREADY, /* ERR_ISCONN -10 Conn already established */ MP_ENOTCONN, /* ERR_CONN -11 Not connected */ -1, /* ERR_IF -12 Low-level netif error */ MP_ECONNABORTED, /* ERR_ABRT -13 Connection aborted */ MP_ECONNRESET, /* ERR_RST -14 Connection reset */ MP_ENOTCONN, /* ERR_CLSD -15 Connection closed */ MP_EIO, /* ERR_ARG -16 Illegal argument. */ MP_EBADF, /* _ERR_BADF -17 Closed socket (null pcb) */ }; #endif /*******************************************************************************/ // The socket object provided by lwip.socket. #define MOD_NETWORK_AF_INET (2) #define MOD_NETWORK_AF_INET6 (10) #define MOD_NETWORK_SOCK_STREAM (1) #define MOD_NETWORK_SOCK_DGRAM (2) #define MOD_NETWORK_SOCK_RAW (3) typedef struct _lwip_socket_obj_t { mp_obj_base_t base; volatile union { struct tcp_pcb *tcp; struct udp_pcb *udp; struct raw_pcb *raw; } pcb; volatile union { struct pbuf *pbuf; struct { uint8_t alloc; uint8_t iget; uint8_t iput; union { struct tcp_pcb *item; // if alloc == 0 struct tcp_pcb **array; // if alloc != 0 } tcp; } connection; } incoming; mp_obj_t callback; byte peer[4]; mp_uint_t peer_port; mp_uint_t timeout; uint16_t recv_offset; uint8_t domain; uint8_t type; #define STATE_NEW 0 #define STATE_LISTENING 1 #define STATE_CONNECTING 2 #define STATE_CONNECTED 3 #define STATE_PEER_CLOSED 4 #define STATE_ACTIVE_UDP 5 // Negative value is lwIP error int8_t state; } lwip_socket_obj_t; static inline void poll_sockets(void) { #ifdef MICROPY_EVENT_POLL_HOOK MICROPY_EVENT_POLL_HOOK; #else mp_hal_delay_ms(1); #endif } STATIC struct tcp_pcb *volatile *lwip_socket_incoming_array(lwip_socket_obj_t *socket) { if (socket->incoming.connection.alloc == 0) { return &socket->incoming.connection.tcp.item; } else { return &socket->incoming.connection.tcp.array[0]; } } STATIC void lwip_socket_free_incoming(lwip_socket_obj_t *socket) { bool socket_is_listener = socket->type == MOD_NETWORK_SOCK_STREAM && socket->pcb.tcp->state == LISTEN; if (!socket_is_listener) { if (socket->incoming.pbuf != NULL) { pbuf_free(socket->incoming.pbuf); socket->incoming.pbuf = NULL; } } else { uint8_t alloc = socket->incoming.connection.alloc; struct tcp_pcb *volatile *tcp_array = lwip_socket_incoming_array(socket); for (uint8_t i = 0; i < alloc; ++i) { // Deregister callback and abort if (tcp_array[i] != NULL) { tcp_poll(tcp_array[i], NULL, 0); tcp_abort(tcp_array[i]); tcp_array[i] = NULL; } } } } /*******************************************************************************/ // Callback functions for the lwIP raw API. static inline void exec_user_callback(lwip_socket_obj_t *socket) { if (socket->callback != MP_OBJ_NULL) { // Schedule the user callback to execute outside the lwIP context mp_sched_schedule(socket->callback, MP_OBJ_FROM_PTR(socket)); } } #if MICROPY_PY_LWIP_SOCK_RAW // Callback for incoming raw packets. #if LWIP_VERSION_MAJOR < 2 STATIC u8_t _lwip_raw_incoming(void *arg, struct raw_pcb *pcb, struct pbuf *p, ip_addr_t *addr) #else STATIC u8_t _lwip_raw_incoming(void *arg, struct raw_pcb *pcb, struct pbuf *p, const ip_addr_t *addr) #endif { lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (socket->incoming.pbuf != NULL) { pbuf_free(p); } else { socket->incoming.pbuf = p; memcpy(&socket->peer, addr, sizeof(socket->peer)); } return 1; // we ate the packet } #endif // Callback for incoming UDP packets. We simply stash the packet and the source address, // in case we need it for recvfrom. #if LWIP_VERSION_MAJOR < 2 STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port) #else STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) #endif { lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (socket->incoming.pbuf != NULL) { // That's why they call it "unreliable". No room in the inn, drop the packet. pbuf_free(p); } else { socket->incoming.pbuf = p; socket->peer_port = (mp_uint_t)port; memcpy(&socket->peer, addr, sizeof(socket->peer)); } } // Callback for general tcp errors. STATIC void _lwip_tcp_error(void *arg, err_t err) { lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; // Free any incoming buffers or connections that are stored lwip_socket_free_incoming(socket); // Pass the error code back via the connection variable. socket->state = err; // If we got here, the lwIP stack either has deallocated or will deallocate the pcb. socket->pcb.tcp = NULL; } // Callback for tcp connection requests. Error code err is unused. (See tcp.h) STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; socket->state = STATE_CONNECTED; return ERR_OK; } // Handle errors (eg connection aborted) on TCP PCBs that have been put on the // accept queue but are not yet actually accepted. STATIC void _lwip_tcp_err_unaccepted(void *arg, err_t err) { struct tcp_pcb *pcb = (struct tcp_pcb *)arg; // The ->connected entry is repurposed to store the parent socket; this is safe // because it's only ever used by lwIP if tcp_connect is called on the TCP PCB. lwip_socket_obj_t *socket = (lwip_socket_obj_t *)pcb->connected; // Array is not volatile because thiss callback is executed within the lwIP context uint8_t alloc = socket->incoming.connection.alloc; struct tcp_pcb **tcp_array = (struct tcp_pcb **)lwip_socket_incoming_array(socket); // Search for PCB on the accept queue of the parent socket struct tcp_pcb **shift_down = NULL; uint8_t i = socket->incoming.connection.iget; do { if (shift_down == NULL) { if (tcp_array[i] == pcb) { shift_down = &tcp_array[i]; } } else { *shift_down = tcp_array[i]; shift_down = &tcp_array[i]; } if (++i >= alloc) { i = 0; } } while (i != socket->incoming.connection.iput); // PCB found in queue, remove it if (shift_down != NULL) { *shift_down = NULL; socket->incoming.connection.iput = shift_down - tcp_array; } } // By default, a child socket of listen socket is created with recv // handler which discards incoming pbuf's. We don't want to do that, // so set this handler which requests lwIP to keep pbuf's and deliver // them later. We cannot cache pbufs in child socket on Python side, // until it is created in accept(). STATIC err_t _lwip_tcp_recv_unaccepted(void *arg, struct tcp_pcb *pcb, struct pbuf *p, err_t err) { return ERR_BUF; } // Callback for incoming tcp connections. STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { // err can be ERR_MEM to notify us that there was no memory for an incoming connection if (err != ERR_OK) { return ERR_OK; } lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; tcp_recv(newpcb, _lwip_tcp_recv_unaccepted); // Search for an empty slot to store the new connection struct tcp_pcb *volatile *slot = &lwip_socket_incoming_array(socket)[socket->incoming.connection.iput]; if (*slot == NULL) { // Have an empty slot to store waiting connection *slot = newpcb; if (++socket->incoming.connection.iput >= socket->incoming.connection.alloc) { socket->incoming.connection.iput = 0; } // Schedule user accept callback exec_user_callback(socket); // Set the error callback to handle the case of a dropped connection before we // have a chance to take it off the accept queue. // The ->connected entry is repurposed to store the parent socket; this is safe // because it's only ever used by lwIP if tcp_connect is called on the TCP PCB. newpcb->connected = (void *)socket; tcp_arg(newpcb, newpcb); tcp_err(newpcb, _lwip_tcp_err_unaccepted); return ERR_OK; } DEBUG_printf("_lwip_tcp_accept: No room to queue pcb waiting for accept\n"); return ERR_BUF; } // Callback for inbound tcp packets. STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) { lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (p == NULL) { // Other side has closed connection. DEBUG_printf("_lwip_tcp_recv[%p]: other side closed connection\n", socket); socket->state = STATE_PEER_CLOSED; exec_user_callback(socket); return ERR_OK; } if (socket->incoming.pbuf == NULL) { socket->incoming.pbuf = p; } else { #ifdef SOCKET_SINGLE_PBUF return ERR_BUF; #else pbuf_cat(socket->incoming.pbuf, p); #endif } exec_user_callback(socket); return ERR_OK; } /*******************************************************************************/ // Functions for socket send/receive operations. Socket send/recv and friends call // these to do the work. // Helper function for send/sendto to handle raw/UDP packets. STATIC mp_uint_t lwip_raw_udp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { if (len > 0xffff) { // Any packet that big is probably going to fail the pbuf_alloc anyway, but may as well try len = 0xffff; } MICROPY_PY_LWIP_ENTER // FIXME: maybe PBUF_ROM? struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM); if (p == NULL) { MICROPY_PY_LWIP_EXIT *_errno = MP_ENOMEM; return -1; } memcpy(p->payload, buf, len); err_t err; if (ip == NULL) { #if MICROPY_PY_LWIP_SOCK_RAW if (socket->type == MOD_NETWORK_SOCK_RAW) { err = raw_send(socket->pcb.raw, p); } else #endif { err = udp_send(socket->pcb.udp, p); } } else { ip_addr_t dest; IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); #if MICROPY_PY_LWIP_SOCK_RAW if (socket->type == MOD_NETWORK_SOCK_RAW) { err = raw_sendto(socket->pcb.raw, p, &dest); } else #endif { err = udp_sendto(socket->pcb.udp, p, &dest, port); } } pbuf_free(p); MICROPY_PY_LWIP_EXIT // udp_sendto can return 1 on occasion for ESP8266 port. It's not known why // but it seems that the send actually goes through without error in this case. // So we treat such cases as a success until further investigation. if (err != ERR_OK && err != 1) { *_errno = error_lookup_table[-err]; return -1; } return len; } // Helper function for recv/recvfrom to handle raw/UDP packets STATIC mp_uint_t lwip_raw_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) { if (socket->incoming.pbuf == NULL) { if (socket->timeout == 0) { // Non-blocking socket. *_errno = MP_EAGAIN; return -1; } // Wait for data to arrive on UDP socket. mp_uint_t start = mp_hal_ticks_ms(); while (socket->incoming.pbuf == NULL) { if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { *_errno = MP_ETIMEDOUT; return -1; } poll_sockets(); } } if (ip != NULL) { memcpy(ip, &socket->peer, sizeof(socket->peer)); *port = socket->peer_port; } struct pbuf *p = socket->incoming.pbuf; MICROPY_PY_LWIP_ENTER u16_t result = pbuf_copy_partial(p, buf, ((p->tot_len > len) ? len : p->tot_len), 0); pbuf_free(p); socket->incoming.pbuf = NULL; MICROPY_PY_LWIP_EXIT return (mp_uint_t)result; } // For use in stream virtual methods #define STREAM_ERROR_CHECK(socket) \ if (socket->state < 0) { \ *_errno = error_lookup_table[-socket->state]; \ return MP_STREAM_ERROR; \ } \ assert(socket->pcb.tcp); // Version of above for use when lock is held #define STREAM_ERROR_CHECK_WITH_LOCK(socket) \ if (socket->state < 0) { \ *_errno = error_lookup_table[-socket->state]; \ MICROPY_PY_LWIP_EXIT \ return MP_STREAM_ERROR; \ } \ assert(socket->pcb.tcp); // Helper function for send/sendto to handle TCP packets STATIC mp_uint_t lwip_tcp_send(lwip_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) { // Check for any pending errors STREAM_ERROR_CHECK(socket); MICROPY_PY_LWIP_ENTER u16_t available = tcp_sndbuf(socket->pcb.tcp); if (available == 0) { // Non-blocking socket if (socket->timeout == 0) { MICROPY_PY_LWIP_EXIT *_errno = MP_EAGAIN; return MP_STREAM_ERROR; } mp_uint_t start = mp_hal_ticks_ms(); // Assume that STATE_PEER_CLOSED may mean half-closed connection, where peer closed it // sending direction, but not receiving. Consequently, check for both STATE_CONNECTED // and STATE_PEER_CLOSED as normal conditions and still waiting for buffers to be sent. // If peer fully closed socket, we would have socket->state set to ERR_RST (connection // reset) by error callback. // Avoid sending too small packets, so wait until at least 16 bytes available while (socket->state >= STATE_CONNECTED && (available = tcp_sndbuf(socket->pcb.tcp)) < 16) { MICROPY_PY_LWIP_EXIT if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { *_errno = MP_ETIMEDOUT; return MP_STREAM_ERROR; } poll_sockets(); MICROPY_PY_LWIP_REENTER } // While we waited, something could happen STREAM_ERROR_CHECK_WITH_LOCK(socket); } u16_t write_len = MIN(available, len); // If tcp_write returns ERR_MEM then there's currently not enough memory to // queue the write, so wait and keep trying until it succeeds (with 10s limit). // Note: if the socket is non-blocking then this code will actually block until // there's enough memory to do the write, but by this stage we have already // committed to being able to write the data. err_t err; for (int i = 0; i < 200; ++i) { err = tcp_write(socket->pcb.tcp, buf, write_len, TCP_WRITE_FLAG_COPY); if (err != ERR_MEM) { break; } err = tcp_output(socket->pcb.tcp); if (err != ERR_OK) { break; } MICROPY_PY_LWIP_EXIT mp_hal_delay_ms(50); MICROPY_PY_LWIP_REENTER } // If the output buffer is getting full then send the data to the lower layers if (err == ERR_OK && tcp_sndbuf(socket->pcb.tcp) < TCP_SND_BUF / 4) { err = tcp_output(socket->pcb.tcp); } MICROPY_PY_LWIP_EXIT if (err != ERR_OK) { *_errno = error_lookup_table[-err]; return MP_STREAM_ERROR; } return write_len; } // Helper function for recv/recvfrom to handle TCP packets STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_t len, int *_errno) { // Check for any pending errors STREAM_ERROR_CHECK(socket); if (socket->incoming.pbuf == NULL) { // Non-blocking socket if (socket->timeout == 0) { if (socket->state == STATE_PEER_CLOSED) { return 0; } *_errno = MP_EAGAIN; return -1; } mp_uint_t start = mp_hal_ticks_ms(); while (socket->state == STATE_CONNECTED && socket->incoming.pbuf == NULL) { if (socket->timeout != -1 && mp_hal_ticks_ms() - start > socket->timeout) { *_errno = MP_ETIMEDOUT; return -1; } poll_sockets(); } if (socket->state == STATE_PEER_CLOSED) { if (socket->incoming.pbuf == NULL) { // socket closed and no data left in buffer return 0; } } else if (socket->state != STATE_CONNECTED) { if (socket->state >= STATE_NEW) { *_errno = MP_ENOTCONN; } else { *_errno = error_lookup_table[-socket->state]; } return -1; } } MICROPY_PY_LWIP_ENTER assert(socket->pcb.tcp != NULL); struct pbuf *p = socket->incoming.pbuf; mp_uint_t remaining = p->len - socket->recv_offset; if (len > remaining) { len = remaining; } memcpy(buf, (byte *)p->payload + socket->recv_offset, len); remaining -= len; if (remaining == 0) { socket->incoming.pbuf = p->next; // If we don't ref here, free() will free the entire chain, // if we ref, it does what we need: frees 1st buf, and decrements // next buf's refcount back to 1. pbuf_ref(p->next); pbuf_free(p); socket->recv_offset = 0; } else { socket->recv_offset += len; } tcp_recved(socket->pcb.tcp, len); MICROPY_PY_LWIP_EXIT return len; } /*******************************************************************************/ // The socket functions provided by lwip.socket. STATIC const mp_obj_type_t lwip_socket_type; STATIC void lwip_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { lwip_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<socket state=%d timeout=%d incoming=%p off=%d>", self->state, self->timeout, self->incoming.pbuf, self->recv_offset); } // FIXME: Only supports two arguments at present STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 4, false); lwip_socket_obj_t *socket = m_new_obj_with_finaliser(lwip_socket_obj_t); socket->base.type = &lwip_socket_type; socket->timeout = -1; socket->recv_offset = 0; socket->domain = MOD_NETWORK_AF_INET; socket->type = MOD_NETWORK_SOCK_STREAM; socket->callback = MP_OBJ_NULL; socket->state = STATE_NEW; if (n_args >= 1) { socket->domain = mp_obj_get_int(args[0]); if (n_args >= 2) { socket->type = mp_obj_get_int(args[1]); } } switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: socket->pcb.tcp = tcp_new(); socket->incoming.connection.alloc = 0; socket->incoming.connection.tcp.item = NULL; break; case MOD_NETWORK_SOCK_DGRAM: socket->pcb.udp = udp_new(); socket->incoming.pbuf = NULL; break; #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: { mp_int_t proto = n_args <= 2 ? 0 : mp_obj_get_int(args[2]); socket->pcb.raw = raw_new(proto); break; } #endif default: mp_raise_OSError(MP_EINVAL); } if (socket->pcb.tcp == NULL) { mp_raise_OSError(MP_ENOMEM); } switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { // Register the socket object as our callback argument. tcp_arg(socket->pcb.tcp, (void *)socket); // Register our error callback. tcp_err(socket->pcb.tcp, _lwip_tcp_error); break; } case MOD_NETWORK_SOCK_DGRAM: { socket->state = STATE_ACTIVE_UDP; // Register our receive callback now. Since UDP sockets don't require binding or connection // before use, there's no other good time to do it. udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket); break; } #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: { // Register our receive callback now. Since raw sockets don't require binding or connection // before use, there's no other good time to do it. raw_recv(socket->pcb.raw, _lwip_raw_incoming, (void *)socket); break; } #endif } return MP_OBJ_FROM_PTR(socket); } STATIC mp_obj_t lwip_socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); ip_addr_t bind_addr; IP4_ADDR(&bind_addr, ip[0], ip[1], ip[2], ip[3]); err_t err = ERR_ARG; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { err = tcp_bind(socket->pcb.tcp, &bind_addr, port); break; } case MOD_NETWORK_SOCK_DGRAM: { err = udp_bind(socket->pcb.udp, &bind_addr, port); break; } } if (err != ERR_OK) { mp_raise_OSError(error_lookup_table[-err]); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_bind_obj, lwip_socket_bind); STATIC mp_obj_t lwip_socket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); mp_int_t backlog = mp_obj_get_int(backlog_in); if (socket->pcb.tcp == NULL) { mp_raise_OSError(MP_EBADF); } if (socket->type != MOD_NETWORK_SOCK_STREAM) { mp_raise_OSError(MP_EOPNOTSUPP); } struct tcp_pcb *new_pcb = tcp_listen_with_backlog(socket->pcb.tcp, (u8_t)backlog); if (new_pcb == NULL) { mp_raise_OSError(MP_ENOMEM); } socket->pcb.tcp = new_pcb; // Allocate memory for the backlog of connections if (backlog <= 1) { socket->incoming.connection.alloc = 0; socket->incoming.connection.tcp.item = NULL; } else { socket->incoming.connection.alloc = backlog; socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb *, backlog); } socket->incoming.connection.iget = 0; socket->incoming.connection.iput = 0; tcp_accept(new_pcb, _lwip_tcp_accept); // Socket is no longer considered "new" for purposes of polling socket->state = STATE_LISTENING; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_listen_obj, lwip_socket_listen); STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); if (socket->type != MOD_NETWORK_SOCK_STREAM) { mp_raise_OSError(MP_EOPNOTSUPP); } // Create new socket object, do it here because we must not raise an out-of-memory // exception when the LWIP concurrency lock is held lwip_socket_obj_t *socket2 = m_new_obj_with_finaliser(lwip_socket_obj_t); socket2->base.type = &lwip_socket_type; MICROPY_PY_LWIP_ENTER if (socket->pcb.tcp == NULL) { MICROPY_PY_LWIP_EXIT m_del_obj(lwip_socket_obj_t, socket2); mp_raise_OSError(MP_EBADF); } // I need to do this because "tcp_accepted", later, is a macro. struct tcp_pcb *listener = socket->pcb.tcp; if (listener->state != LISTEN) { MICROPY_PY_LWIP_EXIT m_del_obj(lwip_socket_obj_t, socket2); mp_raise_OSError(MP_EINVAL); } // accept incoming connection struct tcp_pcb *volatile *incoming_connection = &lwip_socket_incoming_array(socket)[socket->incoming.connection.iget]; if (*incoming_connection == NULL) { if (socket->timeout == 0) { MICROPY_PY_LWIP_EXIT m_del_obj(lwip_socket_obj_t, socket2); mp_raise_OSError(MP_EAGAIN); } else if (socket->timeout != -1) { mp_uint_t retries = socket->timeout / 100; while (*incoming_connection == NULL) { MICROPY_PY_LWIP_EXIT if (retries-- == 0) { m_del_obj(lwip_socket_obj_t, socket2); mp_raise_OSError(MP_ETIMEDOUT); } mp_hal_delay_ms(100); MICROPY_PY_LWIP_REENTER } } else { while (*incoming_connection == NULL) { MICROPY_PY_LWIP_EXIT poll_sockets(); MICROPY_PY_LWIP_REENTER } } } // We get a new pcb handle... socket2->pcb.tcp = *incoming_connection; if (++socket->incoming.connection.iget >= socket->incoming.connection.alloc) { socket->incoming.connection.iget = 0; } *incoming_connection = NULL; // ...and set up the new socket for it. socket2->domain = MOD_NETWORK_AF_INET; socket2->type = MOD_NETWORK_SOCK_STREAM; socket2->incoming.pbuf = NULL; socket2->timeout = socket->timeout; socket2->state = STATE_CONNECTED; socket2->recv_offset = 0; socket2->callback = MP_OBJ_NULL; tcp_arg(socket2->pcb.tcp, (void *)socket2); tcp_err(socket2->pcb.tcp, _lwip_tcp_error); tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv); tcp_accepted(listener); MICROPY_PY_LWIP_EXIT // make the return value uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; memcpy(ip, &(socket2->pcb.tcp->remote_ip), sizeof(ip)); mp_uint_t port = (mp_uint_t)socket2->pcb.tcp->remote_port; mp_obj_tuple_t *client = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); client->items[0] = MP_OBJ_FROM_PTR(socket2); client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); return MP_OBJ_FROM_PTR(client); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(lwip_socket_accept_obj, lwip_socket_accept); STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); if (socket->pcb.tcp == NULL) { mp_raise_OSError(MP_EBADF); } // get address uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); ip_addr_t dest; IP4_ADDR(&dest, ip[0], ip[1], ip[2], ip[3]); err_t err = ERR_ARG; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { if (socket->state != STATE_NEW) { if (socket->state == STATE_CONNECTED) { mp_raise_OSError(MP_EISCONN); } else { mp_raise_OSError(MP_EALREADY); } } // Register our receive callback. MICROPY_PY_LWIP_ENTER tcp_recv(socket->pcb.tcp, _lwip_tcp_recv); socket->state = STATE_CONNECTING; err = tcp_connect(socket->pcb.tcp, &dest, port, _lwip_tcp_connected); if (err != ERR_OK) { MICROPY_PY_LWIP_EXIT socket->state = STATE_NEW; mp_raise_OSError(error_lookup_table[-err]); } socket->peer_port = (mp_uint_t)port; memcpy(socket->peer, &dest, sizeof(socket->peer)); MICROPY_PY_LWIP_EXIT // And now we wait... if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); if (socket->state != STATE_CONNECTING) { break; } } if (socket->state == STATE_CONNECTING) { mp_raise_OSError(MP_EINPROGRESS); } } else { while (socket->state == STATE_CONNECTING) { poll_sockets(); } } if (socket->state == STATE_CONNECTED) { err = ERR_OK; } else { err = socket->state; } break; } case MOD_NETWORK_SOCK_DGRAM: { err = udp_connect(socket->pcb.udp, &dest, port); break; } #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: { err = raw_connect(socket->pcb.raw, &dest); break; } #endif } if (err != ERR_OK) { mp_raise_OSError(error_lookup_table[-err]); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_connect_obj, lwip_socket_connect); STATIC void lwip_socket_check_connected(lwip_socket_obj_t *socket) { if (socket->pcb.tcp == NULL) { // not connected int _errno = error_lookup_table[-socket->state]; socket->state = _ERR_BADF; mp_raise_OSError(_errno); } } STATIC mp_obj_t lwip_socket_send(mp_obj_t self_in, mp_obj_t buf_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); int _errno; lwip_socket_check_connected(socket); mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: #endif ret = lwip_raw_udp_send(socket, bufinfo.buf, bufinfo.len, NULL, 0, &_errno); break; } if (ret == -1) { mp_raise_OSError(_errno); } return mp_obj_new_int_from_uint(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_send_obj, lwip_socket_send); STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); int _errno; lwip_socket_check_connected(socket); mp_int_t len = mp_obj_get_int(len_in); vstr_t vstr; vstr_init_len(&vstr, len); mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: #endif ret = lwip_raw_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno); break; } if (ret == -1) { mp_raise_OSError(_errno); } if (ret == 0) { return mp_const_empty_bytes; } vstr.len = ret; return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recv_obj, lwip_socket_recv); STATIC mp_obj_t lwip_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); int _errno; lwip_socket_check_connected(socket); mp_buffer_info_t bufinfo; mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_READ); uint8_t ip[NETUTILS_IPV4ADDR_BUFSIZE]; mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_BIG); mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: #endif ret = lwip_raw_udp_send(socket, bufinfo.buf, bufinfo.len, ip, port, &_errno); break; } if (ret == -1) { mp_raise_OSError(_errno); } return mp_obj_new_int_from_uint(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(lwip_socket_sendto_obj, lwip_socket_sendto); STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); int _errno; lwip_socket_check_connected(socket); mp_int_t len = mp_obj_get_int(len_in); vstr_t vstr; vstr_init_len(&vstr, len); byte ip[4]; mp_uint_t port; mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { memcpy(ip, &socket->peer, sizeof(socket->peer)); port = (mp_uint_t)socket->peer_port; ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: #endif ret = lwip_raw_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno); break; } if (ret == -1) { mp_raise_OSError(_errno); } mp_obj_t tuple[2]; if (ret == 0) { tuple[0] = mp_const_empty_bytes; } else { vstr.len = ret; tuple[0] = mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); return mp_obj_new_tuple(2, tuple); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_recvfrom_obj, lwip_socket_recvfrom); STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); lwip_socket_check_connected(socket); int _errno; mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { if (socket->timeout == 0) { // Behavior of sendall() for non-blocking sockets isn't explicitly specified. // But it's specified that "On error, an exception is raised, there is no // way to determine how much data, if any, was successfully sent." Then, the // most useful behavior is: check whether we will be able to send all of input // data without EAGAIN, and if won't be, raise it without sending any. if (bufinfo.len > tcp_sndbuf(socket->pcb.tcp)) { mp_raise_OSError(MP_EAGAIN); } } // TODO: In CPython3.5, socket timeout should apply to the // entire sendall() operation, not to individual send() chunks. while (bufinfo.len != 0) { ret = lwip_tcp_send(socket, bufinfo.buf, bufinfo.len, &_errno); if (ret == -1) { mp_raise_OSError(_errno); } bufinfo.len -= ret; bufinfo.buf = (char *)bufinfo.buf + ret; } break; } case MOD_NETWORK_SOCK_DGRAM: mp_raise_NotImplementedError(NULL); break; } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_sendall_obj, lwip_socket_sendall); STATIC mp_obj_t lwip_socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); mp_uint_t timeout; if (timeout_in == mp_const_none) { timeout = -1; } else { #if MICROPY_PY_BUILTINS_FLOAT timeout = (mp_uint_t)(MICROPY_FLOAT_CONST(1000.0) * mp_obj_get_float(timeout_in)); #else timeout = 1000 * mp_obj_get_int(timeout_in); #endif } socket->timeout = timeout; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_settimeout_obj, lwip_socket_settimeout); STATIC mp_obj_t lwip_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); bool val = mp_obj_is_true(flag_in); if (val) { socket->timeout = -1; } else { socket->timeout = 0; } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(lwip_socket_setblocking_obj, lwip_socket_setblocking); STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) { (void)n_args; // always 4 lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(args[0]); int opt = mp_obj_get_int(args[2]); if (opt == 20) { if (args[3] == mp_const_none) { socket->callback = MP_OBJ_NULL; } else { socket->callback = args[3]; } return mp_const_none; } switch (opt) { // level: SOL_SOCKET case SOF_REUSEADDR: { mp_int_t val = mp_obj_get_int(args[3]); // Options are common for UDP and TCP pcb's. if (val) { ip_set_option(socket->pcb.tcp, SOF_REUSEADDR); } else { ip_reset_option(socket->pcb.tcp, SOF_REUSEADDR); } break; } // level: IPPROTO_IP case IP_ADD_MEMBERSHIP: { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); if (bufinfo.len != sizeof(ip_addr_t) * 2) { mp_raise_ValueError(NULL); } // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf); if (err != ERR_OK) { mp_raise_OSError(error_lookup_table[-err]); } break; } default: printf("Warning: lwip.setsockopt() not implemented\n"); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_setsockopt_obj, 4, 4, lwip_socket_setsockopt); STATIC mp_obj_t lwip_socket_makefile(size_t n_args, const mp_obj_t *args) { (void)n_args; return args[0]; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_socket_makefile_obj, 1, 3, lwip_socket_makefile); STATIC mp_uint_t lwip_socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: return lwip_tcp_receive(socket, buf, size, errcode); case MOD_NETWORK_SOCK_DGRAM: #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: #endif return lwip_raw_udp_receive(socket, buf, size, NULL, NULL, errcode); } // Unreachable return MP_STREAM_ERROR; } STATIC mp_uint_t lwip_socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: return lwip_tcp_send(socket, buf, size, errcode); case MOD_NETWORK_SOCK_DGRAM: #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: #endif return lwip_raw_udp_send(socket, buf, size, NULL, 0, errcode); } // Unreachable return MP_STREAM_ERROR; } STATIC err_t _lwip_tcp_close_poll(void *arg, struct tcp_pcb *pcb) { // Connection has not been cleanly closed so just abort it to free up memory tcp_poll(pcb, NULL, 0); tcp_abort(pcb); return ERR_OK; } STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { lwip_socket_obj_t *socket = MP_OBJ_TO_PTR(self_in); mp_uint_t ret; MICROPY_PY_LWIP_ENTER if (request == MP_STREAM_POLL) { uintptr_t flags = arg; ret = 0; if (flags & MP_STREAM_POLL_RD) { if (socket->state == STATE_LISTENING) { // Listening TCP socket may have one or multiple connections waiting if (lwip_socket_incoming_array(socket)[socket->incoming.connection.iget] != NULL) { ret |= MP_STREAM_POLL_RD; } } else { // Otherwise there is just one slot for incoming data if (socket->incoming.pbuf != NULL) { ret |= MP_STREAM_POLL_RD; } } } if (flags & MP_STREAM_POLL_WR) { if (socket->type == MOD_NETWORK_SOCK_DGRAM && socket->pcb.udp != NULL) { // UDP socket is writable ret |= MP_STREAM_POLL_WR; #if MICROPY_PY_LWIP_SOCK_RAW } else if (socket->type == MOD_NETWORK_SOCK_RAW && socket->pcb.raw != NULL) { // raw socket is writable ret |= MP_STREAM_POLL_WR; #endif } else if (socket->pcb.tcp != NULL && tcp_sndbuf(socket->pcb.tcp) > 0) { // TCP socket is writable // Note: pcb.tcp==NULL if state<0, and in this case we can't call tcp_sndbuf ret |= MP_STREAM_POLL_WR; } } if (socket->state == STATE_NEW) { // New sockets are not connected so set HUP ret |= MP_STREAM_POLL_HUP; } else if (socket->state == STATE_PEER_CLOSED) { // Peer-closed socket is both readable and writable: read will // return EOF, write - error. Without this poll will hang on a // socket which was closed by peer. ret |= flags & (MP_STREAM_POLL_RD | MP_STREAM_POLL_WR); } else if (socket->state == ERR_RST) { // Socket was reset by peer, a write will return an error ret |= flags & MP_STREAM_POLL_WR; ret |= MP_STREAM_POLL_HUP; } else if (socket->state == _ERR_BADF) { ret |= MP_STREAM_POLL_NVAL; } else if (socket->state < 0) { // Socket in some other error state, use catch-all ERR flag // TODO: may need to set other return flags here ret |= MP_STREAM_POLL_ERR; } } else if (request == MP_STREAM_CLOSE) { if (socket->pcb.tcp == NULL) { MICROPY_PY_LWIP_EXIT return 0; } // Free any incoming buffers or connections that are stored lwip_socket_free_incoming(socket); switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { // Deregister callback (pcb.tcp is set to NULL below so must deregister now) tcp_arg(socket->pcb.tcp, NULL); tcp_err(socket->pcb.tcp, NULL); tcp_recv(socket->pcb.tcp, NULL); if (socket->pcb.tcp->state != LISTEN) { // Schedule a callback to abort the connection if it's not cleanly closed after // the given timeout. The callback must be set before calling tcp_close since // the latter may free the pcb; if it doesn't then the callback will be active. tcp_poll(socket->pcb.tcp, _lwip_tcp_close_poll, MICROPY_PY_LWIP_TCP_CLOSE_TIMEOUT_MS / 500); } if (tcp_close(socket->pcb.tcp) != ERR_OK) { DEBUG_printf("lwip_close: had to call tcp_abort()\n"); tcp_abort(socket->pcb.tcp); } break; } case MOD_NETWORK_SOCK_DGRAM: udp_recv(socket->pcb.udp, NULL, NULL); udp_remove(socket->pcb.udp); break; #if MICROPY_PY_LWIP_SOCK_RAW case MOD_NETWORK_SOCK_RAW: raw_recv(socket->pcb.raw, NULL, NULL); raw_remove(socket->pcb.raw); break; #endif } socket->pcb.tcp = NULL; socket->state = _ERR_BADF; ret = 0; } else { *errcode = MP_EINVAL; ret = MP_STREAM_ERROR; } MICROPY_PY_LWIP_EXIT return ret; } STATIC const mp_rom_map_elem_t lwip_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&lwip_socket_bind_obj) }, { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&lwip_socket_listen_obj) }, { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&lwip_socket_accept_obj) }, { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&lwip_socket_connect_obj) }, { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&lwip_socket_send_obj) }, { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&lwip_socket_recv_obj) }, { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&lwip_socket_sendto_obj) }, { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&lwip_socket_recvfrom_obj) }, { MP_ROM_QSTR(MP_QSTR_sendall), MP_ROM_PTR(&lwip_socket_sendall_obj) }, { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&lwip_socket_settimeout_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&lwip_socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&lwip_socket_setsockopt_obj) }, { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&lwip_socket_makefile_obj) }, { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, }; STATIC MP_DEFINE_CONST_DICT(lwip_socket_locals_dict, lwip_socket_locals_dict_table); STATIC const mp_stream_p_t lwip_socket_stream_p = { .read = lwip_socket_read, .write = lwip_socket_write, .ioctl = lwip_socket_ioctl, }; STATIC const mp_obj_type_t lwip_socket_type = { { &mp_type_type }, .name = MP_QSTR_socket, .print = lwip_socket_print, .make_new = lwip_socket_make_new, .protocol = &lwip_socket_stream_p, .locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict, }; /******************************************************************************/ // Support functions for memory protection. lwIP has its own memory management // routines for its internal structures, and since they might be called in // interrupt handlers, they need some protection. sys_prot_t sys_arch_protect() { return (sys_prot_t)MICROPY_BEGIN_ATOMIC_SECTION(); } void sys_arch_unprotect(sys_prot_t state) { MICROPY_END_ATOMIC_SECTION((mp_uint_t)state); } /******************************************************************************/ // Polling callbacks for the interfaces connected to lwIP. Right now it calls // itself a "list" but isn't; we only support a single interface. typedef struct nic_poll { void (*poll)(void *arg); void *poll_arg; } nic_poll_t; STATIC nic_poll_t lwip_poll_list; void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) { lwip_poll_list.poll = poll; lwip_poll_list.poll_arg = poll_arg; } void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) { lwip_poll_list.poll = NULL; } /******************************************************************************/ // The lwip global functions. STATIC mp_obj_t mod_lwip_reset() { lwip_init(); lwip_poll_list.poll = NULL; return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_reset_obj, mod_lwip_reset); STATIC mp_obj_t mod_lwip_callback() { if (lwip_poll_list.poll != NULL) { lwip_poll_list.poll(lwip_poll_list.poll_arg); } sys_check_timeouts(); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_0(mod_lwip_callback_obj, mod_lwip_callback); typedef struct _getaddrinfo_state_t { volatile int status; volatile ip_addr_t ipaddr; } getaddrinfo_state_t; // Callback for incoming DNS requests. #if LWIP_VERSION_MAJOR < 2 STATIC void lwip_getaddrinfo_cb(const char *name, ip_addr_t *ipaddr, void *arg) #else STATIC void lwip_getaddrinfo_cb(const char *name, const ip_addr_t *ipaddr, void *arg) #endif { getaddrinfo_state_t *state = arg; if (ipaddr != NULL) { state->status = 1; state->ipaddr = *ipaddr; } else { // error state->status = -2; } } // lwip.getaddrinfo STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { mp_obj_t host_in = args[0], port_in = args[1]; const char *host = mp_obj_str_get_str(host_in); mp_int_t port = mp_obj_get_int(port_in); // If constraints were passed then check they are compatible with the supported params if (n_args > 2) { mp_int_t family = mp_obj_get_int(args[2]); mp_int_t type = 0; mp_int_t proto = 0; mp_int_t flags = 0; if (n_args > 3) { type = mp_obj_get_int(args[3]); if (n_args > 4) { proto = mp_obj_get_int(args[4]); if (n_args > 5) { flags = mp_obj_get_int(args[5]); } } } if (!((family == 0 || family == MOD_NETWORK_AF_INET) && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) && proto == 0 && flags == 0)) { mp_warning(MP_WARN_CAT(RuntimeWarning), "unsupported getaddrinfo constraints"); } } getaddrinfo_state_t state; state.status = 0; MICROPY_PY_LWIP_ENTER err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state); MICROPY_PY_LWIP_EXIT switch (ret) { case ERR_OK: // cached state.status = 1; break; case ERR_INPROGRESS: while (state.status == 0) { poll_sockets(); } break; default: state.status = ret; } if (state.status < 0) { // TODO: CPython raises gaierror, we raise with native lwIP negative error // values, to differentiate from normal errno's at least in such way. mp_raise_OSError(state.status); } mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); tuple->items[0] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_AF_INET); tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM); tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG); return mp_obj_new_list(1, (mp_obj_t *)&tuple); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo); // Debug functions STATIC mp_obj_t lwip_print_pcbs() { tcp_debug_print_pcbs(); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_0(lwip_print_pcbs_obj, lwip_print_pcbs); #if MICROPY_PY_LWIP STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lwip) }, { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&mod_lwip_reset_obj) }, { MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&mod_lwip_callback_obj) }, { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&lwip_getaddrinfo_obj) }, { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) }, // objects { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) }, #ifdef MICROPY_PY_LWIP_SLIP { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, #endif // class constants { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) }, { MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) }, { MP_ROM_QSTR(MP_QSTR_SOCK_STREAM), MP_ROM_INT(MOD_NETWORK_SOCK_STREAM) }, { MP_ROM_QSTR(MP_QSTR_SOCK_DGRAM), MP_ROM_INT(MOD_NETWORK_SOCK_DGRAM) }, #if MICROPY_PY_LWIP_SOCK_RAW { MP_ROM_QSTR(MP_QSTR_SOCK_RAW), MP_ROM_INT(MOD_NETWORK_SOCK_RAW) }, #endif { MP_ROM_QSTR(MP_QSTR_SOL_SOCKET), MP_ROM_INT(1) }, { MP_ROM_QSTR(MP_QSTR_SO_REUSEADDR), MP_ROM_INT(SOF_REUSEADDR) }, { MP_ROM_QSTR(MP_QSTR_IPPROTO_IP), MP_ROM_INT(0) }, { MP_ROM_QSTR(MP_QSTR_IP_ADD_MEMBERSHIP), MP_ROM_INT(IP_ADD_MEMBERSHIP) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table); const mp_obj_module_t mp_module_lwip = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_lwip_globals, }; #endif // MICROPY_PY_LWIP
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modlwip.c
C
apache-2.0
62,127
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2015-2017 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <stdint.h> #include "py/obj.h" #include "py/mphal.h" /******************************************************************************/ // Low-level 1-Wire routines #define TIMING_RESET1 (480) #define TIMING_RESET2 (70) #define TIMING_RESET3 (410) #define TIMING_READ1 (5) #define TIMING_READ2 (5) #define TIMING_READ3 (40) #define TIMING_WRITE1 (10) #define TIMING_WRITE2 (50) #define TIMING_WRITE3 (10) STATIC int onewire_bus_reset(mp_hal_pin_obj_t pin) { mp_hal_pin_od_low(pin); mp_hal_delay_us(TIMING_RESET1); uint32_t i = mp_hal_quiet_timing_enter(); mp_hal_pin_od_high(pin); mp_hal_delay_us_fast(TIMING_RESET2); int status = !mp_hal_pin_read(pin); mp_hal_quiet_timing_exit(i); mp_hal_delay_us(TIMING_RESET3); return status; } STATIC int onewire_bus_readbit(mp_hal_pin_obj_t pin) { mp_hal_pin_od_high(pin); uint32_t i = mp_hal_quiet_timing_enter(); mp_hal_pin_od_low(pin); mp_hal_delay_us_fast(TIMING_READ1); mp_hal_pin_od_high(pin); mp_hal_delay_us_fast(TIMING_READ2); int value = mp_hal_pin_read(pin); mp_hal_quiet_timing_exit(i); mp_hal_delay_us_fast(TIMING_READ3); return value; } STATIC void onewire_bus_writebit(mp_hal_pin_obj_t pin, int value) { uint32_t i = mp_hal_quiet_timing_enter(); mp_hal_pin_od_low(pin); mp_hal_delay_us_fast(TIMING_WRITE1); if (value) { mp_hal_pin_od_high(pin); } mp_hal_delay_us_fast(TIMING_WRITE2); mp_hal_pin_od_high(pin); mp_hal_delay_us_fast(TIMING_WRITE3); mp_hal_quiet_timing_exit(i); } /******************************************************************************/ // MicroPython bindings STATIC mp_obj_t onewire_reset(mp_obj_t pin_in) { return mp_obj_new_bool(onewire_bus_reset(mp_hal_get_pin_obj(pin_in))); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_reset_obj, onewire_reset); STATIC mp_obj_t onewire_readbit(mp_obj_t pin_in) { return MP_OBJ_NEW_SMALL_INT(onewire_bus_readbit(mp_hal_get_pin_obj(pin_in))); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_readbit_obj, onewire_readbit); STATIC mp_obj_t onewire_readbyte(mp_obj_t pin_in) { mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(pin_in); uint8_t value = 0; for (int i = 0; i < 8; ++i) { value |= onewire_bus_readbit(pin) << i; } return MP_OBJ_NEW_SMALL_INT(value); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_readbyte_obj, onewire_readbyte); STATIC mp_obj_t onewire_writebit(mp_obj_t pin_in, mp_obj_t value_in) { onewire_bus_writebit(mp_hal_get_pin_obj(pin_in), mp_obj_get_int(value_in)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(onewire_writebit_obj, onewire_writebit); STATIC mp_obj_t onewire_writebyte(mp_obj_t pin_in, mp_obj_t value_in) { mp_hal_pin_obj_t pin = mp_hal_get_pin_obj(pin_in); int value = mp_obj_get_int(value_in); for (int i = 0; i < 8; ++i) { onewire_bus_writebit(pin, value & 1); value >>= 1; } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(onewire_writebyte_obj, onewire_writebyte); STATIC mp_obj_t onewire_crc8(mp_obj_t data) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); uint8_t crc = 0; for (size_t i = 0; i < bufinfo.len; ++i) { uint8_t byte = ((uint8_t *)bufinfo.buf)[i]; for (int b = 0; b < 8; ++b) { uint8_t fb_bit = (crc ^ byte) & 0x01; if (fb_bit == 0x01) { crc = crc ^ 0x18; } crc = (crc >> 1) & 0x7f; if (fb_bit == 0x01) { crc = crc | 0x80; } byte = byte >> 1; } } return MP_OBJ_NEW_SMALL_INT(crc); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(onewire_crc8_obj, onewire_crc8); STATIC const mp_rom_map_elem_t onewire_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_onewire) }, { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&onewire_reset_obj) }, { MP_ROM_QSTR(MP_QSTR_readbit), MP_ROM_PTR(&onewire_readbit_obj) }, { MP_ROM_QSTR(MP_QSTR_readbyte), MP_ROM_PTR(&onewire_readbyte_obj) }, { MP_ROM_QSTR(MP_QSTR_writebit), MP_ROM_PTR(&onewire_writebit_obj) }, { MP_ROM_QSTR(MP_QSTR_writebyte), MP_ROM_PTR(&onewire_writebyte_obj) }, { MP_ROM_QSTR(MP_QSTR_crc8), MP_ROM_PTR(&onewire_crc8_obj) }, }; STATIC MP_DEFINE_CONST_DICT(onewire_module_globals, onewire_module_globals_table); const mp_obj_module_t mp_module_onewire = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&onewire_module_globals, };
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modonewire.c
C
apache-2.0
5,780
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2020 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/smallint.h" #include "py/pairheap.h" #include "py/mphal.h" #if MICROPY_PY_UASYNCIO // Used when task cannot be guaranteed to be non-NULL. #define TASK_PAIRHEAP(task) ((task) ? &(task)->pairheap : NULL) #define TASK_STATE_RUNNING_NOT_WAITED_ON (mp_const_true) #define TASK_STATE_DONE_NOT_WAITED_ON (mp_const_none) #define TASK_STATE_DONE_WAS_WAITED_ON (mp_const_false) #define TASK_IS_DONE(task) ( \ (task)->state == TASK_STATE_DONE_NOT_WAITED_ON \ || (task)->state == TASK_STATE_DONE_WAS_WAITED_ON) typedef struct _mp_obj_task_t { mp_pairheap_t pairheap; mp_obj_t coro; mp_obj_t data; mp_obj_t state; mp_obj_t ph_key; } mp_obj_task_t; typedef struct _mp_obj_task_queue_t { mp_obj_base_t base; mp_obj_task_t *heap; } mp_obj_task_queue_t; STATIC const mp_obj_type_t task_queue_type; STATIC const mp_obj_type_t task_type; STATIC mp_obj_t task_queue_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args); /******************************************************************************/ // Ticks for task ordering in pairing heap STATIC mp_obj_t ticks(void) { return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_ms() & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)); } STATIC mp_int_t ticks_diff(mp_obj_t t1_in, mp_obj_t t0_in) { mp_uint_t t0 = MP_OBJ_SMALL_INT_VALUE(t0_in); mp_uint_t t1 = MP_OBJ_SMALL_INT_VALUE(t1_in); mp_int_t diff = ((t1 - t0 + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)) - MICROPY_PY_UTIME_TICKS_PERIOD / 2; return diff; } STATIC int task_lt(mp_pairheap_t *n1, mp_pairheap_t *n2) { mp_obj_task_t *t1 = (mp_obj_task_t *)n1; mp_obj_task_t *t2 = (mp_obj_task_t *)n2; return MP_OBJ_SMALL_INT_VALUE(ticks_diff(t1->ph_key, t2->ph_key)) < 0; } /******************************************************************************/ // TaskQueue class STATIC mp_obj_t task_queue_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { (void)args; mp_arg_check_num(n_args, n_kw, 0, 0, false); mp_obj_task_queue_t *self = m_new_obj(mp_obj_task_queue_t); self->base.type = type; self->heap = (mp_obj_task_t *)mp_pairheap_new(task_lt); return MP_OBJ_FROM_PTR(self); } STATIC mp_obj_t task_queue_peek(mp_obj_t self_in) { mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(self_in); if (self->heap == NULL) { return mp_const_none; } else { return MP_OBJ_FROM_PTR(self->heap); } } STATIC MP_DEFINE_CONST_FUN_OBJ_1(task_queue_peek_obj, task_queue_peek); STATIC mp_obj_t task_queue_push_sorted(size_t n_args, const mp_obj_t *args) { mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(args[0]); mp_obj_task_t *task = MP_OBJ_TO_PTR(args[1]); task->data = mp_const_none; if (n_args == 2) { task->ph_key = ticks(); } else { assert(mp_obj_is_small_int(args[2])); task->ph_key = args[2]; } self->heap = (mp_obj_task_t *)mp_pairheap_push(task_lt, TASK_PAIRHEAP(self->heap), TASK_PAIRHEAP(task)); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(task_queue_push_sorted_obj, 2, 3, task_queue_push_sorted); STATIC mp_obj_t task_queue_pop_head(mp_obj_t self_in) { mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_task_t *head = (mp_obj_task_t *)mp_pairheap_peek(task_lt, &self->heap->pairheap); if (head == NULL) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty heap")); } self->heap = (mp_obj_task_t *)mp_pairheap_pop(task_lt, &self->heap->pairheap); return MP_OBJ_FROM_PTR(head); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(task_queue_pop_head_obj, task_queue_pop_head); STATIC mp_obj_t task_queue_remove(mp_obj_t self_in, mp_obj_t task_in) { mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(self_in); mp_obj_task_t *task = MP_OBJ_TO_PTR(task_in); self->heap = (mp_obj_task_t *)mp_pairheap_delete(task_lt, &self->heap->pairheap, &task->pairheap); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(task_queue_remove_obj, task_queue_remove); STATIC const mp_rom_map_elem_t task_queue_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_peek), MP_ROM_PTR(&task_queue_peek_obj) }, { MP_ROM_QSTR(MP_QSTR_push_sorted), MP_ROM_PTR(&task_queue_push_sorted_obj) }, { MP_ROM_QSTR(MP_QSTR_push_head), MP_ROM_PTR(&task_queue_push_sorted_obj) }, { MP_ROM_QSTR(MP_QSTR_pop_head), MP_ROM_PTR(&task_queue_pop_head_obj) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&task_queue_remove_obj) }, }; STATIC MP_DEFINE_CONST_DICT(task_queue_locals_dict, task_queue_locals_dict_table); STATIC const mp_obj_type_t task_queue_type = { { &mp_type_type }, .name = MP_QSTR_TaskQueue, .make_new = task_queue_make_new, .locals_dict = (mp_obj_dict_t *)&task_queue_locals_dict, }; /******************************************************************************/ // Task class // This is the core uasyncio context with cur_task, _task_queue and CancelledError. STATIC mp_obj_t uasyncio_context = MP_OBJ_NULL; STATIC mp_obj_t task_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 2, false); mp_obj_task_t *self = m_new_obj(mp_obj_task_t); self->pairheap.base.type = type; mp_pairheap_init_node(task_lt, &self->pairheap); self->coro = args[0]; self->data = mp_const_none; self->state = TASK_STATE_RUNNING_NOT_WAITED_ON; self->ph_key = MP_OBJ_NEW_SMALL_INT(0); if (n_args == 2) { uasyncio_context = args[1]; } return MP_OBJ_FROM_PTR(self); } STATIC mp_obj_t task_done(mp_obj_t self_in) { mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_bool(TASK_IS_DONE(self)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(task_done_obj, task_done); STATIC mp_obj_t task_cancel(mp_obj_t self_in) { mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in); // Check if task is already finished. if (TASK_IS_DONE(self)) { return mp_const_false; } // Can't cancel self (not supported yet). mp_obj_t cur_task = mp_obj_dict_get(uasyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR_cur_task)); if (self_in == cur_task) { mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("can't cancel self")); } // If Task waits on another task then forward the cancel to the one it's waiting on. while (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(self->data)), MP_OBJ_FROM_PTR(&task_type))) { self = MP_OBJ_TO_PTR(self->data); } mp_obj_t _task_queue = mp_obj_dict_get(uasyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR__task_queue)); // Reschedule Task as a cancelled task. mp_obj_t dest[3]; mp_load_method_maybe(self->data, MP_QSTR_remove, dest); if (dest[0] != MP_OBJ_NULL) { // Not on the main running queue, remove the task from the queue it's on. dest[2] = MP_OBJ_FROM_PTR(self); mp_call_method_n_kw(1, 0, dest); // _task_queue.push_head(self) dest[0] = _task_queue; dest[1] = MP_OBJ_FROM_PTR(self); task_queue_push_sorted(2, dest); } else if (ticks_diff(self->ph_key, ticks()) > 0) { // On the main running queue but scheduled in the future, so bring it forward to now. // _task_queue.remove(self) task_queue_remove(_task_queue, MP_OBJ_FROM_PTR(self)); // _task_queue.push_head(self) dest[0] = _task_queue; dest[1] = MP_OBJ_FROM_PTR(self); task_queue_push_sorted(2, dest); } self->data = mp_obj_dict_get(uasyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR_CancelledError)); return mp_const_true; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(task_cancel_obj, task_cancel); STATIC void task_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in); if (dest[0] == MP_OBJ_NULL) { // Load if (attr == MP_QSTR_coro) { dest[0] = self->coro; } else if (attr == MP_QSTR_data) { dest[0] = self->data; } else if (attr == MP_QSTR_state) { dest[0] = self->state; } else if (attr == MP_QSTR_done) { dest[0] = MP_OBJ_FROM_PTR(&task_done_obj); dest[1] = self_in; } else if (attr == MP_QSTR_cancel) { dest[0] = MP_OBJ_FROM_PTR(&task_cancel_obj); dest[1] = self_in; } else if (attr == MP_QSTR_ph_key) { dest[0] = self->ph_key; } } else if (dest[1] != MP_OBJ_NULL) { // Store if (attr == MP_QSTR_data) { self->data = dest[1]; dest[0] = MP_OBJ_NULL; } else if (attr == MP_QSTR_state) { self->state = dest[1]; dest[0] = MP_OBJ_NULL; } } } STATIC mp_obj_t task_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { (void)iter_buf; mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in); if (TASK_IS_DONE(self)) { // Signal that the completed-task has been await'ed on. self->state = TASK_STATE_DONE_WAS_WAITED_ON; } else if (self->state == TASK_STATE_RUNNING_NOT_WAITED_ON) { // Allocate the waiting queue. self->state = task_queue_make_new(&task_queue_type, 0, 0, NULL); } return self_in; } STATIC mp_obj_t task_iternext(mp_obj_t self_in) { mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in); if (TASK_IS_DONE(self)) { // Task finished, raise return value to caller so it can continue. nlr_raise(self->data); } else { // Put calling task on waiting queue. mp_obj_t cur_task = mp_obj_dict_get(uasyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR_cur_task)); mp_obj_t args[2] = { self->state, cur_task }; task_queue_push_sorted(2, args); // Set calling task's data to this task that it waits on, to double-link it. ((mp_obj_task_t *)MP_OBJ_TO_PTR(cur_task))->data = self_in; } return mp_const_none; } STATIC const mp_obj_type_t task_type = { { &mp_type_type }, .name = MP_QSTR_Task, .make_new = task_make_new, .attr = task_attr, .getiter = task_getiter, .iternext = task_iternext, }; /******************************************************************************/ // C-level uasyncio module STATIC const mp_rom_map_elem_t mp_module_uasyncio_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__uasyncio) }, { MP_ROM_QSTR(MP_QSTR_TaskQueue), MP_ROM_PTR(&task_queue_type) }, { MP_ROM_QSTR(MP_QSTR_Task), MP_ROM_PTR(&task_type) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_uasyncio_globals, mp_module_uasyncio_globals_table); const mp_obj_module_t mp_module_uasyncio = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_uasyncio_globals, }; #endif // MICROPY_PY_UASYNCIO
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduasyncio.c
C
apache-2.0
12,021
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <assert.h> #include <string.h> #include "py/runtime.h" #include "py/binary.h" #if MICROPY_PY_UBINASCII STATIC mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) { // First argument is the data to convert. // Second argument is an optional separator to be used between values. const char *sep = NULL; mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); // Code below assumes non-zero buffer length when computing size with // separator, so handle the zero-length case here. if (bufinfo.len == 0) { return mp_const_empty_bytes; } vstr_t vstr; size_t out_len = bufinfo.len * 2; if (n_args > 1) { // 1-char separator between hex numbers out_len += bufinfo.len - 1; sep = mp_obj_str_get_str(args[1]); } vstr_init_len(&vstr, out_len); byte *in = bufinfo.buf, *out = (byte *)vstr.buf; for (mp_uint_t i = bufinfo.len; i--;) { byte d = (*in >> 4); if (d > 9) { d += 'a' - '9' - 1; } *out++ = d + '0'; d = (*in++ & 0xf); if (d > 9) { d += 'a' - '9' - 1; } *out++ = d + '0'; if (sep != NULL && i != 0) { *out++ = *sep; } } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_binascii_hexlify_obj, 1, 2, mod_binascii_hexlify); STATIC mp_obj_t mod_binascii_unhexlify(mp_obj_t data) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); if ((bufinfo.len & 1) != 0) { mp_raise_ValueError(MP_ERROR_TEXT("odd-length string")); } vstr_t vstr; vstr_init_len(&vstr, bufinfo.len / 2); byte *in = bufinfo.buf, *out = (byte *)vstr.buf; byte hex_byte = 0; for (mp_uint_t i = bufinfo.len; i--;) { byte hex_ch = *in++; if (unichar_isxdigit(hex_ch)) { hex_byte += unichar_xdigit_value(hex_ch); } else { mp_raise_ValueError(MP_ERROR_TEXT("non-hex digit found")); } if (i & 1) { hex_byte <<= 4; } else { *out++ = hex_byte; hex_byte = 0; } } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_unhexlify_obj, mod_binascii_unhexlify); // If ch is a character in the base64 alphabet, and is not a pad character, then // the corresponding integer between 0 and 63, inclusively, is returned. // Otherwise, -1 is returned. static int mod_binascii_sextet(byte ch) { if (ch >= 'A' && ch <= 'Z') { return ch - 'A'; } else if (ch >= 'a' && ch <= 'z') { return ch - 'a' + 26; } else if (ch >= '0' && ch <= '9') { return ch - '0' + 52; } else if (ch == '+') { return 62; } else if (ch == '/') { return 63; } else { return -1; } } STATIC mp_obj_t mod_binascii_a2b_base64(mp_obj_t data) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); byte *in = bufinfo.buf; vstr_t vstr; vstr_init(&vstr, (bufinfo.len / 4) * 3 + 1); // Potentially over-allocate byte *out = (byte *)vstr.buf; uint shift = 0; int nbits = 0; // Number of meaningful bits in shift bool hadpad = false; // Had a pad character since last valid character for (size_t i = 0; i < bufinfo.len; i++) { if (in[i] == '=') { if ((nbits == 2) || ((nbits == 4) && hadpad)) { nbits = 0; break; } hadpad = true; } int sextet = mod_binascii_sextet(in[i]); if (sextet == -1) { continue; } hadpad = false; shift = (shift << 6) | sextet; nbits += 6; if (nbits >= 8) { nbits -= 8; out[vstr.len++] = (shift >> nbits) & 0xFF; } } if (nbits) { mp_raise_ValueError(MP_ERROR_TEXT("incorrect padding")); } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_a2b_base64_obj, mod_binascii_a2b_base64); STATIC mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); vstr_t vstr; vstr_init_len(&vstr, ((bufinfo.len != 0) ? (((bufinfo.len - 1) / 3) + 1) * 4 : 0) + 1); // First pass, we convert input buffer to numeric base 64 values byte *in = bufinfo.buf, *out = (byte *)vstr.buf; mp_uint_t i; for (i = bufinfo.len; i >= 3; i -= 3) { *out++ = (in[0] & 0xFC) >> 2; *out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4; *out++ = (in[1] & 0x0F) << 2 | (in[2] & 0xC0) >> 6; *out++ = in[2] & 0x3F; in += 3; } if (i != 0) { *out++ = (in[0] & 0xFC) >> 2; if (i == 2) { *out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4; *out++ = (in[1] & 0x0F) << 2; } else { *out++ = (in[0] & 0x03) << 4; *out++ = 64; } *out = 64; } // Second pass, we convert number base 64 values to actual base64 ascii encoding out = (byte *)vstr.buf; for (mp_uint_t j = vstr.len - 1; j--;) { if (*out < 26) { *out += 'A'; } else if (*out < 52) { *out += 'a' - 26; } else if (*out < 62) { *out += '0' - 52; } else if (*out == 62) { *out = '+'; } else if (*out == 63) { *out = '/'; } else { *out = '='; } out++; } *out = '\n'; return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_b2a_base64_obj, mod_binascii_b2a_base64); #if MICROPY_PY_UBINASCII_CRC32 #include "lib/uzlib/tinf.h" STATIC mp_obj_t mod_binascii_crc32(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); uint32_t crc = (n_args > 1) ? mp_obj_get_int_truncated(args[1]) : 0; crc = uzlib_crc32(bufinfo.buf, bufinfo.len, crc ^ 0xffffffff); return mp_obj_new_int_from_uint(crc ^ 0xffffffff); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_binascii_crc32_obj, 1, 2, mod_binascii_crc32); #endif STATIC const mp_rom_map_elem_t mp_module_binascii_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ubinascii) }, { MP_ROM_QSTR(MP_QSTR_hexlify), MP_ROM_PTR(&mod_binascii_hexlify_obj) }, { MP_ROM_QSTR(MP_QSTR_unhexlify), MP_ROM_PTR(&mod_binascii_unhexlify_obj) }, { MP_ROM_QSTR(MP_QSTR_a2b_base64), MP_ROM_PTR(&mod_binascii_a2b_base64_obj) }, { MP_ROM_QSTR(MP_QSTR_b2a_base64), MP_ROM_PTR(&mod_binascii_b2a_base64_obj) }, #if MICROPY_PY_UBINASCII_CRC32 { MP_ROM_QSTR(MP_QSTR_crc32), MP_ROM_PTR(&mod_binascii_crc32_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_binascii_globals, mp_module_binascii_globals_table); const mp_obj_module_t mp_module_ubinascii = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_binascii_globals, }; #endif // MICROPY_PY_UBINASCII
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modubinascii.c
C
apache-2.0
8,458
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017-2018 Paul Sokolovsky * Copyright (c) 2018 Yonatan Goldschmidt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_PY_UCRYPTOLIB #include <assert.h> #include <string.h> #include "py/runtime.h" // This module implements crypto ciphers API, roughly following // https://www.python.org/dev/peps/pep-0272/ . Exact implementation // of PEP 272 can be made with a simple wrapper which adds all the // needed boilerplate. // values follow PEP 272 enum { UCRYPTOLIB_MODE_ECB = 1, UCRYPTOLIB_MODE_CBC = 2, UCRYPTOLIB_MODE_CTR = 6, }; struct ctr_params { // counter is the IV of the AES context. size_t offset; // in encrypted_counter // encrypted counter uint8_t encrypted_counter[16]; }; #if MICROPY_SSL_AXTLS #include "lib/axtls/crypto/crypto.h" #define AES_CTX_IMPL AES_CTX #endif #if MICROPY_SSL_MBEDTLS #include <mbedtls/aes.h> // we can't run mbedtls AES key schedule until we know whether we're used for encrypt or decrypt. // therefore, we store the key & keysize and on the first call to encrypt/decrypt we override them // with the mbedtls_aes_context, as they are not longer required. (this is done to save space) struct mbedtls_aes_ctx_with_key { union { mbedtls_aes_context mbedtls_ctx; struct { uint8_t key[32]; uint8_t keysize; } init_data; } u; unsigned char iv[16]; }; #define AES_CTX_IMPL struct mbedtls_aes_ctx_with_key #endif typedef struct _mp_obj_aes_t { mp_obj_base_t base; AES_CTX_IMPL ctx; uint8_t block_mode : 6; #define AES_KEYTYPE_NONE 0 #define AES_KEYTYPE_ENC 1 #define AES_KEYTYPE_DEC 2 uint8_t key_type : 2; } mp_obj_aes_t; static inline bool is_ctr_mode(int block_mode) { #if MICROPY_PY_UCRYPTOLIB_CTR return block_mode == UCRYPTOLIB_MODE_CTR; #else return false; #endif } static inline struct ctr_params *ctr_params_from_aes(mp_obj_aes_t *o) { // ctr_params follows aes object struct return (struct ctr_params *)&o[1]; } #if MICROPY_SSL_AXTLS STATIC void aes_initial_set_key_impl(AES_CTX_IMPL *ctx, const uint8_t *key, size_t keysize, const uint8_t iv[16]) { assert(16 == keysize || 32 == keysize); AES_set_key(ctx, key, iv, (16 == keysize) ? AES_MODE_128 : AES_MODE_256); } STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) { if (!encrypt) { AES_convert_key(ctx); } } STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) { memcpy(out, in, 16); // We assume that out (vstr.buf or given output buffer) is uint32_t aligned uint32_t *p = (uint32_t *)out; // axTLS likes it weird and complicated with byteswaps for (int i = 0; i < 4; i++) { p[i] = MP_HTOBE32(p[i]); } if (encrypt) { AES_encrypt(ctx, p); } else { AES_decrypt(ctx, p); } for (int i = 0; i < 4; i++) { p[i] = MP_BE32TOH(p[i]); } } STATIC void aes_process_cbc_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, bool encrypt) { if (encrypt) { AES_cbc_encrypt(ctx, in, out, in_len); } else { AES_cbc_decrypt(ctx, in, out, in_len); } } #if MICROPY_PY_UCRYPTOLIB_CTR // axTLS doesn't have CTR support out of the box. This implements the counter part using the ECB primitive. STATIC void aes_process_ctr_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, struct ctr_params *ctr_params) { size_t n = ctr_params->offset; uint8_t *const counter = ctx->iv; while (in_len--) { if (n == 0) { aes_process_ecb_impl(ctx, counter, ctr_params->encrypted_counter, true); // increment the 128-bit counter for (int i = 15; i >= 0; --i) { if (++counter[i] != 0) { break; } } } *out++ = *in++ ^ ctr_params->encrypted_counter[n]; n = (n + 1) & 0xf; } ctr_params->offset = n; } #endif #endif #if MICROPY_SSL_MBEDTLS STATIC void aes_initial_set_key_impl(AES_CTX_IMPL *ctx, const uint8_t *key, size_t keysize, const uint8_t iv[16]) { ctx->u.init_data.keysize = keysize; memcpy(ctx->u.init_data.key, key, keysize); if (NULL != iv) { memcpy(ctx->iv, iv, sizeof(ctx->iv)); } } STATIC void aes_final_set_key_impl(AES_CTX_IMPL *ctx, bool encrypt) { // first, copy key aside uint8_t key[32]; uint8_t keysize = ctx->u.init_data.keysize; memcpy(key, ctx->u.init_data.key, keysize); // now, override key with the mbedtls context object mbedtls_aes_init(&ctx->u.mbedtls_ctx); // setkey call will succeed, we've already checked the keysize earlier. assert(16 == keysize || 32 == keysize); if (encrypt) { mbedtls_aes_setkey_enc(&ctx->u.mbedtls_ctx, key, keysize * 8); } else { mbedtls_aes_setkey_dec(&ctx->u.mbedtls_ctx, key, keysize * 8); } } STATIC void aes_process_ecb_impl(AES_CTX_IMPL *ctx, const uint8_t in[16], uint8_t out[16], bool encrypt) { mbedtls_aes_crypt_ecb(&ctx->u.mbedtls_ctx, encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT, in, out); } STATIC void aes_process_cbc_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, bool encrypt) { mbedtls_aes_crypt_cbc(&ctx->u.mbedtls_ctx, encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT, in_len, ctx->iv, in, out); } #if MICROPY_PY_UCRYPTOLIB_CTR STATIC void aes_process_ctr_impl(AES_CTX_IMPL *ctx, const uint8_t *in, uint8_t *out, size_t in_len, struct ctr_params *ctr_params) { mbedtls_aes_crypt_ctr(&ctx->u.mbedtls_ctx, in_len, &ctr_params->offset, ctx->iv, ctr_params->encrypted_counter, in, out); } #endif #endif STATIC mp_obj_t ucryptolib_aes_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 2, 3, false); const mp_int_t block_mode = mp_obj_get_int(args[1]); switch (block_mode) { case UCRYPTOLIB_MODE_ECB: case UCRYPTOLIB_MODE_CBC: #if MICROPY_PY_UCRYPTOLIB_CTR case UCRYPTOLIB_MODE_CTR: #endif break; default: mp_raise_ValueError(MP_ERROR_TEXT("mode")); } mp_obj_aes_t *o = m_new_obj_var(mp_obj_aes_t, struct ctr_params, !!is_ctr_mode(block_mode)); o->base.type = type; o->block_mode = block_mode; o->key_type = AES_KEYTYPE_NONE; mp_buffer_info_t keyinfo; mp_get_buffer_raise(args[0], &keyinfo, MP_BUFFER_READ); if (32 != keyinfo.len && 16 != keyinfo.len) { mp_raise_ValueError(MP_ERROR_TEXT("key")); } mp_buffer_info_t ivinfo; ivinfo.buf = NULL; if (n_args > 2 && args[2] != mp_const_none) { mp_get_buffer_raise(args[2], &ivinfo, MP_BUFFER_READ); if (16 != ivinfo.len) { mp_raise_ValueError(MP_ERROR_TEXT("IV")); } } else if (o->block_mode == UCRYPTOLIB_MODE_CBC || is_ctr_mode(o->block_mode)) { mp_raise_ValueError(MP_ERROR_TEXT("IV")); } if (is_ctr_mode(block_mode)) { ctr_params_from_aes(o)->offset = 0; } aes_initial_set_key_impl(&o->ctx, keyinfo.buf, keyinfo.len, ivinfo.buf); return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t aes_process(size_t n_args, const mp_obj_t *args, bool encrypt) { mp_obj_aes_t *self = MP_OBJ_TO_PTR(args[0]); mp_obj_t in_buf = args[1]; mp_obj_t out_buf = MP_OBJ_NULL; if (n_args > 2) { out_buf = args[2]; } mp_buffer_info_t in_bufinfo; mp_get_buffer_raise(in_buf, &in_bufinfo, MP_BUFFER_READ); if (!is_ctr_mode(self->block_mode) && in_bufinfo.len % 16 != 0) { mp_raise_ValueError(MP_ERROR_TEXT("blksize % 16")); } vstr_t vstr; mp_buffer_info_t out_bufinfo; uint8_t *out_buf_ptr; if (out_buf != MP_OBJ_NULL) { mp_get_buffer_raise(out_buf, &out_bufinfo, MP_BUFFER_WRITE); if (out_bufinfo.len < in_bufinfo.len) { mp_raise_ValueError(MP_ERROR_TEXT("output too small")); } out_buf_ptr = out_bufinfo.buf; } else { vstr_init_len(&vstr, in_bufinfo.len); out_buf_ptr = (uint8_t *)vstr.buf; } if (AES_KEYTYPE_NONE == self->key_type) { // always set key for encryption if CTR mode. const bool encrypt_mode = encrypt || is_ctr_mode(self->block_mode); aes_final_set_key_impl(&self->ctx, encrypt_mode); self->key_type = encrypt ? AES_KEYTYPE_ENC : AES_KEYTYPE_DEC; } else { if ((encrypt && self->key_type == AES_KEYTYPE_DEC) || (!encrypt && self->key_type == AES_KEYTYPE_ENC)) { mp_raise_ValueError(MP_ERROR_TEXT("can't encrypt & decrypt")); } } switch (self->block_mode) { case UCRYPTOLIB_MODE_ECB: { uint8_t *in = in_bufinfo.buf, *out = out_buf_ptr; uint8_t *top = in + in_bufinfo.len; for (; in < top; in += 16, out += 16) { aes_process_ecb_impl(&self->ctx, in, out, encrypt); } break; } case UCRYPTOLIB_MODE_CBC: aes_process_cbc_impl(&self->ctx, in_bufinfo.buf, out_buf_ptr, in_bufinfo.len, encrypt); break; #if MICROPY_PY_UCRYPTOLIB_CTR case UCRYPTOLIB_MODE_CTR: aes_process_ctr_impl(&self->ctx, in_bufinfo.buf, out_buf_ptr, in_bufinfo.len, ctr_params_from_aes(self)); break; #endif } if (out_buf != MP_OBJ_NULL) { return out_buf; } return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC mp_obj_t ucryptolib_aes_encrypt(size_t n_args, const mp_obj_t *args) { return aes_process(n_args, args, true); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_encrypt_obj, 2, 3, ucryptolib_aes_encrypt); STATIC mp_obj_t ucryptolib_aes_decrypt(size_t n_args, const mp_obj_t *args) { return aes_process(n_args, args, false); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucryptolib_aes_decrypt_obj, 2, 3, ucryptolib_aes_decrypt); STATIC const mp_rom_map_elem_t ucryptolib_aes_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_encrypt), MP_ROM_PTR(&ucryptolib_aes_encrypt_obj) }, { MP_ROM_QSTR(MP_QSTR_decrypt), MP_ROM_PTR(&ucryptolib_aes_decrypt_obj) }, }; STATIC MP_DEFINE_CONST_DICT(ucryptolib_aes_locals_dict, ucryptolib_aes_locals_dict_table); STATIC const mp_obj_type_t ucryptolib_aes_type = { { &mp_type_type }, .name = MP_QSTR_aes, .make_new = ucryptolib_aes_make_new, .locals_dict = (void *)&ucryptolib_aes_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_ucryptolib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucryptolib) }, { MP_ROM_QSTR(MP_QSTR_aes), MP_ROM_PTR(&ucryptolib_aes_type) }, #if MICROPY_PY_UCRYPTOLIB_CONSTS { MP_ROM_QSTR(MP_QSTR_MODE_ECB), MP_ROM_INT(UCRYPTOLIB_MODE_ECB) }, { MP_ROM_QSTR(MP_QSTR_MODE_CBC), MP_ROM_INT(UCRYPTOLIB_MODE_CBC) }, #if MICROPY_PY_UCRYPTOLIB_CTR { MP_ROM_QSTR(MP_QSTR_MODE_CTR), MP_ROM_INT(UCRYPTOLIB_MODE_CTR) }, #endif #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_ucryptolib_globals, mp_module_ucryptolib_globals_table); const mp_obj_module_t mp_module_ucryptolib = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_ucryptolib_globals, }; #endif // MICROPY_PY_UCRYPTOLIB
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moducryptolib.c
C
apache-2.0
12,522
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014-2018 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <assert.h> #include <string.h> #include <stdint.h> #include "py/runtime.h" #include "py/objtuple.h" #include "py/binary.h" #if MICROPY_PY_UCTYPES // The uctypes module allows defining the layout of a raw data structure (using // terms of the C language), and then access memory buffers using this definition. // The module also provides convenience functions to access memory buffers // contained in Python objects or wrap memory buffers in Python objects. #define LAYOUT_LITTLE_ENDIAN (0) #define LAYOUT_BIG_ENDIAN (1) #define LAYOUT_NATIVE (2) #define VAL_TYPE_BITS 4 #define BITF_LEN_BITS 5 #define BITF_OFF_BITS 5 #define OFFSET_BITS 17 #define LEN_BITS (OFFSET_BITS + BITF_OFF_BITS) #if VAL_TYPE_BITS + BITF_LEN_BITS + BITF_OFF_BITS + OFFSET_BITS != 31 #error Invalid encoding field length #endif enum { UINT8, INT8, UINT16, INT16, UINT32, INT32, UINT64, INT64, BFUINT8, BFINT8, BFUINT16, BFINT16, BFUINT32, BFINT32, FLOAT32, FLOAT64, }; #define AGG_TYPE_BITS 2 enum { STRUCT, PTR, ARRAY, }; // Here we need to set sign bit right #define TYPE2SMALLINT(x, nbits) ((((int)x) << (32 - nbits)) >> 1) #define GET_TYPE(x, nbits) (((x) >> (31 - nbits)) & ((1 << nbits) - 1)) // Bit 0 is "is_signed" #define GET_SCALAR_SIZE(val_type) (1 << ((val_type) >> 1)) #define VALUE_MASK(type_nbits) ~((int)0x80000000 >> type_nbits) #define IS_SCALAR_ARRAY(tuple_desc) ((tuple_desc)->len == 2) // We cannot apply the below to INT8, as their range [-128, 127] #define IS_SCALAR_ARRAY_OF_BYTES(tuple_desc) (GET_TYPE(MP_OBJ_SMALL_INT_VALUE((tuple_desc)->items[1]), VAL_TYPE_BITS) == UINT8) // "struct" in uctypes context means "structural", i.e. aggregate, type. STATIC const mp_obj_type_t uctypes_struct_type; typedef struct _mp_obj_uctypes_struct_t { mp_obj_base_t base; mp_obj_t desc; byte *addr; uint32_t flags; } mp_obj_uctypes_struct_t; STATIC NORETURN void syntax_error(void) { mp_raise_TypeError(MP_ERROR_TEXT("syntax error in uctypes descriptor")); } STATIC mp_obj_t uctypes_struct_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 2, 3, false); mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = type; o->addr = (void *)(uintptr_t)mp_obj_int_get_truncated(args[0]); o->desc = args[1]; o->flags = LAYOUT_NATIVE; if (n_args == 3) { o->flags = mp_obj_get_int(args[2]); } return MP_OBJ_FROM_PTR(o); } STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); const char *typen = "unk"; if (mp_obj_is_dict_or_ordereddict(self->desc)) { typen = "STRUCT"; } else if (mp_obj_is_type(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); switch (agg_type) { case PTR: typen = "PTR"; break; case ARRAY: typen = "ARRAY"; break; } } else { typen = "ERROR"; } mp_printf(print, "<struct %s %p>", typen, self->addr); } // Get size of any type descriptor STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size); // Get size of scalar type descriptor static inline mp_uint_t uctypes_struct_scalar_size(int val_type) { if (val_type == FLOAT32) { return 4; } else { return GET_SCALAR_SIZE(val_type & 7); } } // Get size of aggregate type descriptor STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_uint_t *max_field_size) { mp_uint_t total_size = 0; mp_int_t offset_ = MP_OBJ_SMALL_INT_VALUE(t->items[0]); mp_uint_t agg_type = GET_TYPE(offset_, AGG_TYPE_BITS); switch (agg_type) { case STRUCT: return uctypes_struct_size(t->items[1], layout_type, max_field_size); case PTR: if (sizeof(void *) > *max_field_size) { *max_field_size = sizeof(void *); } return sizeof(void *); case ARRAY: { mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]); uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS); arr_sz &= VALUE_MASK(VAL_TYPE_BITS); mp_uint_t item_s; if (t->len == 2) { // Elements of array are scalar item_s = uctypes_struct_scalar_size(val_type); if (item_s > *max_field_size) { *max_field_size = item_s; } } else { // Elements of array are aggregates item_s = uctypes_struct_size(t->items[2], layout_type, max_field_size); } return item_s * arr_sz; } default: assert(0); } return total_size; } STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) { if (!mp_obj_is_dict_or_ordereddict(desc_in)) { if (mp_obj_is_type(desc_in, &mp_type_tuple)) { return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); } else if (mp_obj_is_small_int(desc_in)) { // We allow sizeof on both type definitions and structures/structure fields, // but scalar structure field is lowered into native Python int, so all // type info is lost. So, we cannot say if it's scalar type description, // or such lowered scalar. mp_raise_TypeError(MP_ERROR_TEXT("can't unambiguously get sizeof scalar")); } syntax_error(); } mp_obj_dict_t *d = MP_OBJ_TO_PTR(desc_in); mp_uint_t total_size = 0; for (mp_uint_t i = 0; i < d->map.alloc; i++) { if (mp_map_slot_is_filled(&d->map, i)) { mp_obj_t v = d->map.table[i].value; if (mp_obj_is_small_int(v)) { mp_uint_t offset = MP_OBJ_SMALL_INT_VALUE(v); mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS); offset &= VALUE_MASK(VAL_TYPE_BITS); if (val_type >= BFUINT8 && val_type <= BFINT32) { offset &= (1 << OFFSET_BITS) - 1; } mp_uint_t s = uctypes_struct_scalar_size(val_type); if (s > *max_field_size) { *max_field_size = s; } if (offset + s > total_size) { total_size = offset + s; } } else { if (!mp_obj_is_type(v, &mp_type_tuple)) { syntax_error(); } mp_obj_tuple_t *t = MP_OBJ_TO_PTR(v); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); offset &= VALUE_MASK(AGG_TYPE_BITS); mp_uint_t s = uctypes_struct_agg_size(t, layout_type, max_field_size); if (offset + s > total_size) { total_size = offset + s; } } } } // Round size up to alignment of biggest field if (layout_type == LAYOUT_NATIVE) { total_size = (total_size + *max_field_size - 1) & ~(*max_field_size - 1); } return total_size; } STATIC mp_obj_t uctypes_struct_sizeof(size_t n_args, const mp_obj_t *args) { mp_obj_t obj_in = args[0]; mp_uint_t max_field_size = 0; if (mp_obj_is_type(obj_in, &mp_type_bytearray)) { return mp_obj_len(obj_in); } int layout_type = LAYOUT_NATIVE; // We can apply sizeof either to structure definition (a dict) // or to instantiated structure if (mp_obj_is_type(obj_in, &uctypes_struct_type)) { if (n_args != 1) { mp_raise_TypeError(NULL); } // Extract structure definition mp_obj_uctypes_struct_t *obj = MP_OBJ_TO_PTR(obj_in); obj_in = obj->desc; layout_type = obj->flags; } else { if (n_args == 2) { layout_type = mp_obj_get_int(args[1]); } } mp_uint_t size = uctypes_struct_size(obj_in, layout_type, &max_field_size); return MP_OBJ_NEW_SMALL_INT(size); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(uctypes_struct_sizeof_obj, 1, 2, uctypes_struct_sizeof); static inline mp_obj_t get_unaligned(uint val_type, byte *p, int big_endian) { char struct_type = big_endian ? '>' : '<'; static const char type2char[16] = "BbHhIiQq------fd"; return mp_binary_get_val(struct_type, type2char[val_type], p, &p); } static inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_t val) { char struct_type = big_endian ? '>' : '<'; static const char type2char[16] = "BbHhIiQq------fd"; mp_binary_set_val(struct_type, type2char[val_type], val, p, &p); } static inline mp_uint_t get_aligned_basic(uint val_type, void *p) { switch (val_type) { case UINT8: return *(uint8_t *)p; case UINT16: return *(uint16_t *)p; case UINT32: return *(uint32_t *)p; } assert(0); return 0; } static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) { switch (val_type) { case UINT8: *(uint8_t *)p = (uint8_t)v; return; case UINT16: *(uint16_t *)p = (uint16_t)v; return; case UINT32: *(uint32_t *)p = (uint32_t)v; return; } assert(0); } STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) { switch (val_type) { case UINT8: return MP_OBJ_NEW_SMALL_INT(((uint8_t *)p)[index]); case INT8: return MP_OBJ_NEW_SMALL_INT(((int8_t *)p)[index]); case UINT16: return MP_OBJ_NEW_SMALL_INT(((uint16_t *)p)[index]); case INT16: return MP_OBJ_NEW_SMALL_INT(((int16_t *)p)[index]); case UINT32: return mp_obj_new_int_from_uint(((uint32_t *)p)[index]); case INT32: return mp_obj_new_int(((int32_t *)p)[index]); case UINT64: return mp_obj_new_int_from_ull(((uint64_t *)p)[index]); case INT64: return mp_obj_new_int_from_ll(((int64_t *)p)[index]); #if MICROPY_PY_BUILTINS_FLOAT case FLOAT32: return mp_obj_new_float_from_f(((float *)p)[index]); case FLOAT64: return mp_obj_new_float_from_d(((double *)p)[index]); #endif default: assert(0); return MP_OBJ_NULL; } } STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { #if MICROPY_PY_BUILTINS_FLOAT if (val_type == FLOAT32 || val_type == FLOAT64) { if (val_type == FLOAT32) { ((float *)p)[index] = mp_obj_get_float_to_f(val); } else { ((double *)p)[index] = mp_obj_get_float_to_d(val); } return; } #endif mp_int_t v = mp_obj_get_int_truncated(val); switch (val_type) { case UINT8: ((uint8_t *)p)[index] = (uint8_t)v; return; case INT8: ((int8_t *)p)[index] = (int8_t)v; return; case UINT16: ((uint16_t *)p)[index] = (uint16_t)v; return; case INT16: ((int16_t *)p)[index] = (int16_t)v; return; case UINT32: ((uint32_t *)p)[index] = (uint32_t)v; return; case INT32: ((int32_t *)p)[index] = (int32_t)v; return; case INT64: case UINT64: if (sizeof(mp_int_t) == 8) { ((uint64_t *)p)[index] = (uint64_t)v; } else { // TODO: Doesn't offer atomic store semantics, but should at least try set_unaligned(val_type, (void *)&((uint64_t *)p)[index], MP_ENDIANNESS_BIG, val); } return; default: assert(0); } } STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set_val) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); if (!mp_obj_is_dict_or_ordereddict(self->desc)) { mp_raise_TypeError(MP_ERROR_TEXT("struct: no fields")); } mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr)); if (mp_obj_is_small_int(deref)) { mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(deref); mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS); offset &= VALUE_MASK(VAL_TYPE_BITS); if (val_type <= INT64 || val_type == FLOAT32 || val_type == FLOAT64) { if (self->flags == LAYOUT_NATIVE) { if (set_val == MP_OBJ_NULL) { return get_aligned(val_type, self->addr + offset, 0); } else { set_aligned(val_type, self->addr + offset, 0, set_val); return set_val; // just !MP_OBJ_NULL } } else { if (set_val == MP_OBJ_NULL) { return get_unaligned(val_type, self->addr + offset, self->flags); } else { set_unaligned(val_type, self->addr + offset, self->flags, set_val); return set_val; // just !MP_OBJ_NULL } } } else if (val_type >= BFUINT8 && val_type <= BFINT32) { uint bit_offset = (offset >> OFFSET_BITS) & 31; uint bit_len = (offset >> LEN_BITS) & 31; offset &= (1 << OFFSET_BITS) - 1; mp_uint_t val; if (self->flags == LAYOUT_NATIVE) { val = get_aligned_basic(val_type & 6, self->addr + offset); } else { val = mp_binary_get_int(GET_SCALAR_SIZE(val_type & 7), val_type & 1, self->flags, self->addr + offset); } if (set_val == MP_OBJ_NULL) { val >>= bit_offset; val &= (1 << bit_len) - 1; // TODO: signed assert((val_type & 1) == 0); return mp_obj_new_int(val); } else { mp_uint_t set_val_int = (mp_uint_t)mp_obj_get_int(set_val); mp_uint_t mask = (1 << bit_len) - 1; set_val_int &= mask; set_val_int <<= bit_offset; mask <<= bit_offset; val = (val & ~mask) | set_val_int; if (self->flags == LAYOUT_NATIVE) { set_aligned_basic(val_type & 6, self->addr + offset, val); } else { mp_binary_set_int(GET_SCALAR_SIZE(val_type & 7), self->flags == LAYOUT_BIG_ENDIAN, self->addr + offset, val); } return set_val; // just !MP_OBJ_NULL } } assert(0); return MP_OBJ_NULL; } if (!mp_obj_is_type(deref, &mp_type_tuple)) { syntax_error(); } if (set_val != MP_OBJ_NULL) { // Cannot assign to aggregate syntax_error(); } mp_obj_tuple_t *sub = MP_OBJ_TO_PTR(deref); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(sub->items[0]); mp_uint_t agg_type = GET_TYPE(offset, AGG_TYPE_BITS); offset &= VALUE_MASK(AGG_TYPE_BITS); switch (agg_type) { case STRUCT: { mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = &uctypes_struct_type; o->desc = sub->items[1]; o->addr = self->addr + offset; o->flags = self->flags; return MP_OBJ_FROM_PTR(o); } case ARRAY: { mp_uint_t dummy; if (IS_SCALAR_ARRAY(sub) && IS_SCALAR_ARRAY_OF_BYTES(sub)) { return mp_obj_new_bytearray_by_ref(uctypes_struct_agg_size(sub, self->flags, &dummy), self->addr + offset); } // Fall thru to return uctypes struct object MP_FALLTHROUGH } case PTR: { mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = &uctypes_struct_type; o->desc = MP_OBJ_FROM_PTR(sub); o->addr = self->addr + offset; o->flags = self->flags; return MP_OBJ_FROM_PTR(o); } } // Should be unreachable once all cases are handled return MP_OBJ_NULL; } STATIC void uctypes_struct_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // load attribute mp_obj_t val = uctypes_struct_attr_op(self_in, attr, MP_OBJ_NULL); dest[0] = val; } else { // delete/store attribute if (uctypes_struct_attr_op(self_in, attr, dest[1]) != MP_OBJ_NULL) { dest[0] = MP_OBJ_NULL; // indicate success } } } STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); if (value == MP_OBJ_NULL) { // delete return MP_OBJ_NULL; // op not supported } else { // load / store if (!mp_obj_is_type(self->desc, &mp_type_tuple)) { mp_raise_TypeError(MP_ERROR_TEXT("struct: can't index")); } mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); mp_int_t index = MP_OBJ_SMALL_INT_VALUE(index_in); if (agg_type == ARRAY) { mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]); uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS); arr_sz &= VALUE_MASK(VAL_TYPE_BITS); if (index >= arr_sz) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("struct: index out of range")); } if (t->len == 2) { // array of scalars if (self->flags == LAYOUT_NATIVE) { if (value == MP_OBJ_SENTINEL) { return get_aligned(val_type, self->addr, index); } else { set_aligned(val_type, self->addr, index, value); return value; // just !MP_OBJ_NULL } } else { byte *p = self->addr + uctypes_struct_scalar_size(val_type) * index; if (value == MP_OBJ_SENTINEL) { return get_unaligned(val_type, p, self->flags); } else { set_unaligned(val_type, p, self->flags, value); return value; // just !MP_OBJ_NULL } } } else if (value == MP_OBJ_SENTINEL) { mp_uint_t dummy = 0; mp_uint_t size = uctypes_struct_size(t->items[2], self->flags, &dummy); mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = &uctypes_struct_type; o->desc = t->items[2]; o->addr = self->addr + size * index; o->flags = self->flags; return MP_OBJ_FROM_PTR(o); } else { return MP_OBJ_NULL; // op not supported } } else if (agg_type == PTR) { byte *p = *(void **)self->addr; if (mp_obj_is_small_int(t->items[1])) { uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS); return get_aligned(val_type, p, index); } else { mp_uint_t dummy = 0; mp_uint_t size = uctypes_struct_size(t->items[1], self->flags, &dummy); mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = &uctypes_struct_type; o->desc = t->items[1]; o->addr = p + size * index; o->flags = self->flags; return MP_OBJ_FROM_PTR(o); } } assert(0); return MP_OBJ_NULL; } } STATIC mp_obj_t uctypes_struct_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_INT: if (mp_obj_is_type(self->desc, &mp_type_tuple)) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->desc); mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); if (agg_type == PTR) { byte *p = *(void **)self->addr; return mp_obj_new_int((mp_int_t)(uintptr_t)p); } } MP_FALLTHROUGH default: return MP_OBJ_NULL; // op not supported } } STATIC mp_int_t uctypes_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { (void)flags; mp_obj_uctypes_struct_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t max_field_size = 0; mp_uint_t size = uctypes_struct_size(self->desc, self->flags, &max_field_size); bufinfo->buf = self->addr; bufinfo->len = size; bufinfo->typecode = BYTEARRAY_TYPECODE; return 0; } // addressof() // Return address of object's data (applies to objects providing the buffer interface). STATIC mp_obj_t uctypes_struct_addressof(mp_obj_t buf) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); return mp_obj_new_int((mp_int_t)(uintptr_t)bufinfo.buf); } MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_addressof_obj, uctypes_struct_addressof); // bytearray_at() // Capture memory at given address of given size as bytearray. STATIC mp_obj_t uctypes_struct_bytearray_at(mp_obj_t ptr, mp_obj_t size) { return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr)); } MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytearray_at); // bytes_at() // Capture memory at given address of given size as bytes. STATIC mp_obj_t uctypes_struct_bytes_at(mp_obj_t ptr, mp_obj_t size) { return mp_obj_new_bytes((void *)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size)); } MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytes_at_obj, uctypes_struct_bytes_at); STATIC const mp_obj_type_t uctypes_struct_type = { { &mp_type_type }, .name = MP_QSTR_struct, .print = uctypes_struct_print, .make_new = uctypes_struct_make_new, .attr = uctypes_struct_attr, .subscr = uctypes_struct_subscr, .unary_op = uctypes_struct_unary_op, .buffer_p = { .get_buffer = uctypes_get_buffer }, }; STATIC const mp_rom_map_elem_t mp_module_uctypes_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uctypes) }, { MP_ROM_QSTR(MP_QSTR_struct), MP_ROM_PTR(&uctypes_struct_type) }, { MP_ROM_QSTR(MP_QSTR_sizeof), MP_ROM_PTR(&uctypes_struct_sizeof_obj) }, { MP_ROM_QSTR(MP_QSTR_addressof), MP_ROM_PTR(&uctypes_struct_addressof_obj) }, { MP_ROM_QSTR(MP_QSTR_bytes_at), MP_ROM_PTR(&uctypes_struct_bytes_at_obj) }, { MP_ROM_QSTR(MP_QSTR_bytearray_at), MP_ROM_PTR(&uctypes_struct_bytearray_at_obj) }, { MP_ROM_QSTR(MP_QSTR_NATIVE), MP_ROM_INT(LAYOUT_NATIVE) }, { MP_ROM_QSTR(MP_QSTR_LITTLE_ENDIAN), MP_ROM_INT(LAYOUT_LITTLE_ENDIAN) }, { MP_ROM_QSTR(MP_QSTR_BIG_ENDIAN), MP_ROM_INT(LAYOUT_BIG_ENDIAN) }, { MP_ROM_QSTR(MP_QSTR_VOID), MP_ROM_INT(TYPE2SMALLINT(UINT8, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_UINT8), MP_ROM_INT(TYPE2SMALLINT(UINT8, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_INT8), MP_ROM_INT(TYPE2SMALLINT(INT8, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_UINT16), MP_ROM_INT(TYPE2SMALLINT(UINT16, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_INT16), MP_ROM_INT(TYPE2SMALLINT(INT16, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_UINT32), MP_ROM_INT(TYPE2SMALLINT(UINT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_INT32), MP_ROM_INT(TYPE2SMALLINT(INT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_UINT64), MP_ROM_INT(TYPE2SMALLINT(UINT64, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_INT64), MP_ROM_INT(TYPE2SMALLINT(INT64, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BFUINT8), MP_ROM_INT(TYPE2SMALLINT(BFUINT8, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BFINT8), MP_ROM_INT(TYPE2SMALLINT(BFINT8, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BFUINT16), MP_ROM_INT(TYPE2SMALLINT(BFUINT16, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BFINT16), MP_ROM_INT(TYPE2SMALLINT(BFINT16, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BFUINT32), MP_ROM_INT(TYPE2SMALLINT(BFUINT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BFINT32), MP_ROM_INT(TYPE2SMALLINT(BFINT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_BF_POS), MP_ROM_INT(OFFSET_BITS) }, { MP_ROM_QSTR(MP_QSTR_BF_LEN), MP_ROM_INT(LEN_BITS) }, #if MICROPY_PY_BUILTINS_FLOAT { MP_ROM_QSTR(MP_QSTR_FLOAT32), MP_ROM_INT(TYPE2SMALLINT(FLOAT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_FLOAT64), MP_ROM_INT(TYPE2SMALLINT(FLOAT64, VAL_TYPE_BITS)) }, #endif #if MICROPY_PY_UCTYPES_NATIVE_C_TYPES // C native type aliases. These depend on GCC-compatible predefined // preprocessor macros. #if __SIZEOF_SHORT__ == 2 { MP_ROM_QSTR(MP_QSTR_SHORT), MP_ROM_INT(TYPE2SMALLINT(INT16, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_USHORT), MP_ROM_INT(TYPE2SMALLINT(UINT16, VAL_TYPE_BITS)) }, #endif #if __SIZEOF_INT__ == 4 { MP_ROM_QSTR(MP_QSTR_INT), MP_ROM_INT(TYPE2SMALLINT(INT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_UINT), MP_ROM_INT(TYPE2SMALLINT(UINT32, VAL_TYPE_BITS)) }, #endif #if __SIZEOF_LONG__ == 4 { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT32, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT32, VAL_TYPE_BITS)) }, #elif __SIZEOF_LONG__ == 8 { MP_ROM_QSTR(MP_QSTR_LONG), MP_ROM_INT(TYPE2SMALLINT(INT64, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ULONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, VAL_TYPE_BITS)) }, #endif #if __SIZEOF_LONG_LONG__ == 8 { MP_ROM_QSTR(MP_QSTR_LONGLONG), MP_ROM_INT(TYPE2SMALLINT(INT64, VAL_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ULONGLONG), MP_ROM_INT(TYPE2SMALLINT(UINT64, VAL_TYPE_BITS)) }, #endif #endif // MICROPY_PY_UCTYPES_NATIVE_C_TYPES { MP_ROM_QSTR(MP_QSTR_PTR), MP_ROM_INT(TYPE2SMALLINT(PTR, AGG_TYPE_BITS)) }, { MP_ROM_QSTR(MP_QSTR_ARRAY), MP_ROM_INT(TYPE2SMALLINT(ARRAY, AGG_TYPE_BITS)) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_uctypes_globals, mp_module_uctypes_globals_table); const mp_obj_module_t mp_module_uctypes = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_uctypes_globals, }; #endif
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moductypes.c
C
apache-2.0
28,152
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <assert.h> #include <string.h> #include "py/runtime.h" #if MICROPY_PY_UHASHLIB #if MICROPY_SSL_MBEDTLS #include "mbedtls/version.h" #endif #if MICROPY_PY_UHASHLIB_SHA256 #if MICROPY_SSL_MBEDTLS #include "mbedtls/sha256.h" #else #include "lib/crypto-algorithms/sha256.h" #endif #endif #if MICROPY_PY_UHASHLIB_SHA1 || MICROPY_PY_UHASHLIB_MD5 #if MICROPY_SSL_AXTLS #include "lib/axtls/crypto/crypto.h" #endif #if MICROPY_SSL_MBEDTLS #include "mbedtls/md5.h" #include "mbedtls/sha1.h" #endif #endif typedef struct _mp_obj_hash_t { mp_obj_base_t base; bool final; // if set, update and digest raise an exception uintptr_t state[0]; // must be aligned to a machine word } mp_obj_hash_t; static void uhashlib_ensure_not_final(mp_obj_hash_t *self) { if (self->final) { mp_raise_ValueError(MP_ERROR_TEXT("hash is final")); } } #if MICROPY_PY_UHASHLIB_SHA256 STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg); #if MICROPY_SSL_MBEDTLS #if MBEDTLS_VERSION_NUMBER < 0x02070000 #define mbedtls_sha256_starts_ret mbedtls_sha256_starts #define mbedtls_sha256_update_ret mbedtls_sha256_update #define mbedtls_sha256_finish_ret mbedtls_sha256_finish #endif STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context)); o->base.type = type; o->final = false; mbedtls_sha256_init((mbedtls_sha256_context *)&o->state); mbedtls_sha256_starts_ret((mbedtls_sha256_context *)&o->state, 0); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); mbedtls_sha256_update_ret((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); self->final = true; vstr_t vstr; vstr_init_len(&vstr, 32); mbedtls_sha256_finish_ret((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #else #include "lib/crypto-algorithms/sha256.c" STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX)); o->base.type = type; o->final = false; sha256_init((CRYAL_SHA256_CTX *)o->state); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); sha256_update((CRYAL_SHA256_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); self->final = true; vstr_t vstr; vstr_init_len(&vstr, SHA256_BLOCK_SIZE); sha256_final((CRYAL_SHA256_CTX *)self->state, (byte *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif STATIC MP_DEFINE_CONST_FUN_OBJ_2(uhashlib_sha256_update_obj, uhashlib_sha256_update); STATIC MP_DEFINE_CONST_FUN_OBJ_1(uhashlib_sha256_digest_obj, uhashlib_sha256_digest); STATIC const mp_rom_map_elem_t uhashlib_sha256_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&uhashlib_sha256_update_obj) }, { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&uhashlib_sha256_digest_obj) }, }; STATIC MP_DEFINE_CONST_DICT(uhashlib_sha256_locals_dict, uhashlib_sha256_locals_dict_table); STATIC const mp_obj_type_t uhashlib_sha256_type = { { &mp_type_type }, .name = MP_QSTR_sha256, .make_new = uhashlib_sha256_make_new, .locals_dict = (void *)&uhashlib_sha256_locals_dict, }; #endif #if MICROPY_PY_UHASHLIB_SHA1 STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg); #if MICROPY_SSL_AXTLS STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX)); o->base.type = type; o->final = false; SHA1_Init((SHA1_CTX *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); SHA1_Update((SHA1_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); self->final = true; vstr_t vstr; vstr_init_len(&vstr, SHA1_SIZE); SHA1_Final((byte *)vstr.buf, (SHA1_CTX *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif #if MICROPY_SSL_MBEDTLS #if MBEDTLS_VERSION_NUMBER < 0x02070000 #define mbedtls_sha1_starts_ret mbedtls_sha1_starts #define mbedtls_sha1_update_ret mbedtls_sha1_update #define mbedtls_sha1_finish_ret mbedtls_sha1_finish #endif STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context)); o->base.type = type; o->final = false; mbedtls_sha1_init((mbedtls_sha1_context *)o->state); mbedtls_sha1_starts_ret((mbedtls_sha1_context *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); mbedtls_sha1_update_ret((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); self->final = true; vstr_t vstr; vstr_init_len(&vstr, 20); mbedtls_sha1_finish_ret((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); mbedtls_sha1_free((mbedtls_sha1_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif STATIC MP_DEFINE_CONST_FUN_OBJ_2(uhashlib_sha1_update_obj, uhashlib_sha1_update); STATIC MP_DEFINE_CONST_FUN_OBJ_1(uhashlib_sha1_digest_obj, uhashlib_sha1_digest); STATIC const mp_rom_map_elem_t uhashlib_sha1_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&uhashlib_sha1_update_obj) }, { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&uhashlib_sha1_digest_obj) }, }; STATIC MP_DEFINE_CONST_DICT(uhashlib_sha1_locals_dict, uhashlib_sha1_locals_dict_table); STATIC const mp_obj_type_t uhashlib_sha1_type = { { &mp_type_type }, .name = MP_QSTR_sha1, .make_new = uhashlib_sha1_make_new, .locals_dict = (void *)&uhashlib_sha1_locals_dict, }; #endif #if MICROPY_PY_UHASHLIB_MD5 STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg); #if MICROPY_SSL_AXTLS STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(MD5_CTX)); o->base.type = type; o->final = false; MD5_Init((MD5_CTX *)o->state); if (n_args == 1) { uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); MD5_Update((MD5_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); self->final = true; vstr_t vstr; vstr_init_len(&vstr, MD5_SIZE); MD5_Final((byte *)vstr.buf, (MD5_CTX *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif // MICROPY_SSL_AXTLS #if MICROPY_SSL_MBEDTLS #if MBEDTLS_VERSION_NUMBER < 0x02070000 #define mbedtls_md5_starts_ret mbedtls_md5_starts #define mbedtls_md5_update_ret mbedtls_md5_update #define mbedtls_md5_finish_ret mbedtls_md5_finish #endif STATIC mp_obj_t uhashlib_md5_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_md5_context)); o->base.type = type; o->final = false; mbedtls_md5_init((mbedtls_md5_context *)o->state); mbedtls_md5_starts_ret((mbedtls_md5_context *)o->state); if (n_args == 1) { uhashlib_md5_update(MP_OBJ_FROM_PTR(o), args[0]); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t uhashlib_md5_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); mbedtls_md5_update_ret((mbedtls_md5_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC mp_obj_t uhashlib_md5_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); uhashlib_ensure_not_final(self); self->final = true; vstr_t vstr; vstr_init_len(&vstr, 16); mbedtls_md5_finish_ret((mbedtls_md5_context *)self->state, (byte *)vstr.buf); mbedtls_md5_free((mbedtls_md5_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif // MICROPY_SSL_MBEDTLS STATIC MP_DEFINE_CONST_FUN_OBJ_2(uhashlib_md5_update_obj, uhashlib_md5_update); STATIC MP_DEFINE_CONST_FUN_OBJ_1(uhashlib_md5_digest_obj, uhashlib_md5_digest); STATIC const mp_rom_map_elem_t uhashlib_md5_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&uhashlib_md5_update_obj) }, { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&uhashlib_md5_digest_obj) }, }; STATIC MP_DEFINE_CONST_DICT(uhashlib_md5_locals_dict, uhashlib_md5_locals_dict_table); STATIC const mp_obj_type_t uhashlib_md5_type = { { &mp_type_type }, .name = MP_QSTR_md5, .make_new = uhashlib_md5_make_new, .locals_dict = (void *)&uhashlib_md5_locals_dict, }; #endif // MICROPY_PY_UHASHLIB_MD5 STATIC const mp_rom_map_elem_t mp_module_uhashlib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uhashlib) }, #if MICROPY_PY_UHASHLIB_SHA256 { MP_ROM_QSTR(MP_QSTR_sha256), MP_ROM_PTR(&uhashlib_sha256_type) }, #endif #if MICROPY_PY_UHASHLIB_SHA1 { MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&uhashlib_sha1_type) }, #endif #if MICROPY_PY_UHASHLIB_MD5 { MP_ROM_QSTR(MP_QSTR_md5), MP_ROM_PTR(&uhashlib_md5_type) }, #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globals_table); const mp_obj_module_t mp_module_uhashlib = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_uhashlib_globals, }; #endif // MICROPY_PY_UHASHLIB
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduhashlib.c
C
apache-2.0
13,512
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/objlist.h" #include "py/runtime.h" #if MICROPY_PY_UHEAPQ // the algorithm here is modelled on CPython's heapq.py STATIC mp_obj_list_t *uheapq_get_heap(mp_obj_t heap_in) { if (!mp_obj_is_type(heap_in, &mp_type_list)) { mp_raise_TypeError(MP_ERROR_TEXT("heap must be a list")); } return MP_OBJ_TO_PTR(heap_in); } STATIC void uheapq_heap_siftdown(mp_obj_list_t *heap, mp_uint_t start_pos, mp_uint_t pos) { mp_obj_t item = heap->items[pos]; while (pos > start_pos) { mp_uint_t parent_pos = (pos - 1) >> 1; mp_obj_t parent = heap->items[parent_pos]; if (mp_binary_op(MP_BINARY_OP_LESS, item, parent) == mp_const_true) { heap->items[pos] = parent; pos = parent_pos; } else { break; } } heap->items[pos] = item; } STATIC void uheapq_heap_siftup(mp_obj_list_t *heap, mp_uint_t pos) { mp_uint_t start_pos = pos; mp_uint_t end_pos = heap->len; mp_obj_t item = heap->items[pos]; for (mp_uint_t child_pos = 2 * pos + 1; child_pos < end_pos; child_pos = 2 * pos + 1) { // choose right child if it's <= left child if (child_pos + 1 < end_pos && mp_binary_op(MP_BINARY_OP_LESS, heap->items[child_pos], heap->items[child_pos + 1]) == mp_const_false) { child_pos += 1; } // bubble up the smaller child heap->items[pos] = heap->items[child_pos]; pos = child_pos; } heap->items[pos] = item; uheapq_heap_siftdown(heap, start_pos, pos); } STATIC mp_obj_t mod_uheapq_heappush(mp_obj_t heap_in, mp_obj_t item) { mp_obj_list_t *heap = uheapq_get_heap(heap_in); mp_obj_list_append(heap_in, item); uheapq_heap_siftdown(heap, 0, heap->len - 1); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_uheapq_heappush_obj, mod_uheapq_heappush); STATIC mp_obj_t mod_uheapq_heappop(mp_obj_t heap_in) { mp_obj_list_t *heap = uheapq_get_heap(heap_in); if (heap->len == 0) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty heap")); } mp_obj_t item = heap->items[0]; heap->len -= 1; heap->items[0] = heap->items[heap->len]; heap->items[heap->len] = MP_OBJ_NULL; // so we don't retain a pointer if (heap->len) { uheapq_heap_siftup(heap, 0); } return item; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_uheapq_heappop_obj, mod_uheapq_heappop); STATIC mp_obj_t mod_uheapq_heapify(mp_obj_t heap_in) { mp_obj_list_t *heap = uheapq_get_heap(heap_in); for (mp_uint_t i = heap->len / 2; i > 0;) { uheapq_heap_siftup(heap, --i); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_uheapq_heapify_obj, mod_uheapq_heapify); #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t mp_module_uheapq_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uheapq) }, { MP_ROM_QSTR(MP_QSTR_heappush), MP_ROM_PTR(&mod_uheapq_heappush_obj) }, { MP_ROM_QSTR(MP_QSTR_heappop), MP_ROM_PTR(&mod_uheapq_heappop_obj) }, { MP_ROM_QSTR(MP_QSTR_heapify), MP_ROM_PTR(&mod_uheapq_heapify_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_uheapq_globals, mp_module_uheapq_globals_table); const mp_obj_module_t mp_module_uheapq = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_uheapq_globals, }; #endif #endif // MICROPY_PY_UHEAPQ
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduheapq.c
C
apache-2.0
4,599
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include "py/objlist.h" #include "py/objstringio.h" #include "py/parsenum.h" #include "py/runtime.h" #include "py/stream.h" #if MICROPY_PY_UJSON #if MICROPY_PY_UJSON_SEPARATORS enum { DUMP_MODE_TO_STRING = 1, DUMP_MODE_TO_STREAM = 2, }; STATIC mp_obj_t mod_ujson_dump_helper(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args, unsigned int mode) { enum { ARG_separators }; static const mp_arg_t allowed_args[] = { { MP_QSTR_separators, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - mode, pos_args + mode, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_print_ext_t print_ext; if (args[ARG_separators].u_obj == mp_const_none) { print_ext.item_separator = ", "; print_ext.key_separator = ": "; } else { mp_obj_t *items; mp_obj_get_array_fixed_n(args[ARG_separators].u_obj, 2, &items); print_ext.item_separator = mp_obj_str_get_str(items[0]); print_ext.key_separator = mp_obj_str_get_str(items[1]); } if (mode == DUMP_MODE_TO_STRING) { // dumps(obj) vstr_t vstr; vstr_init_print(&vstr, 8, &print_ext.base); mp_obj_print_helper(&print_ext.base, pos_args[0], PRINT_JSON); return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); } else { // dump(obj, stream) print_ext.base.data = MP_OBJ_TO_PTR(pos_args[1]); print_ext.base.print_strn = mp_stream_write_adaptor; mp_get_stream_raise(pos_args[1], MP_STREAM_OP_WRITE); mp_obj_print_helper(&print_ext.base, pos_args[0], PRINT_JSON); return mp_const_none; } } STATIC mp_obj_t mod_ujson_dump(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { return mod_ujson_dump_helper(n_args, pos_args, kw_args, DUMP_MODE_TO_STREAM); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ujson_dump_obj, 2, mod_ujson_dump); STATIC mp_obj_t mod_ujson_dumps(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { return mod_ujson_dump_helper(n_args, pos_args, kw_args, DUMP_MODE_TO_STRING); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ujson_dumps_obj, 1, mod_ujson_dumps); #else STATIC mp_obj_t mod_ujson_dump(mp_obj_t obj, mp_obj_t stream) { mp_get_stream_raise(stream, MP_STREAM_OP_WRITE); mp_print_t print = {MP_OBJ_TO_PTR(stream), mp_stream_write_adaptor}; mp_obj_print_helper(&print, obj, PRINT_JSON); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ujson_dump_obj, mod_ujson_dump); STATIC mp_obj_t mod_ujson_dumps(mp_obj_t obj) { vstr_t vstr; mp_print_t print; vstr_init_print(&vstr, 8, &print); mp_obj_print_helper(&print, obj, PRINT_JSON); return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_dumps_obj, mod_ujson_dumps); #endif // The function below implements a simple non-recursive JSON parser. // // The JSON specification is at http://www.ietf.org/rfc/rfc4627.txt // The parser here will parse any valid JSON and return the correct // corresponding Python object. It allows through a superset of JSON, since // it treats commas and colons as "whitespace", and doesn't care if // brackets/braces are correctly paired. It will raise a ValueError if the // input is outside it's specs. // // Most of the work is parsing the primitives (null, false, true, numbers, // strings). It does 1 pass over the input stream. It tries to be fast and // small in code size, while not using more RAM than necessary. typedef struct _ujson_stream_t { mp_obj_t stream_obj; mp_uint_t (*read)(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode); int errcode; byte cur; } ujson_stream_t; #define S_EOF (0) // null is not allowed in json stream so is ok as EOF marker #define S_END(s) ((s).cur == S_EOF) #define S_CUR(s) ((s).cur) #define S_NEXT(s) (ujson_stream_next(&(s))) STATIC byte ujson_stream_next(ujson_stream_t *s) { mp_uint_t ret = s->read(s->stream_obj, &s->cur, 1, &s->errcode); if (s->errcode != 0) { mp_raise_OSError(s->errcode); } if (ret == 0) { s->cur = S_EOF; } return s->cur; } STATIC mp_obj_t mod_ujson_load(mp_obj_t stream_obj) { const mp_stream_p_t *stream_p = mp_get_stream_raise(stream_obj, MP_STREAM_OP_READ); ujson_stream_t s = {stream_obj, stream_p->read, 0, 0}; vstr_t vstr; vstr_init(&vstr, 8); mp_obj_list_t stack; // we use a list as a simple stack for nested JSON stack.len = 0; stack.items = NULL; mp_obj_t stack_top = MP_OBJ_NULL; const mp_obj_type_t *stack_top_type = NULL; mp_obj_t stack_key = MP_OBJ_NULL; S_NEXT(s); for (;;) { cont: if (S_END(s)) { break; } mp_obj_t next = MP_OBJ_NULL; bool enter = false; byte cur = S_CUR(s); S_NEXT(s); switch (cur) { case ',': case ':': case ' ': case '\t': case '\n': case '\r': goto cont; case 'n': if (S_CUR(s) == 'u' && S_NEXT(s) == 'l' && S_NEXT(s) == 'l') { S_NEXT(s); next = mp_const_none; } else { goto fail; } break; case 'f': if (S_CUR(s) == 'a' && S_NEXT(s) == 'l' && S_NEXT(s) == 's' && S_NEXT(s) == 'e') { S_NEXT(s); next = mp_const_false; } else { goto fail; } break; case 't': if (S_CUR(s) == 'r' && S_NEXT(s) == 'u' && S_NEXT(s) == 'e') { S_NEXT(s); next = mp_const_true; } else { goto fail; } break; case '"': vstr_reset(&vstr); for (; !S_END(s) && S_CUR(s) != '"';) { byte c = S_CUR(s); if (c == '\\') { c = S_NEXT(s); switch (c) { case 'b': c = 0x08; break; case 'f': c = 0x0c; break; case 'n': c = 0x0a; break; case 'r': c = 0x0d; break; case 't': c = 0x09; break; case 'u': { mp_uint_t num = 0; for (int i = 0; i < 4; i++) { c = (S_NEXT(s) | 0x20) - '0'; if (c > 9) { c -= ('a' - ('9' + 1)); } num = (num << 4) | c; } vstr_add_char(&vstr, num); goto str_cont; } } } vstr_add_byte(&vstr, c); str_cont: S_NEXT(s); } if (S_END(s)) { goto fail; } S_NEXT(s); next = mp_obj_new_str(vstr.buf, vstr.len); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { bool flt = false; vstr_reset(&vstr); for (;;) { vstr_add_byte(&vstr, cur); cur = S_CUR(s); if (cur == '.' || cur == 'E' || cur == 'e') { flt = true; } else if (cur == '+' || cur == '-' || unichar_isdigit(cur)) { // pass } else { break; } S_NEXT(s); } if (flt) { next = mp_parse_num_decimal(vstr.buf, vstr.len, false, false, NULL); } else { next = mp_parse_num_integer(vstr.buf, vstr.len, 10, NULL); } break; } case '[': next = mp_obj_new_list(0, NULL); enter = true; break; case '{': next = mp_obj_new_dict(0); enter = true; break; case '}': case ']': { if (stack_top == MP_OBJ_NULL) { // no object at all goto fail; } if (stack.len == 0) { // finished; compound object goto success; } stack.len -= 1; stack_top = stack.items[stack.len]; stack_top_type = mp_obj_get_type(stack_top); goto cont; } default: goto fail; } if (stack_top == MP_OBJ_NULL) { stack_top = next; stack_top_type = mp_obj_get_type(stack_top); if (!enter) { // finished; single primitive only goto success; } } else { // append to list or dict if (stack_top_type == &mp_type_list) { mp_obj_list_append(stack_top, next); } else { if (stack_key == MP_OBJ_NULL) { stack_key = next; if (enter) { goto fail; } } else { mp_obj_dict_store(stack_top, stack_key, next); stack_key = MP_OBJ_NULL; } } if (enter) { if (stack.items == NULL) { mp_obj_list_init(&stack, 1); stack.items[0] = stack_top; } else { mp_obj_list_append(MP_OBJ_FROM_PTR(&stack), stack_top); } stack_top = next; stack_top_type = mp_obj_get_type(stack_top); } } } success: // eat trailing whitespace while (unichar_isspace(S_CUR(s))) { S_NEXT(s); } if (!S_END(s)) { // unexpected chars goto fail; } if (stack_top == MP_OBJ_NULL || stack.len != 0) { // not exactly 1 object goto fail; } vstr_clear(&vstr); return stack_top; fail: mp_raise_ValueError(MP_ERROR_TEXT("syntax error in JSON")); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load); STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(obj, &bufinfo, MP_BUFFER_READ); vstr_t vstr = {bufinfo.len, bufinfo.len, (char *)bufinfo.buf, true}; mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL}; return mod_ujson_load(MP_OBJ_FROM_PTR(&sio)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_loads_obj, mod_ujson_loads); STATIC const mp_rom_map_elem_t mp_module_ujson_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ujson) }, { MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&mod_ujson_dump_obj) }, { MP_ROM_QSTR(MP_QSTR_dumps), MP_ROM_PTR(&mod_ujson_dumps_obj) }, { MP_ROM_QSTR(MP_QSTR_load), MP_ROM_PTR(&mod_ujson_load_obj) }, { MP_ROM_QSTR(MP_QSTR_loads), MP_ROM_PTR(&mod_ujson_loads_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_ujson_globals, mp_module_ujson_globals_table); const mp_obj_module_t mp_module_ujson = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_ujson_globals, }; #endif // MICROPY_PY_UJSON
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modujson.c
C
apache-2.0
13,568
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <assert.h> #include <string.h> #include "py/runtime.h" #if MICROPY_PY_URANDOM // Work out if the seed will be set on import or not. #if MICROPY_MODULE_BUILTIN_INIT && defined(MICROPY_PY_URANDOM_SEED_INIT_FUNC) #define SEED_ON_IMPORT (1) #else #define SEED_ON_IMPORT (0) #endif // Yasmarang random number generator // by Ilya Levin // http://www.literatecode.com/yasmarang // Public Domain #if !MICROPY_ENABLE_DYNRUNTIME #if SEED_ON_IMPORT // If the state is seeded on import then keep these variables in the BSS. STATIC uint32_t yasmarang_pad, yasmarang_n, yasmarang_d; STATIC uint8_t yasmarang_dat; #else // Without seed-on-import these variables must be initialised via the data section. STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233; STATIC uint8_t yasmarang_dat = 0; #endif #endif STATIC uint32_t yasmarang(void) { yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29); yasmarang_n = yasmarang_pad | 2; yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1); yasmarang_dat ^= (char)yasmarang_pad ^ (yasmarang_d >> 8) ^ 1; return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1); } /* yasmarang */ // End of Yasmarang #if MICROPY_PY_URANDOM_EXTRA_FUNCS // returns an unsigned integer below the given argument // n must not be zero STATIC uint32_t yasmarang_randbelow(uint32_t n) { uint32_t mask = 1; while ((n & mask) < n) { mask = (mask << 1) | 1; } uint32_t r; do { r = yasmarang() & mask; } while (r >= n); return r; } #endif STATIC mp_obj_t mod_urandom_getrandbits(mp_obj_t num_in) { int n = mp_obj_get_int(num_in); if (n > 32 || n < 0) { mp_raise_ValueError(MP_ERROR_TEXT("bits must be 32 or less")); } if (n == 0) { return MP_OBJ_NEW_SMALL_INT(0); } uint32_t mask = ~0; // Beware of C undefined behavior when shifting by >= than bit size mask >>= (32 - n); return mp_obj_new_int_from_uint(yasmarang() & mask); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_urandom_getrandbits_obj, mod_urandom_getrandbits); STATIC mp_obj_t mod_urandom_seed(size_t n_args, const mp_obj_t *args) { mp_uint_t seed; if (n_args == 0 || args[0] == mp_const_none) { #ifdef MICROPY_PY_URANDOM_SEED_INIT_FUNC seed = MICROPY_PY_URANDOM_SEED_INIT_FUNC; #else mp_raise_ValueError(MP_ERROR_TEXT("no default seed")); #endif } else { seed = mp_obj_get_int_truncated(args[0]); } yasmarang_pad = seed; yasmarang_n = 69; yasmarang_d = 233; yasmarang_dat = 0; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_urandom_seed_obj, 0, 1, mod_urandom_seed); #if MICROPY_PY_URANDOM_EXTRA_FUNCS STATIC mp_obj_t mod_urandom_randrange(size_t n_args, const mp_obj_t *args) { mp_int_t start = mp_obj_get_int(args[0]); if (n_args == 1) { // range(stop) if (start > 0) { return mp_obj_new_int(yasmarang_randbelow(start)); } else { goto error; } } else { mp_int_t stop = mp_obj_get_int(args[1]); if (n_args == 2) { // range(start, stop) if (start < stop) { return mp_obj_new_int(start + yasmarang_randbelow(stop - start)); } else { goto error; } } else { // range(start, stop, step) mp_int_t step = mp_obj_get_int(args[2]); mp_int_t n; if (step > 0) { n = (stop - start + step - 1) / step; } else if (step < 0) { n = (stop - start + step + 1) / step; } else { goto error; } if (n > 0) { return mp_obj_new_int(start + step * yasmarang_randbelow(n)); } else { goto error; } } } error: mp_raise_ValueError(NULL); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_urandom_randrange_obj, 1, 3, mod_urandom_randrange); STATIC mp_obj_t mod_urandom_randint(mp_obj_t a_in, mp_obj_t b_in) { mp_int_t a = mp_obj_get_int(a_in); mp_int_t b = mp_obj_get_int(b_in); if (a <= b) { return mp_obj_new_int(a + yasmarang_randbelow(b - a + 1)); } else { mp_raise_ValueError(NULL); } } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_urandom_randint_obj, mod_urandom_randint); STATIC mp_obj_t mod_urandom_choice(mp_obj_t seq) { mp_int_t len = mp_obj_get_int(mp_obj_len(seq)); if (len > 0) { return mp_obj_subscr(seq, mp_obj_new_int(yasmarang_randbelow(len)), MP_OBJ_SENTINEL); } else { mp_raise_type(&mp_type_IndexError); } } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_urandom_choice_obj, mod_urandom_choice); #if MICROPY_PY_BUILTINS_FLOAT // returns a number in the range [0..1) using Yasmarang to fill in the fraction bits STATIC mp_float_t yasmarang_float(void) { mp_float_union_t u; u.p.sgn = 0; u.p.exp = (1 << (MP_FLOAT_EXP_BITS - 1)) - 1; if (MP_FLOAT_FRAC_BITS <= 32) { u.p.frc = yasmarang(); } else { u.p.frc = ((uint64_t)yasmarang() << 32) | (uint64_t)yasmarang(); } return u.f - 1; } STATIC mp_obj_t mod_urandom_random(void) { return mp_obj_new_float(yasmarang_float()); } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_urandom_random_obj, mod_urandom_random); STATIC mp_obj_t mod_urandom_uniform(mp_obj_t a_in, mp_obj_t b_in) { mp_float_t a = mp_obj_get_float(a_in); mp_float_t b = mp_obj_get_float(b_in); return mp_obj_new_float(a + (b - a) * yasmarang_float()); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_urandom_uniform_obj, mod_urandom_uniform); #endif #endif // MICROPY_PY_URANDOM_EXTRA_FUNCS #if SEED_ON_IMPORT STATIC mp_obj_t mod_urandom___init__() { // This module may be imported by more than one name so need to ensure // that it's only ever seeded once. static bool seeded = false; if (!seeded) { seeded = true; mod_urandom_seed(0, NULL); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_urandom___init___obj, mod_urandom___init__); #endif #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t mp_module_urandom_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_urandom) }, #if SEED_ON_IMPORT { MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&mod_urandom___init___obj) }, #endif { MP_ROM_QSTR(MP_QSTR_getrandbits), MP_ROM_PTR(&mod_urandom_getrandbits_obj) }, { MP_ROM_QSTR(MP_QSTR_seed), MP_ROM_PTR(&mod_urandom_seed_obj) }, #if MICROPY_PY_URANDOM_EXTRA_FUNCS { MP_ROM_QSTR(MP_QSTR_randrange), MP_ROM_PTR(&mod_urandom_randrange_obj) }, { MP_ROM_QSTR(MP_QSTR_randint), MP_ROM_PTR(&mod_urandom_randint_obj) }, { MP_ROM_QSTR(MP_QSTR_choice), MP_ROM_PTR(&mod_urandom_choice_obj) }, #if MICROPY_PY_BUILTINS_FLOAT { MP_ROM_QSTR(MP_QSTR_random), MP_ROM_PTR(&mod_urandom_random_obj) }, { MP_ROM_QSTR(MP_QSTR_uniform), MP_ROM_PTR(&mod_urandom_uniform_obj) }, #endif #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_urandom_globals, mp_module_urandom_globals_table); const mp_obj_module_t mp_module_urandom = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_urandom_globals, }; #endif #endif // MICROPY_PY_URANDOM
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modurandom.c
C
apache-2.0
8,637
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <assert.h> #include <string.h> #include "py/runtime.h" #include "py/binary.h" #include "py/objstr.h" #include "py/stackctrl.h" #if MICROPY_PY_URE #define re1_5_stack_chk() MP_STACK_CHECK() #include "lib/re1.5/re1.5.h" #define FLAG_DEBUG 0x1000 typedef struct _mp_obj_re_t { mp_obj_base_t base; ByteProg re; } mp_obj_re_t; typedef struct _mp_obj_match_t { mp_obj_base_t base; int num_matches; mp_obj_t str; const char *caps[0]; } mp_obj_match_t; STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args); #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_obj_type_t re_type; #endif STATIC void match_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_match_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<match num=%d>", self->num_matches); } STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) { mp_obj_match_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t no = mp_obj_get_int(no_in); if (no < 0 || no >= self->num_matches) { mp_raise_type_arg(&mp_type_IndexError, no_in); } const char *start = self->caps[no * 2]; if (start == NULL) { // no match for this group return mp_const_none; } return mp_obj_new_str_of_type(mp_obj_get_type(self->str), (const byte *)start, self->caps[no * 2 + 1] - start); } MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group); #if MICROPY_PY_URE_MATCH_GROUPS STATIC mp_obj_t match_groups(mp_obj_t self_in) { mp_obj_match_t *self = MP_OBJ_TO_PTR(self_in); if (self->num_matches <= 1) { return mp_const_empty_tuple; } mp_obj_tuple_t *groups = MP_OBJ_TO_PTR(mp_obj_new_tuple(self->num_matches - 1, NULL)); for (int i = 1; i < self->num_matches; ++i) { groups->items[i - 1] = match_group(self_in, MP_OBJ_NEW_SMALL_INT(i)); } return MP_OBJ_FROM_PTR(groups); } MP_DEFINE_CONST_FUN_OBJ_1(match_groups_obj, match_groups); #endif #if MICROPY_PY_URE_MATCH_SPAN_START_END STATIC void match_span_helper(size_t n_args, const mp_obj_t *args, mp_obj_t span[2]) { mp_obj_match_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t no = 0; if (n_args == 2) { no = mp_obj_get_int(args[1]); if (no < 0 || no >= self->num_matches) { mp_raise_type_arg(&mp_type_IndexError, args[1]); } } mp_int_t s = -1; mp_int_t e = -1; const char *start = self->caps[no * 2]; if (start != NULL) { // have a match for this group const char *begin = mp_obj_str_get_str(self->str); s = start - begin; e = self->caps[no * 2 + 1] - begin; } span[0] = mp_obj_new_int(s); span[1] = mp_obj_new_int(e); } STATIC mp_obj_t match_span(size_t n_args, const mp_obj_t *args) { mp_obj_t span[2]; match_span_helper(n_args, args, span); return mp_obj_new_tuple(2, span); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(match_span_obj, 1, 2, match_span); STATIC mp_obj_t match_start(size_t n_args, const mp_obj_t *args) { mp_obj_t span[2]; match_span_helper(n_args, args, span); return span[0]; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(match_start_obj, 1, 2, match_start); STATIC mp_obj_t match_end(size_t n_args, const mp_obj_t *args) { mp_obj_t span[2]; match_span_helper(n_args, args, span); return span[1]; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(match_end_obj, 1, 2, match_end); #endif #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t match_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_group), MP_ROM_PTR(&match_group_obj) }, #if MICROPY_PY_URE_MATCH_GROUPS { MP_ROM_QSTR(MP_QSTR_groups), MP_ROM_PTR(&match_groups_obj) }, #endif #if MICROPY_PY_URE_MATCH_SPAN_START_END { MP_ROM_QSTR(MP_QSTR_span), MP_ROM_PTR(&match_span_obj) }, { MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&match_start_obj) }, { MP_ROM_QSTR(MP_QSTR_end), MP_ROM_PTR(&match_end_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(match_locals_dict, match_locals_dict_table); STATIC const mp_obj_type_t match_type = { { &mp_type_type }, .name = MP_QSTR_match, .print = match_print, .locals_dict = (void *)&match_locals_dict, }; #endif STATIC void re_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_re_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<re %p>", self); } STATIC mp_obj_t ure_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { (void)n_args; mp_obj_re_t *self; if (mp_obj_is_type(args[0], &re_type)) { self = MP_OBJ_TO_PTR(args[0]); } else { self = MP_OBJ_TO_PTR(mod_re_compile(1, args)); } Subject subj; size_t len; subj.begin = mp_obj_str_get_data(args[1], &len); subj.end = subj.begin + len; int caps_num = (self->re.sub + 1) * 2; mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char *, caps_num); // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char memset((char *)match->caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, is_anchored); if (res == 0) { m_del_var(mp_obj_match_t, char *, caps_num, match); return mp_const_none; } match->base.type = &match_type; match->num_matches = caps_num / 2; // caps_num counts start and end pointers match->str = args[1]; return MP_OBJ_FROM_PTR(match); } STATIC mp_obj_t re_match(size_t n_args, const mp_obj_t *args) { return ure_exec(true, n_args, args); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(re_match_obj, 2, 4, re_match); STATIC mp_obj_t re_search(size_t n_args, const mp_obj_t *args) { return ure_exec(false, n_args, args); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(re_search_obj, 2, 4, re_search); STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { mp_obj_re_t *self = MP_OBJ_TO_PTR(args[0]); Subject subj; size_t len; const mp_obj_type_t *str_type = mp_obj_get_type(args[1]); subj.begin = mp_obj_str_get_data(args[1], &len); subj.end = subj.begin + len; int caps_num = (self->re.sub + 1) * 2; int maxsplit = 0; if (n_args > 2) { maxsplit = mp_obj_get_int(args[2]); } mp_obj_t retval = mp_obj_new_list(0, NULL); const char **caps = mp_local_alloc(caps_num * sizeof(char *)); while (true) { // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char memset((char **)caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, caps, caps_num, false); // if we didn't have a match, or had an empty match, it's time to stop if (!res || caps[0] == caps[1]) { break; } mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, caps[0] - subj.begin); mp_obj_list_append(retval, s); if (self->re.sub > 0) { mp_raise_NotImplementedError(MP_ERROR_TEXT("splitting with sub-captures")); } subj.begin = caps[1]; if (maxsplit > 0 && --maxsplit == 0) { break; } } // cast is a workaround for a bug in msvc (see above) mp_local_free((char **)caps); mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, subj.end - subj.begin); mp_obj_list_append(retval, s); return retval; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(re_split_obj, 2, 3, re_split); #if MICROPY_PY_URE_SUB STATIC mp_obj_t re_sub_helper(size_t n_args, const mp_obj_t *args) { mp_obj_re_t *self; if (mp_obj_is_type(args[0], &re_type)) { self = MP_OBJ_TO_PTR(args[0]); } else { self = MP_OBJ_TO_PTR(mod_re_compile(1, args)); } mp_obj_t replace = args[1]; mp_obj_t where = args[2]; mp_int_t count = 0; if (n_args > 3) { count = mp_obj_get_int(args[3]); // Note: flags are currently ignored } size_t where_len; const char *where_str = mp_obj_str_get_data(where, &where_len); Subject subj; subj.begin = where_str; subj.end = subj.begin + where_len; int caps_num = (self->re.sub + 1) * 2; vstr_t vstr_return; vstr_return.buf = NULL; // We'll init the vstr after the first match mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char *)); match->base.type = &match_type; match->num_matches = caps_num / 2; // caps_num counts start and end pointers match->str = where; for (;;) { // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char memset((char *)match->caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, false); // If we didn't have a match, or had an empty match, it's time to stop if (!res || match->caps[0] == match->caps[1]) { break; } // Initialise the vstr if it's not already if (vstr_return.buf == NULL) { vstr_init(&vstr_return, match->caps[0] - subj.begin); } // Add pre-match string vstr_add_strn(&vstr_return, subj.begin, match->caps[0] - subj.begin); // Get replacement string const char *repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace)); // Append replacement string to result, substituting any regex groups while (*repl != '\0') { if (*repl == '\\') { ++repl; bool is_g_format = false; if (*repl == 'g' && repl[1] == '<') { // Group specified with syntax "\g<number>" repl += 2; is_g_format = true; } if ('0' <= *repl && *repl <= '9') { // Group specified with syntax "\g<number>" or "\number" unsigned int match_no = 0; do { match_no = match_no * 10 + (*repl++ - '0'); } while ('0' <= *repl && *repl <= '9'); if (is_g_format && *repl == '>') { ++repl; } if (match_no >= (unsigned int)match->num_matches) { mp_raise_type_arg(&mp_type_IndexError, MP_OBJ_NEW_SMALL_INT(match_no)); } const char *start_match = match->caps[match_no * 2]; if (start_match != NULL) { // Add the substring matched by group const char *end_match = match->caps[match_no * 2 + 1]; vstr_add_strn(&vstr_return, start_match, end_match - start_match); } } else if (*repl == '\\') { // Add the \ character vstr_add_byte(&vstr_return, *repl++); } } else { // Just add the current byte from the replacement string vstr_add_byte(&vstr_return, *repl++); } } // Move start pointer to end of last match subj.begin = match->caps[1]; // Stop substitutions if count was given and gets to 0 if (count > 0 && --count == 0) { break; } } mp_local_free(match); if (vstr_return.buf == NULL) { // Optimisation for case of no substitutions return where; } // Add post-match string vstr_add_strn(&vstr_return, subj.begin, subj.end - subj.begin); return mp_obj_new_str_from_vstr(mp_obj_get_type(where), &vstr_return); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(re_sub_obj, 3, 5, re_sub_helper); #endif #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t re_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_match), MP_ROM_PTR(&re_match_obj) }, { MP_ROM_QSTR(MP_QSTR_search), MP_ROM_PTR(&re_search_obj) }, { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&re_split_obj) }, #if MICROPY_PY_URE_SUB { MP_ROM_QSTR(MP_QSTR_sub), MP_ROM_PTR(&re_sub_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(re_locals_dict, re_locals_dict_table); STATIC const mp_obj_type_t re_type = { { &mp_type_type }, .name = MP_QSTR_ure, .print = re_print, .locals_dict = (void *)&re_locals_dict, }; #endif STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { (void)n_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; #if MICROPY_PY_URE_DEBUG int flags = 0; if (n_args > 1) { flags = mp_obj_get_int(args[1]); } #endif int error = re1_5_compilecode(&o->re, re_str); if (error != 0) { error: mp_raise_ValueError(MP_ERROR_TEXT("error in regex")); } #if MICROPY_PY_URE_DEBUG if (flags & FLAG_DEBUG) { re1_5_dumpcode(&o->re); } #endif return MP_OBJ_FROM_PTR(o); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_re_compile_obj, 1, 2, mod_re_compile); #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t mp_module_re_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ure) }, { MP_ROM_QSTR(MP_QSTR_compile), MP_ROM_PTR(&mod_re_compile_obj) }, { MP_ROM_QSTR(MP_QSTR_match), MP_ROM_PTR(&re_match_obj) }, { MP_ROM_QSTR(MP_QSTR_search), MP_ROM_PTR(&re_search_obj) }, #if MICROPY_PY_URE_SUB { MP_ROM_QSTR(MP_QSTR_sub), MP_ROM_PTR(&re_sub_obj) }, #endif #if MICROPY_PY_URE_DEBUG { MP_ROM_QSTR(MP_QSTR_DEBUG), MP_ROM_INT(FLAG_DEBUG) }, #endif }; STATIC MP_DEFINE_CONST_DICT(mp_module_re_globals, mp_module_re_globals_table); const mp_obj_module_t mp_module_ure = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_re_globals, }; #endif // Source files #include'd here to make sure they're compiled in // only if module is enabled by config setting. #define re1_5_fatal(x) assert(!x) #include "lib/re1.5/compilecode.c" #if MICROPY_PY_URE_DEBUG #include "lib/re1.5/dumpcode.c" #endif #include "lib/re1.5/recursiveloop.c" #include "lib/re1.5/charclass.c" #endif // MICROPY_PY_URE
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modure.c
C
apache-2.0
15,705
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George * Copyright (c) 2015-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_PY_USELECT #include <stdio.h> #include "py/runtime.h" #include "py/obj.h" #include "py/objlist.h" #include "py/stream.h" #include "py/mperrno.h" #include "py/mphal.h" // Flags for poll() #define FLAG_ONESHOT (1) typedef struct _poll_obj_t { mp_obj_t obj; mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); mp_uint_t flags; mp_uint_t flags_ret; } poll_obj_t; STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_len, mp_uint_t flags, bool or_flags) { for (mp_uint_t i = 0; i < obj_len; i++) { mp_map_elem_t *elem = mp_map_lookup(poll_map, mp_obj_id(obj[i]), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); if (elem->value == MP_OBJ_NULL) { // object not found; get its ioctl and add it to the poll list const mp_stream_p_t *stream_p = mp_get_stream_raise(obj[i], MP_STREAM_OP_IOCTL); poll_obj_t *poll_obj = m_new_obj(poll_obj_t); poll_obj->obj = obj[i]; poll_obj->ioctl = stream_p->ioctl; poll_obj->flags = flags; poll_obj->flags_ret = 0; elem->value = MP_OBJ_FROM_PTR(poll_obj); } else { // object exists; update its flags if (or_flags) { ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags |= flags; } else { ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = flags; } } } } // poll each object in the map STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, size_t *rwx_num) { mp_uint_t n_ready = 0; for (mp_uint_t i = 0; i < poll_map->alloc; ++i) { if (!mp_map_slot_is_filled(poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map->table[i].value); int errcode; mp_int_t ret = poll_obj->ioctl(poll_obj->obj, MP_STREAM_POLL, poll_obj->flags, &errcode); poll_obj->flags_ret = ret; if (ret == -1) { // error doing ioctl mp_raise_OSError(errcode); } if (ret != 0) { // object is ready n_ready += 1; if (rwx_num != NULL) { if (ret & MP_STREAM_POLL_RD) { rwx_num[0] += 1; } if (ret & MP_STREAM_POLL_WR) { rwx_num[1] += 1; } if ((ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) { rwx_num[2] += 1; } } } } return n_ready; } #if MICROPY_PY_USELECT_SELECT // select(rlist, wlist, xlist[, timeout]) STATIC mp_obj_t select_select(size_t n_args, const mp_obj_t *args) { // get array data from tuple/list arguments size_t rwx_len[3]; mp_obj_t *r_array, *w_array, *x_array; mp_obj_get_array(args[0], &rwx_len[0], &r_array); mp_obj_get_array(args[1], &rwx_len[1], &w_array); mp_obj_get_array(args[2], &rwx_len[2], &x_array); // get timeout mp_uint_t timeout = -1; if (n_args == 4) { if (args[3] != mp_const_none) { #if MICROPY_PY_BUILTINS_FLOAT float timeout_f = mp_obj_get_float_to_f(args[3]); if (timeout_f >= 0) { timeout = (mp_uint_t)(timeout_f * 1000); } #else timeout = mp_obj_get_int(args[3]) * 1000; #endif } } // merge separate lists and get the ioctl function for each object mp_map_t poll_map; mp_map_init(&poll_map, rwx_len[0] + rwx_len[1] + rwx_len[2]); poll_map_add(&poll_map, r_array, rwx_len[0], MP_STREAM_POLL_RD, true); poll_map_add(&poll_map, w_array, rwx_len[1], MP_STREAM_POLL_WR, true); poll_map_add(&poll_map, x_array, rwx_len[2], MP_STREAM_POLL_ERR | MP_STREAM_POLL_HUP, true); mp_uint_t start_tick = mp_hal_ticks_ms(); rwx_len[0] = rwx_len[1] = rwx_len[2] = 0; for (;;) { // poll the objects mp_uint_t n_ready = poll_map_poll(&poll_map, rwx_len); if (n_ready > 0 || (timeout != (mp_uint_t)-1 && mp_hal_ticks_ms() - start_tick >= timeout)) { // one or more objects are ready, or we had a timeout mp_obj_t list_array[3]; list_array[0] = mp_obj_new_list(rwx_len[0], NULL); list_array[1] = mp_obj_new_list(rwx_len[1], NULL); list_array[2] = mp_obj_new_list(rwx_len[2], NULL); rwx_len[0] = rwx_len[1] = rwx_len[2] = 0; for (mp_uint_t i = 0; i < poll_map.alloc; ++i) { if (!mp_map_slot_is_filled(&poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(poll_map.table[i].value); if (poll_obj->flags_ret & MP_STREAM_POLL_RD) { ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[0]))->items[rwx_len[0]++] = poll_obj->obj; } if (poll_obj->flags_ret & MP_STREAM_POLL_WR) { ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[1]))->items[rwx_len[1]++] = poll_obj->obj; } if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) { ((mp_obj_list_t *)MP_OBJ_TO_PTR(list_array[2]))->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); return mp_obj_new_tuple(3, list_array); } MICROPY_EVENT_POLL_HOOK } } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_select_select_obj, 3, 4, select_select); #endif // MICROPY_PY_USELECT_SELECT typedef struct _mp_obj_poll_t { mp_obj_base_t base; mp_map_t poll_map; short iter_cnt; short iter_idx; int flags; // callee-owned tuple mp_obj_t ret_tuple; } mp_obj_poll_t; // register(obj[, eventmask]) STATIC mp_obj_t poll_register(size_t n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t flags; if (n_args == 3) { flags = mp_obj_get_int(args[2]); } else { flags = MP_STREAM_POLL_RD | MP_STREAM_POLL_WR; } poll_map_add(&self->poll_map, &args[1], 1, flags, false); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_register_obj, 2, 3, poll_register); // unregister(obj) STATIC mp_obj_t poll_unregister(mp_obj_t self_in, mp_obj_t obj_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP_REMOVE_IF_FOUND); // TODO raise KeyError if obj didn't exist in map return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(poll_unregister_obj, poll_unregister); // modify(obj, eventmask) STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmask_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); mp_map_elem_t *elem = mp_map_lookup(&self->poll_map, mp_obj_id(obj_in), MP_MAP_LOOKUP); if (elem == NULL) { mp_raise_OSError(MP_ENOENT); } ((poll_obj_t *)MP_OBJ_TO_PTR(elem->value))->flags = mp_obj_get_int(eventmask_in); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); STATIC mp_uint_t poll_poll_internal(uint n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); // work out timeout (its given already in ms) mp_uint_t timeout = -1; int flags = 0; if (n_args >= 2) { if (args[1] != mp_const_none) { mp_int_t timeout_i = mp_obj_get_int(args[1]); if (timeout_i >= 0) { timeout = timeout_i; } } if (n_args >= 3) { flags = mp_obj_get_int(args[2]); } } self->flags = flags; mp_uint_t start_tick = mp_hal_ticks_ms(); mp_uint_t n_ready; for (;;) { // poll the objects n_ready = poll_map_poll(&self->poll_map, NULL); if (n_ready > 0 || (timeout != (mp_uint_t)-1 && mp_hal_ticks_ms() - start_tick >= timeout)) { break; } MICROPY_EVENT_POLL_HOOK } return n_ready; } STATIC mp_obj_t poll_poll(size_t n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); mp_uint_t n_ready = poll_poll_internal(n_args, args); // one or more objects are ready, or we had a timeout mp_obj_list_t *ret_list = MP_OBJ_TO_PTR(mp_obj_new_list(n_ready, NULL)); n_ready = 0; for (mp_uint_t i = 0; i < self->poll_map.alloc; ++i) { if (!mp_map_slot_is_filled(&self->poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); if (poll_obj->flags_ret != 0) { mp_obj_t tuple[2] = {poll_obj->obj, MP_OBJ_NEW_SMALL_INT(poll_obj->flags_ret)}; ret_list->items[n_ready++] = mp_obj_new_tuple(2, tuple); if (self->flags & FLAG_ONESHOT) { // Don't poll next time, until new event flags will be set explicitly poll_obj->flags = 0; } } } return MP_OBJ_FROM_PTR(ret_list); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_poll_obj, 1, 3, poll_poll); STATIC mp_obj_t poll_ipoll(size_t n_args, const mp_obj_t *args) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(args[0]); if (self->ret_tuple == MP_OBJ_NULL) { self->ret_tuple = mp_obj_new_tuple(2, NULL); } int n_ready = poll_poll_internal(n_args, args); self->iter_cnt = n_ready; self->iter_idx = 0; return args[0]; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(poll_ipoll_obj, 1, 3, poll_ipoll); STATIC mp_obj_t poll_iternext(mp_obj_t self_in) { mp_obj_poll_t *self = MP_OBJ_TO_PTR(self_in); if (self->iter_cnt == 0) { return MP_OBJ_STOP_ITERATION; } self->iter_cnt--; for (mp_uint_t i = self->iter_idx; i < self->poll_map.alloc; ++i) { self->iter_idx++; if (!mp_map_slot_is_filled(&self->poll_map, i)) { continue; } poll_obj_t *poll_obj = MP_OBJ_TO_PTR(self->poll_map.table[i].value); if (poll_obj->flags_ret != 0) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->ret_tuple); t->items[0] = poll_obj->obj; t->items[1] = MP_OBJ_NEW_SMALL_INT(poll_obj->flags_ret); if (self->flags & FLAG_ONESHOT) { // Don't poll next time, until new event flags will be set explicitly poll_obj->flags = 0; } return MP_OBJ_FROM_PTR(t); } } assert(!"inconsistent number of poll active entries"); self->iter_cnt = 0; return MP_OBJ_STOP_ITERATION; } STATIC const mp_rom_map_elem_t poll_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_register), MP_ROM_PTR(&poll_register_obj) }, { MP_ROM_QSTR(MP_QSTR_unregister), MP_ROM_PTR(&poll_unregister_obj) }, { MP_ROM_QSTR(MP_QSTR_modify), MP_ROM_PTR(&poll_modify_obj) }, { MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&poll_poll_obj) }, { MP_ROM_QSTR(MP_QSTR_ipoll), MP_ROM_PTR(&poll_ipoll_obj) }, }; STATIC MP_DEFINE_CONST_DICT(poll_locals_dict, poll_locals_dict_table); STATIC const mp_obj_type_t mp_type_poll = { { &mp_type_type }, .name = MP_QSTR_poll, .getiter = mp_identity_getiter, .iternext = poll_iternext, .locals_dict = (void *)&poll_locals_dict, }; // poll() STATIC mp_obj_t select_poll(void) { mp_obj_poll_t *poll = m_new_obj(mp_obj_poll_t); poll->base.type = &mp_type_poll; mp_map_init(&poll->poll_map, 0); poll->iter_cnt = 0; poll->ret_tuple = MP_OBJ_NULL; return MP_OBJ_FROM_PTR(poll); } MP_DEFINE_CONST_FUN_OBJ_0(mp_select_poll_obj, select_poll); STATIC const mp_rom_map_elem_t mp_module_select_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uselect) }, #if MICROPY_PY_USELECT_SELECT { MP_ROM_QSTR(MP_QSTR_select), MP_ROM_PTR(&mp_select_select_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_poll), MP_ROM_PTR(&mp_select_poll_obj) }, { MP_ROM_QSTR(MP_QSTR_POLLIN), MP_ROM_INT(MP_STREAM_POLL_RD) }, { MP_ROM_QSTR(MP_QSTR_POLLOUT), MP_ROM_INT(MP_STREAM_POLL_WR) }, { MP_ROM_QSTR(MP_QSTR_POLLERR), MP_ROM_INT(MP_STREAM_POLL_ERR) }, { MP_ROM_QSTR(MP_QSTR_POLLHUP), MP_ROM_INT(MP_STREAM_POLL_HUP) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_table); const mp_obj_module_t mp_module_uselect = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_select_globals, }; #endif // MICROPY_PY_USELECT
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduselect.c
C
apache-2.0
13,729
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2015-2019 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "py/objstr.h" #if MICROPY_PY_USSL && MICROPY_SSL_AXTLS #include "ssl.h" typedef struct _mp_obj_ssl_socket_t { mp_obj_base_t base; mp_obj_t sock; SSL_CTX *ssl_ctx; SSL *ssl_sock; byte *buf; uint32_t bytes_left; bool blocking; } mp_obj_ssl_socket_t; struct ssl_args { mp_arg_val_t key; mp_arg_val_t cert; mp_arg_val_t server_side; mp_arg_val_t server_hostname; mp_arg_val_t do_handshake; }; STATIC const mp_obj_type_t ussl_socket_type; // Table of error strings corresponding to SSL_xxx error codes. STATIC const char *const ssl_error_tab1[] = { "NOT_OK", "DEAD", "CLOSE_NOTIFY", "EAGAIN", }; STATIC const char *const ssl_error_tab2[] = { "CONN_LOST", "RECORD_OVERFLOW", "SOCK_SETUP_FAILURE", NULL, "INVALID_HANDSHAKE", "INVALID_PROT_MSG", "INVALID_HMAC", "INVALID_VERSION", "UNSUPPORTED_EXTENSION", "INVALID_SESSION", "NO_CIPHER", "INVALID_CERT_HASH_ALG", "BAD_CERTIFICATE", "INVALID_KEY", NULL, "FINISHED_INVALID", "NO_CERT_DEFINED", "NO_CLIENT_RENOG", "NOT_SUPPORTED", }; STATIC NORETURN void ussl_raise_error(int err) { MP_STATIC_ASSERT(SSL_NOT_OK - 3 == SSL_EAGAIN); MP_STATIC_ASSERT(SSL_ERROR_CONN_LOST - 18 == SSL_ERROR_NOT_SUPPORTED); // Check if err corresponds to something in one of the error string tables. const char *errstr = NULL; if (SSL_NOT_OK >= err && err >= SSL_EAGAIN) { errstr = ssl_error_tab1[SSL_NOT_OK - err]; } else if (SSL_ERROR_CONN_LOST >= err && err >= SSL_ERROR_NOT_SUPPORTED) { errstr = ssl_error_tab2[SSL_ERROR_CONN_LOST - err]; } // Unknown error, just raise the error code. if (errstr == NULL) { mp_raise_OSError(err); } // Construct string object. mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t); if (o_str == NULL) { mp_raise_OSError(err); } o_str->base.type = &mp_type_str; o_str->data = (const byte *)errstr; o_str->len = strlen((char *)o_str->data); o_str->hash = qstr_compute_hash(o_str->data, o_str->len); // Raise OSError(err, str). mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(err), MP_OBJ_FROM_PTR(o_str)}; nlr_raise(mp_obj_exception_make_new(&mp_type_OSError, 2, 0, args)); } STATIC mp_obj_ssl_socket_t *ussl_socket_new(mp_obj_t sock, struct ssl_args *args) { #if MICROPY_PY_USSL_FINALISER mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); #else mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); #endif o->base.type = &ussl_socket_type; o->buf = NULL; o->bytes_left = 0; o->sock = sock; o->blocking = true; uint32_t options = SSL_SERVER_VERIFY_LATER; if (!args->do_handshake.u_bool) { options |= SSL_CONNECT_IN_PARTS; } if (args->key.u_obj != mp_const_none) { options |= SSL_NO_DEFAULT_KEY; } if ((o->ssl_ctx = ssl_ctx_new(options, SSL_DEFAULT_CLNT_SESS)) == NULL) { mp_raise_OSError(MP_EINVAL); } if (args->key.u_obj != mp_const_none) { size_t len; const byte *data = (const byte *)mp_obj_str_get_data(args->key.u_obj, &len); int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL); if (res != SSL_OK) { mp_raise_ValueError(MP_ERROR_TEXT("invalid key")); } data = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &len); res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL); if (res != SSL_OK) { mp_raise_ValueError(MP_ERROR_TEXT("invalid cert")); } } if (args->server_side.u_bool) { o->ssl_sock = ssl_server_new(o->ssl_ctx, (long)sock); } else { SSL_EXTENSIONS *ext = ssl_ext_new(); if (args->server_hostname.u_obj != mp_const_none) { ext->host_name = (char *)mp_obj_str_get_str(args->server_hostname.u_obj); } o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext); if (args->do_handshake.u_bool) { int r = ssl_handshake_status(o->ssl_sock); if (r != SSL_OK) { if (r == SSL_CLOSE_NOTIFY) { // EOF r = MP_ENOTCONN; } else if (r == SSL_EAGAIN) { r = MP_EAGAIN; } ussl_raise_error(r); } } } return o; } STATIC void ussl_socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<_SSLSocket %p>", self->ssl_sock); } STATIC mp_uint_t ussl_socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); if (o->ssl_sock == NULL) { *errcode = EBADF; return MP_STREAM_ERROR; } while (o->bytes_left == 0) { mp_int_t r = ssl_read(o->ssl_sock, &o->buf); if (r == SSL_OK) { // SSL_OK from ssl_read() means "everything is ok, but there's // no user data yet". It may happen e.g. if handshake is not // finished yet. The best way we can treat it is by returning // EAGAIN. This may be a bit unexpected in blocking mode, but // default is to perform complete handshake in constructor, so // this should not happen in blocking mode. On the other hand, // in nonblocking mode EAGAIN (comparing to the alternative of // looping) is really preferrable. if (o->blocking) { continue; } else { goto eagain; } } if (r < 0) { if (r == SSL_CLOSE_NOTIFY || r == SSL_ERROR_CONN_LOST) { // EOF return 0; } if (r == SSL_EAGAIN) { eagain: r = MP_EAGAIN; } *errcode = r; return MP_STREAM_ERROR; } o->bytes_left = r; } if (size > o->bytes_left) { size = o->bytes_left; } memcpy(buf, o->buf, size); o->buf += size; o->bytes_left -= size; return size; } STATIC mp_uint_t ussl_socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); if (o->ssl_sock == NULL) { *errcode = EBADF; return MP_STREAM_ERROR; } mp_int_t r; eagain: r = ssl_write(o->ssl_sock, buf, size); if (r == 0) { // see comment in ussl_socket_read above if (o->blocking) { goto eagain; } else { r = SSL_EAGAIN; } } if (r < 0) { if (r == SSL_CLOSE_NOTIFY || r == SSL_ERROR_CONN_LOST) { return 0; // EOF } if (r == SSL_EAGAIN) { r = MP_EAGAIN; } *errcode = r; return MP_STREAM_ERROR; } return r; } STATIC mp_uint_t ussl_socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); if (request == MP_STREAM_CLOSE && self->ssl_sock != NULL) { ssl_free(self->ssl_sock); ssl_ctx_free(self->ssl_ctx); self->ssl_sock = NULL; } // Pass all requests down to the underlying socket return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC mp_obj_t ussl_socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in); mp_obj_t sock = o->sock; mp_obj_t dest[3]; mp_load_method(sock, MP_QSTR_setblocking, dest); dest[2] = flag_in; mp_obj_t res = mp_call_method_n_kw(1, 0, dest); o->blocking = mp_obj_is_true(flag_in); return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(ussl_socket_setblocking_obj, ussl_socket_setblocking); STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&ussl_socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, #if MICROPY_PY_USSL_FINALISER { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table); STATIC const mp_stream_p_t ussl_socket_stream_p = { .read = ussl_socket_read, .write = ussl_socket_write, .ioctl = ussl_socket_ioctl, }; STATIC const mp_obj_type_t ussl_socket_type = { { &mp_type_type }, // Save on qstr's, reuse same as for module .name = MP_QSTR_ussl, .print = ussl_socket_print, .getiter = NULL, .iternext = NULL, .protocol = &ussl_socket_stream_p, .locals_dict = (void *)&ussl_socket_locals_dict, }; STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { // TODO: Implement more args static const mp_arg_t allowed_args[] = { { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_do_handshake, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, }; // TODO: Check that sock implements stream protocol mp_obj_t sock = pos_args[0]; struct ssl_args args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); return MP_OBJ_FROM_PTR(ussl_socket_new(sock, &args)); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket); STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) }, { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table); const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_ssl_globals, }; #endif // MICROPY_PY_USSL
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modussl_axtls.c
C
apache-2.0
11,897
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Linaro Ltd. * Copyright (c) 2019 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_PY_USSL && MICROPY_SSL_MBEDTLS #include <stdio.h> #include <string.h> #include <errno.h> // needed because mp_is_nonblocking_error uses system error codes #include "py/runtime.h" #include "py/stream.h" #include "py/objstr.h" // mbedtls_time_t #include "mbedtls/platform.h" #include "mbedtls/ssl.h" #include "mbedtls/x509_crt.h" #include "mbedtls/pk.h" #include "mbedtls/entropy.h" #include "mbedtls/ctr_drbg.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" typedef struct _mp_obj_ssl_socket_t { mp_obj_base_t base; mp_obj_t sock; mbedtls_entropy_context entropy; mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ssl_context ssl; mbedtls_ssl_config conf; mbedtls_x509_crt cacert; mbedtls_x509_crt cert; mbedtls_pk_context pkey; } mp_obj_ssl_socket_t; struct ssl_args { mp_arg_val_t key; mp_arg_val_t cert; mp_arg_val_t server_side; mp_arg_val_t server_hostname; mp_arg_val_t do_handshake; }; STATIC const mp_obj_type_t ussl_socket_type; #ifdef MBEDTLS_DEBUG_C STATIC void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) { (void)ctx; (void)level; printf("DBG:%s:%04d: %s\n", file, line, str); } #endif STATIC NORETURN void mbedtls_raise_error(int err) { // _mbedtls_ssl_send and _mbedtls_ssl_recv (below) turn positive error codes from the // underlying socket into negative codes to pass them through mbedtls. Here we turn them // positive again so they get interpreted as the OSError they really are. The // cut-off of -256 is a bit hacky, sigh. if (err < 0 && err > -256) { mp_raise_OSError(-err); } #if defined(MBEDTLS_ERROR_C) // Including mbedtls_strerror takes about 1.5KB due to the error strings. // MBEDTLS_ERROR_C is the define used by mbedtls to conditionally include mbedtls_strerror. // It is set/unset in the MBEDTLS_CONFIG_FILE which is defined in the Makefile. // Try to allocate memory for the message #define ERR_STR_MAX 80 // mbedtls_strerror truncates if it doesn't fit mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t); byte *o_str_buf = m_new_maybe(byte, ERR_STR_MAX); if (o_str == NULL || o_str_buf == NULL) { mp_raise_OSError(err); } // print the error message into the allocated buffer mbedtls_strerror(err, (char *)o_str_buf, ERR_STR_MAX); size_t len = strlen((char *)o_str_buf); // Put the exception object together o_str->base.type = &mp_type_str; o_str->data = o_str_buf; o_str->len = len; o_str->hash = qstr_compute_hash(o_str->data, o_str->len); // raise mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(err), MP_OBJ_FROM_PTR(o_str)}; nlr_raise(mp_obj_exception_make_new(&mp_type_OSError, 2, 0, args)); #else // mbedtls is compiled without error strings so we simply return the err number mp_raise_OSError(err); // err is typically a large negative number #endif } STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) { mp_obj_t sock = *(mp_obj_t *)ctx; const mp_stream_p_t *sock_stream = mp_get_stream(sock); int err; mp_uint_t out_sz = sock_stream->write(sock, buf, len, &err); if (out_sz == MP_STREAM_ERROR) { if (mp_is_nonblocking_error(err)) { return MBEDTLS_ERR_SSL_WANT_WRITE; } return -err; // convert an MP_ERRNO to something mbedtls passes through as error } else { return out_sz; } } // _mbedtls_ssl_recv is called by mbedtls to receive bytes from the underlying socket STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) { mp_obj_t sock = *(mp_obj_t *)ctx; const mp_stream_p_t *sock_stream = mp_get_stream(sock); int err; mp_uint_t out_sz = sock_stream->read(sock, buf, len, &err); if (out_sz == MP_STREAM_ERROR) { if (mp_is_nonblocking_error(err)) { return MBEDTLS_ERR_SSL_WANT_READ; } return -err; } else { return out_sz; } } STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { // Verify the socket object has the full stream protocol mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); #if MICROPY_PY_USSL_FINALISER mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); #else mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); #endif o->base.type = &ussl_socket_type; o->sock = sock; int ret; mbedtls_ssl_init(&o->ssl); mbedtls_ssl_config_init(&o->conf); mbedtls_x509_crt_init(&o->cacert); mbedtls_x509_crt_init(&o->cert); mbedtls_pk_init(&o->pkey); mbedtls_ctr_drbg_init(&o->ctr_drbg); #ifdef MBEDTLS_DEBUG_C // Debug level (0-4) 1=warning, 2=info, 3=debug, 4=verbose mbedtls_debug_set_threshold(0); #endif mbedtls_entropy_init(&o->entropy); const byte seed[] = "upy"; ret = mbedtls_ctr_drbg_seed(&o->ctr_drbg, mbedtls_entropy_func, &o->entropy, seed, sizeof(seed)); if (ret != 0) { goto cleanup; } ret = mbedtls_ssl_config_defaults(&o->conf, args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { goto cleanup; } mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE); mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg); #ifdef MBEDTLS_DEBUG_C mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL); #endif ret = mbedtls_ssl_setup(&o->ssl, &o->conf); if (ret != 0) { goto cleanup; } if (args->server_hostname.u_obj != mp_const_none) { const char *sni = mp_obj_str_get_str(args->server_hostname.u_obj); ret = mbedtls_ssl_set_hostname(&o->ssl, sni); if (ret != 0) { goto cleanup; } } mbedtls_ssl_set_bio(&o->ssl, &o->sock, _mbedtls_ssl_send, _mbedtls_ssl_recv, NULL); if (args->key.u_obj != mp_const_none) { size_t key_len; const byte *key = (const byte *)mp_obj_str_get_data(args->key.u_obj, &key_len); // len should include terminating null ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0); if (ret != 0) { ret = MBEDTLS_ERR_PK_BAD_INPUT_DATA; // use general error for all key errors goto cleanup; } size_t cert_len; const byte *cert = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &cert_len); // len should include terminating null ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1); if (ret != 0) { ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA; // use general error for all cert errors goto cleanup; } ret = mbedtls_ssl_conf_own_cert(&o->conf, &o->cert, &o->pkey); if (ret != 0) { goto cleanup; } } if (args->do_handshake.u_bool) { while ((ret = mbedtls_ssl_handshake(&o->ssl)) != 0) { if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { goto cleanup; } } } return o; cleanup: mbedtls_pk_free(&o->pkey); mbedtls_x509_crt_free(&o->cert); mbedtls_x509_crt_free(&o->cacert); mbedtls_ssl_free(&o->ssl); mbedtls_ssl_config_free(&o->conf); mbedtls_ctr_drbg_free(&o->ctr_drbg); mbedtls_entropy_free(&o->entropy); if (ret == MBEDTLS_ERR_SSL_ALLOC_FAILED) { mp_raise_OSError(MP_ENOMEM); } else if (ret == MBEDTLS_ERR_PK_BAD_INPUT_DATA) { mp_raise_ValueError(MP_ERROR_TEXT("invalid key")); } else if (ret == MBEDTLS_ERR_X509_BAD_INPUT_DATA) { mp_raise_ValueError(MP_ERROR_TEXT("invalid cert")); } else { mbedtls_raise_error(ret); } } STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); if (!mp_obj_is_true(binary_form)) { mp_raise_NotImplementedError(NULL); } const mbedtls_x509_crt *peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl); if (peer_cert == NULL) { return mp_const_none; } return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert); STATIC void socket_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<_SSLSocket %p>", self); } STATIC mp_uint_t socket_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); int ret = mbedtls_ssl_read(&o->ssl, buf, size); if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { // end of stream return 0; } if (ret >= 0) { return ret; } if (ret == MBEDTLS_ERR_SSL_WANT_READ) { ret = MP_EWOULDBLOCK; } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { // If handshake is not finished, read attempt may end up in protocol // wanting to write next handshake message. The same may happen with // renegotation. ret = MP_EWOULDBLOCK; } *errcode = ret; return MP_STREAM_ERROR; } STATIC mp_uint_t socket_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(o_in); int ret = mbedtls_ssl_write(&o->ssl, buf, size); if (ret >= 0) { return ret; } if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) { ret = MP_EWOULDBLOCK; } else if (ret == MBEDTLS_ERR_SSL_WANT_READ) { // If handshake is not finished, write attempt may end up in protocol // wanting to read next handshake message. The same may happen with // renegotation. ret = MP_EWOULDBLOCK; } *errcode = ret; return MP_STREAM_ERROR; } STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t flag_in) { mp_obj_ssl_socket_t *o = MP_OBJ_TO_PTR(self_in); mp_obj_t sock = o->sock; mp_obj_t dest[3]; mp_load_method(sock, MP_QSTR_setblocking, dest); dest[2] = flag_in; return mp_call_method_n_kw(1, 0, dest); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); STATIC mp_uint_t socket_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_ssl_socket_t *self = MP_OBJ_TO_PTR(o_in); if (request == MP_STREAM_CLOSE) { mbedtls_pk_free(&self->pkey); mbedtls_x509_crt_free(&self->cert); mbedtls_x509_crt_free(&self->cacert); mbedtls_ssl_free(&self->ssl); mbedtls_ssl_config_free(&self->conf); mbedtls_ctr_drbg_free(&self->ctr_drbg); mbedtls_entropy_free(&self->entropy); } // Pass all requests down to the underlying socket return mp_get_stream(self->sock)->ioctl(self->sock, request, arg, errcode); } STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, #if MICROPY_PY_USSL_FINALISER { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) }, }; STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table); STATIC const mp_stream_p_t ussl_socket_stream_p = { .read = socket_read, .write = socket_write, .ioctl = socket_ioctl, }; STATIC const mp_obj_type_t ussl_socket_type = { { &mp_type_type }, // Save on qstr's, reuse same as for module .name = MP_QSTR_ussl, .print = socket_print, .getiter = NULL, .iternext = NULL, .protocol = &ussl_socket_stream_p, .locals_dict = (void *)&ussl_socket_locals_dict, }; STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { // TODO: Implement more args static const mp_arg_t allowed_args[] = { { MP_QSTR_key, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_cert, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_do_handshake, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, }; // TODO: Check that sock implements stream protocol mp_obj_t sock = pos_args[0]; struct ssl_args args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); return MP_OBJ_FROM_PTR(socket_new(sock, &args)); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 1, mod_ssl_wrap_socket); STATIC const mp_rom_map_elem_t mp_module_ssl_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ussl) }, { MP_ROM_QSTR(MP_QSTR_wrap_socket), MP_ROM_PTR(&mod_ssl_wrap_socket_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table); const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_ssl_globals, }; #endif // MICROPY_PY_USSL
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modussl_mbedtls.c
C
apache-2.0
14,950
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George * Copyright (c) 2016-2017 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <string.h> #include "py/objlist.h" #include "py/runtime.h" #include "py/smallint.h" #if MICROPY_PY_UTIMEQ #define MODULO MICROPY_PY_UTIME_TICKS_PERIOD #define DEBUG 0 // the algorithm here is modelled on CPython's heapq.py struct qentry { mp_uint_t time; mp_uint_t id; mp_obj_t callback; mp_obj_t args; }; typedef struct _mp_obj_utimeq_t { mp_obj_base_t base; mp_uint_t alloc; mp_uint_t len; struct qentry items[]; } mp_obj_utimeq_t; STATIC mp_uint_t utimeq_id; STATIC mp_obj_utimeq_t *utimeq_get_heap(mp_obj_t heap_in) { return MP_OBJ_TO_PTR(heap_in); } STATIC bool time_less_than(struct qentry *item, struct qentry *parent) { mp_uint_t item_tm = item->time; mp_uint_t parent_tm = parent->time; mp_uint_t res = parent_tm - item_tm; if (res == 0) { // TODO: This actually should use the same "ring" logic // as for time, to avoid artifacts when id's overflow. return item->id < parent->id; } if ((mp_int_t)res < 0) { res += MODULO; } return res && res < (MODULO / 2); } STATIC mp_obj_t utimeq_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 1, false); mp_uint_t alloc = mp_obj_get_int(args[0]); mp_obj_utimeq_t *o = m_new_obj_var(mp_obj_utimeq_t, struct qentry, alloc); o->base.type = type; memset(o->items, 0, sizeof(*o->items) * alloc); o->alloc = alloc; o->len = 0; return MP_OBJ_FROM_PTR(o); } STATIC void utimeq_heap_siftdown(mp_obj_utimeq_t *heap, mp_uint_t start_pos, mp_uint_t pos) { struct qentry item = heap->items[pos]; while (pos > start_pos) { mp_uint_t parent_pos = (pos - 1) >> 1; struct qentry *parent = &heap->items[parent_pos]; bool lessthan = time_less_than(&item, parent); if (lessthan) { heap->items[pos] = *parent; pos = parent_pos; } else { break; } } heap->items[pos] = item; } STATIC void utimeq_heap_siftup(mp_obj_utimeq_t *heap, mp_uint_t pos) { mp_uint_t start_pos = pos; mp_uint_t end_pos = heap->len; struct qentry item = heap->items[pos]; for (mp_uint_t child_pos = 2 * pos + 1; child_pos < end_pos; child_pos = 2 * pos + 1) { // choose right child if it's <= left child if (child_pos + 1 < end_pos) { bool lessthan = time_less_than(&heap->items[child_pos], &heap->items[child_pos + 1]); if (!lessthan) { child_pos += 1; } } // bubble up the smaller child heap->items[pos] = heap->items[child_pos]; pos = child_pos; } heap->items[pos] = item; utimeq_heap_siftdown(heap, start_pos, pos); } STATIC mp_obj_t mod_utimeq_heappush(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_t heap_in = args[0]; mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); if (heap->len == heap->alloc) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("queue overflow")); } mp_uint_t l = heap->len; heap->items[l].time = MP_OBJ_SMALL_INT_VALUE(args[1]); heap->items[l].id = utimeq_id++; heap->items[l].callback = args[2]; heap->items[l].args = args[3]; utimeq_heap_siftdown(heap, 0, heap->len); heap->len++; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_utimeq_heappush_obj, 4, 4, mod_utimeq_heappush); STATIC mp_obj_t mod_utimeq_heappop(mp_obj_t heap_in, mp_obj_t list_ref) { mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); if (heap->len == 0) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty heap")); } mp_obj_list_t *ret = MP_OBJ_TO_PTR(list_ref); if (!mp_obj_is_type(list_ref, &mp_type_list) || ret->len < 3) { mp_raise_TypeError(NULL); } struct qentry *item = &heap->items[0]; ret->items[0] = MP_OBJ_NEW_SMALL_INT(item->time); ret->items[1] = item->callback; ret->items[2] = item->args; heap->len -= 1; heap->items[0] = heap->items[heap->len]; heap->items[heap->len].callback = MP_OBJ_NULL; // so we don't retain a pointer heap->items[heap->len].args = MP_OBJ_NULL; if (heap->len) { utimeq_heap_siftup(heap, 0); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_utimeq_heappop_obj, mod_utimeq_heappop); STATIC mp_obj_t mod_utimeq_peektime(mp_obj_t heap_in) { mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); if (heap->len == 0) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty heap")); } struct qentry *item = &heap->items[0]; return MP_OBJ_NEW_SMALL_INT(item->time); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_peektime_obj, mod_utimeq_peektime); #if DEBUG STATIC mp_obj_t mod_utimeq_dump(mp_obj_t heap_in) { mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); for (int i = 0; i < heap->len; i++) { printf(UINT_FMT "\t%p\t%p\n", heap->items[i].time, MP_OBJ_TO_PTR(heap->items[i].callback), MP_OBJ_TO_PTR(heap->items[i].args)); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump); #endif STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0); case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len); default: return MP_OBJ_NULL; // op not supported } } STATIC const mp_rom_map_elem_t utimeq_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_push), MP_ROM_PTR(&mod_utimeq_heappush_obj) }, { MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&mod_utimeq_heappop_obj) }, { MP_ROM_QSTR(MP_QSTR_peektime), MP_ROM_PTR(&mod_utimeq_peektime_obj) }, #if DEBUG { MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&mod_utimeq_dump_obj) }, #endif }; STATIC MP_DEFINE_CONST_DICT(utimeq_locals_dict, utimeq_locals_dict_table); STATIC const mp_obj_type_t utimeq_type = { { &mp_type_type }, .name = MP_QSTR_utimeq, .make_new = utimeq_make_new, .unary_op = utimeq_unary_op, .locals_dict = (void *)&utimeq_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_utimeq_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_utimeq) }, { MP_ROM_QSTR(MP_QSTR_utimeq), MP_ROM_PTR(&utimeq_type) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_utimeq_globals, mp_module_utimeq_globals_table); const mp_obj_module_t mp_module_utimeq = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_utimeq_globals, }; #endif // MICROPY_PY_UTIMEQ
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modutimeq.c
C
apache-2.0
7,973
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "extmod/moduwebsocket.h" #if MICROPY_PY_UWEBSOCKET enum { FRAME_HEADER, FRAME_OPT, PAYLOAD, CONTROL }; enum { BLOCKING_WRITE = 0x80 }; typedef struct _mp_obj_websocket_t { mp_obj_base_t base; mp_obj_t sock; uint32_t msg_sz; byte mask[4]; byte state; byte to_recv; byte mask_pos; byte buf_pos; byte buf[6]; byte opts; // Copy of last data frame flags byte ws_flags; // Copy of current frame flags byte last_flags; } mp_obj_websocket_t; STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode); STATIC mp_obj_t websocket_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 2, false); mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); mp_obj_websocket_t *o = m_new_obj(mp_obj_websocket_t); o->base.type = type; o->sock = args[0]; o->state = FRAME_HEADER; o->to_recv = 2; o->mask_pos = 0; o->buf_pos = 0; o->opts = FRAME_TXT; if (n_args > 1 && args[1] == mp_const_true) { o->opts |= BLOCKING_WRITE; } return MP_OBJ_FROM_PTR(o); } STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); const mp_stream_p_t *stream_p = mp_get_stream(self->sock); while (1) { if (self->to_recv != 0) { mp_uint_t out_sz = stream_p->read(self->sock, self->buf + self->buf_pos, self->to_recv, errcode); if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { return out_sz; } self->buf_pos += out_sz; self->to_recv -= out_sz; if (self->to_recv != 0) { *errcode = MP_EAGAIN; return MP_STREAM_ERROR; } } switch (self->state) { case FRAME_HEADER: { // TODO: Split frame handling below is untested so far, so conservatively disable it assert(self->buf[0] & 0x80); // "Control frames MAY be injected in the middle of a fragmented message." // So, they must be processed before data frames (and not alter // self->ws_flags) byte frame_type = self->buf[0]; self->last_flags = frame_type; frame_type &= FRAME_OPCODE_MASK; if ((self->buf[0] & FRAME_OPCODE_MASK) == FRAME_CONT) { // Preserve previous frame type self->ws_flags = (self->ws_flags & FRAME_OPCODE_MASK) | (self->buf[0] & ~FRAME_OPCODE_MASK); } else { self->ws_flags = self->buf[0]; } // Reset mask in case someone will use "simplified" protocol // without masks. memset(self->mask, 0, sizeof(self->mask)); int to_recv = 0; size_t sz = self->buf[1] & 0x7f; if (sz == 126) { // Msg size is next 2 bytes to_recv += 2; } else if (sz == 127) { // Msg size is next 8 bytes assert(0); } if (self->buf[1] & 0x80) { // Next 4 bytes is mask to_recv += 4; } self->buf_pos = 0; self->to_recv = to_recv; self->msg_sz = sz; // May be overridden by FRAME_OPT if (to_recv != 0) { self->state = FRAME_OPT; } else { if (frame_type >= FRAME_CLOSE) { self->state = CONTROL; } else { self->state = PAYLOAD; } } continue; } case FRAME_OPT: { if ((self->buf_pos & 3) == 2) { // First two bytes are message length self->msg_sz = (self->buf[0] << 8) | self->buf[1]; } if (self->buf_pos >= 4) { // Last 4 bytes is mask memcpy(self->mask, self->buf + self->buf_pos - 4, 4); } self->buf_pos = 0; if ((self->last_flags & FRAME_OPCODE_MASK) >= FRAME_CLOSE) { self->state = CONTROL; } else { self->state = PAYLOAD; } continue; } case PAYLOAD: case CONTROL: { mp_uint_t out_sz = 0; if (self->msg_sz == 0) { // In case message had zero payload goto no_payload; } size_t sz = MIN(size, self->msg_sz); out_sz = stream_p->read(self->sock, buf, sz, errcode); if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { return out_sz; } sz = out_sz; for (byte *p = buf; sz--; p++) { *p ^= self->mask[self->mask_pos++ & 3]; } self->msg_sz -= out_sz; if (self->msg_sz == 0) { byte last_state; no_payload: last_state = self->state; self->state = FRAME_HEADER; self->to_recv = 2; self->mask_pos = 0; self->buf_pos = 0; // Handle control frame if (last_state == CONTROL) { byte frame_type = self->last_flags & FRAME_OPCODE_MASK; if (frame_type == FRAME_CLOSE) { static const char close_resp[2] = {0x88, 0}; int err; websocket_write(self_in, close_resp, sizeof(close_resp), &err); return 0; } // DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); continue; } } if (out_sz != 0) { return out_sz; } // Empty (data) frame received is not EOF continue; } } } } STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); assert(size < 0x10000); byte header[4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)}; int hdr_sz; if (size < 126) { header[1] = size; hdr_sz = 2; } else { header[1] = 126; header[2] = size >> 8; header[3] = size & 0xff; hdr_sz = 4; } mp_obj_t dest[3]; if (self->opts & BLOCKING_WRITE) { mp_load_method(self->sock, MP_QSTR_setblocking, dest); dest[2] = mp_const_true; mp_call_method_n_kw(1, 0, dest); } mp_uint_t out_sz = mp_stream_write_exactly(self->sock, header, hdr_sz, errcode); if (*errcode == 0) { out_sz = mp_stream_write_exactly(self->sock, buf, size, errcode); } if (self->opts & BLOCKING_WRITE) { dest[2] = mp_const_false; mp_call_method_n_kw(1, 0, dest); } if (*errcode != 0) { return MP_STREAM_ERROR; } return out_sz; } STATIC mp_uint_t websocket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); switch (request) { case MP_STREAM_CLOSE: // TODO: Send close signaling to the other side, otherwise it's // abrupt close (connection abort). mp_stream_close(self->sock); return 0; case MP_STREAM_GET_DATA_OPTS: return self->ws_flags & FRAME_OPCODE_MASK; case MP_STREAM_SET_DATA_OPTS: { int cur = self->opts & FRAME_OPCODE_MASK; self->opts = (self->opts & ~FRAME_OPCODE_MASK) | (arg & FRAME_OPCODE_MASK); return cur; } default: *errcode = MP_EINVAL; return MP_STREAM_ERROR; } } STATIC const mp_rom_map_elem_t websocket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&mp_stream_ioctl_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, }; STATIC MP_DEFINE_CONST_DICT(websocket_locals_dict, websocket_locals_dict_table); STATIC const mp_stream_p_t websocket_stream_p = { .read = websocket_read, .write = websocket_write, .ioctl = websocket_ioctl, }; STATIC const mp_obj_type_t websocket_type = { { &mp_type_type }, .name = MP_QSTR_websocket, .make_new = websocket_make_new, .protocol = &websocket_stream_p, .locals_dict = (void *)&websocket_locals_dict, }; STATIC const mp_rom_map_elem_t uwebsocket_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uwebsocket) }, { MP_ROM_QSTR(MP_QSTR_websocket), MP_ROM_PTR(&websocket_type) }, }; STATIC MP_DEFINE_CONST_DICT(uwebsocket_module_globals, uwebsocket_module_globals_table); const mp_obj_module_t mp_module_uwebsocket = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&uwebsocket_module_globals, }; #endif // MICROPY_PY_UWEBSOCKET
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduwebsocket.c
C
apache-2.0
11,159
#ifndef MICROPY_INCLUDED_EXTMOD_MODUWEBSOCKET_H #define MICROPY_INCLUDED_EXTMOD_MODUWEBSOCKET_H #define FRAME_OPCODE_MASK 0x0f enum { FRAME_CONT, FRAME_TXT, FRAME_BIN, FRAME_CLOSE = 0x8, FRAME_PING, FRAME_PONG }; #endif // MICROPY_INCLUDED_EXTMOD_MODUWEBSOCKET_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduwebsocket.h
C
apache-2.0
273
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014-2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "py/mperrno.h" #if MICROPY_PY_UZLIB #include "lib/uzlib/tinf.h" #if 0 // print debugging info #define DEBUG_printf DEBUG_printf #else // don't print debugging info #define DEBUG_printf(...) (void)0 #endif typedef struct _mp_obj_decompio_t { mp_obj_base_t base; mp_obj_t src_stream; TINF_DATA decomp; bool eof; } mp_obj_decompio_t; STATIC int read_src_stream(TINF_DATA *data) { byte *p = (void *)data; p -= offsetof(mp_obj_decompio_t, decomp); mp_obj_decompio_t *self = (mp_obj_decompio_t *)p; const mp_stream_p_t *stream = mp_get_stream(self->src_stream); int err; byte c; mp_uint_t out_sz = stream->read(self->src_stream, &c, 1, &err); if (out_sz == MP_STREAM_ERROR) { mp_raise_OSError(err); } if (out_sz == 0) { mp_raise_type(&mp_type_EOFError); } return c; } STATIC mp_obj_t decompio_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 2, false); mp_get_stream_raise(args[0], MP_STREAM_OP_READ); mp_obj_decompio_t *o = m_new_obj(mp_obj_decompio_t); o->base.type = type; memset(&o->decomp, 0, sizeof(o->decomp)); o->decomp.readSource = read_src_stream; o->src_stream = args[0]; o->eof = false; mp_int_t dict_opt = 0; int dict_sz; if (n_args > 1) { dict_opt = mp_obj_get_int(args[1]); } if (dict_opt >= 16) { int st = uzlib_gzip_parse_header(&o->decomp); if (st != TINF_OK) { goto header_error; } dict_sz = 1 << (dict_opt - 16); } else if (dict_opt >= 0) { dict_opt = uzlib_zlib_parse_header(&o->decomp); if (dict_opt < 0) { header_error: mp_raise_ValueError(MP_ERROR_TEXT("compression header")); } dict_sz = 1 << dict_opt; } else { dict_sz = 1 << -dict_opt; } uzlib_uncompress_init(&o->decomp, m_new(byte, dict_sz), dict_sz); return MP_OBJ_FROM_PTR(o); } STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { mp_obj_decompio_t *o = MP_OBJ_TO_PTR(o_in); if (o->eof) { return 0; } o->decomp.dest = buf; o->decomp.dest_limit = (byte *)buf + size; int st = uzlib_uncompress_chksum(&o->decomp); if (st == TINF_DONE) { o->eof = true; } if (st < 0) { *errcode = MP_EINVAL; return MP_STREAM_ERROR; } return o->decomp.dest - (byte *)buf; } #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t decompio_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, }; STATIC MP_DEFINE_CONST_DICT(decompio_locals_dict, decompio_locals_dict_table); #endif STATIC const mp_stream_p_t decompio_stream_p = { .read = decompio_read, }; #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_obj_type_t decompio_type = { { &mp_type_type }, .name = MP_QSTR_DecompIO, .make_new = decompio_make_new, .protocol = &decompio_stream_p, .locals_dict = (void *)&decompio_locals_dict, }; #endif STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { mp_obj_t data = args[0]; mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); TINF_DATA *decomp = m_new_obj(TINF_DATA); memset(decomp, 0, sizeof(*decomp)); DEBUG_printf("sizeof(TINF_DATA)=" UINT_FMT "\n", sizeof(*decomp)); uzlib_uncompress_init(decomp, NULL, 0); mp_uint_t dest_buf_size = (bufinfo.len + 15) & ~15; byte *dest_buf = m_new(byte, dest_buf_size); decomp->dest = dest_buf; decomp->dest_limit = dest_buf + dest_buf_size; DEBUG_printf("uzlib: Initial out buffer: " UINT_FMT " bytes\n", dest_buf_size); decomp->source = bufinfo.buf; decomp->source_limit = (byte *)bufinfo.buf + bufinfo.len; int st; bool is_zlib = true; if (n_args > 1 && MP_OBJ_SMALL_INT_VALUE(args[1]) < 0) { is_zlib = false; } if (is_zlib) { st = uzlib_zlib_parse_header(decomp); if (st < 0) { goto error; } } while (1) { st = uzlib_uncompress_chksum(decomp); if (st < 0) { goto error; } if (st == TINF_DONE) { break; } size_t offset = decomp->dest - dest_buf; dest_buf = m_renew(byte, dest_buf, dest_buf_size, dest_buf_size + 256); dest_buf_size += 256; decomp->dest = dest_buf + offset; decomp->dest_limit = decomp->dest + 256; } mp_uint_t final_sz = decomp->dest - dest_buf; DEBUG_printf("uzlib: Resizing from " UINT_FMT " to final size: " UINT_FMT " bytes\n", dest_buf_size, final_sz); dest_buf = (byte *)m_renew(byte, dest_buf, dest_buf_size, final_sz); mp_obj_t res = mp_obj_new_bytearray_by_ref(final_sz, dest_buf); m_del_obj(TINF_DATA, decomp); return res; error: mp_raise_type_arg(&mp_type_ValueError, MP_OBJ_NEW_SMALL_INT(st)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_uzlib_decompress_obj, 1, 3, mod_uzlib_decompress); #if !MICROPY_ENABLE_DYNRUNTIME STATIC const mp_rom_map_elem_t mp_module_uzlib_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uzlib) }, { MP_ROM_QSTR(MP_QSTR_decompress), MP_ROM_PTR(&mod_uzlib_decompress_obj) }, { MP_ROM_QSTR(MP_QSTR_DecompIO), MP_ROM_PTR(&decompio_type) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_uzlib_globals, mp_module_uzlib_globals_table); const mp_obj_module_t mp_module_uzlib = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&mp_module_uzlib_globals, }; #endif // Source files #include'd here to make sure they're compiled in // only if module is enabled by config setting. #include "lib/uzlib/tinflate.c" #include "lib/uzlib/tinfzlib.c" #include "lib/uzlib/tinfgzip.c" #include "lib/uzlib/adler32.c" #include "lib/uzlib/crc32.c" #endif // MICROPY_PY_UZLIB
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/moduzlib.c
C
apache-2.0
7,410
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <stdint.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "py/builtin.h" #ifdef MICROPY_PY_WEBREPL_DELAY #include "py/mphal.h" #endif #include "extmod/moduwebsocket.h" #if MICROPY_PY_WEBREPL #if 0 // print debugging info #define DEBUG_printf DEBUG_printf #else // don't print debugging info #define DEBUG_printf(...) (void)0 #endif struct webrepl_file { char sig[2]; char type; char flags; uint64_t offset; uint32_t size; uint16_t fname_len; char fname[64]; } __attribute__((packed)); enum { PUT_FILE = 1, GET_FILE, GET_VER }; enum { STATE_PASSWD, STATE_NORMAL }; typedef struct _mp_obj_webrepl_t { mp_obj_base_t base; mp_obj_t sock; byte state; byte hdr_to_recv; uint32_t data_to_recv; struct webrepl_file hdr; mp_obj_t cur_file; } mp_obj_webrepl_t; STATIC const char passwd_prompt[] = "Password: "; STATIC const char connected_prompt[] = "\r\nWebREPL connected\r\n>>> "; STATIC const char denied_prompt[] = "\r\nAccess denied\r\n"; STATIC char webrepl_passwd[10]; STATIC void write_webrepl(mp_obj_t websock, const void *buf, size_t len) { const mp_stream_p_t *sock_stream = mp_get_stream(websock); int err; int old_opts = sock_stream->ioctl(websock, MP_STREAM_SET_DATA_OPTS, FRAME_BIN, &err); sock_stream->write(websock, buf, len, &err); sock_stream->ioctl(websock, MP_STREAM_SET_DATA_OPTS, old_opts, &err); } #define SSTR(s) s, sizeof(s) - 1 STATIC void write_webrepl_str(mp_obj_t websock, const char *str, int sz) { int err; const mp_stream_p_t *sock_stream = mp_get_stream(websock); sock_stream->write(websock, str, sz, &err); } STATIC void write_webrepl_resp(mp_obj_t websock, uint16_t code) { char buf[4] = {'W', 'B', code & 0xff, code >> 8}; write_webrepl(websock, buf, sizeof(buf)); } STATIC mp_obj_t webrepl_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 2, false); mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); DEBUG_printf("sizeof(struct webrepl_file) = %lu\n", sizeof(struct webrepl_file)); mp_obj_webrepl_t *o = m_new_obj(mp_obj_webrepl_t); o->base.type = type; o->sock = args[0]; o->hdr_to_recv = sizeof(struct webrepl_file); o->data_to_recv = 0; o->state = STATE_PASSWD; write_webrepl_str(args[0], SSTR(passwd_prompt)); return MP_OBJ_FROM_PTR(o); } STATIC void check_file_op_finished(mp_obj_webrepl_t *self) { if (self->data_to_recv == 0) { mp_stream_close(self->cur_file); self->hdr_to_recv = sizeof(struct webrepl_file); DEBUG_printf("webrepl: Finished file operation %d\n", self->hdr.type); write_webrepl_resp(self->sock, 0); } } STATIC int write_file_chunk(mp_obj_webrepl_t *self) { const mp_stream_p_t *file_stream = mp_get_stream(self->cur_file); byte readbuf[2 + 256]; int err; mp_uint_t out_sz = file_stream->read(self->cur_file, readbuf + 2, sizeof(readbuf) - 2, &err); if (out_sz == MP_STREAM_ERROR) { return out_sz; } readbuf[0] = out_sz; readbuf[1] = out_sz >> 8; DEBUG_printf("webrepl: Sending %d bytes of file\n", out_sz); write_webrepl(self->sock, readbuf, 2 + out_sz); return out_sz; } STATIC void handle_op(mp_obj_webrepl_t *self) { // Handle operations not requiring opened file switch (self->hdr.type) { case GET_VER: { static const char ver[] = {MICROPY_VERSION_MAJOR, MICROPY_VERSION_MINOR, MICROPY_VERSION_MICRO}; write_webrepl(self->sock, ver, sizeof(ver)); self->hdr_to_recv = sizeof(struct webrepl_file); return; } } // Handle operations requiring opened file mp_obj_t open_args[2] = { mp_obj_new_str(self->hdr.fname, strlen(self->hdr.fname)), MP_OBJ_NEW_QSTR(MP_QSTR_rb) }; if (self->hdr.type == PUT_FILE) { open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb); } self->cur_file = mp_builtin_open(2, open_args, (mp_map_t *)&mp_const_empty_map); #if 0 struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 }; int err; mp_uint_t res = file_stream->ioctl(self->cur_file, MP_STREAM_SEEK, (uintptr_t)&seek, &err); assert(res != MP_STREAM_ERROR); #endif write_webrepl_resp(self->sock, 0); if (self->hdr.type == PUT_FILE) { self->data_to_recv = self->hdr.size; check_file_op_finished(self); } else if (self->hdr.type == GET_FILE) { self->data_to_recv = 1; } } STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode); STATIC mp_uint_t webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { mp_uint_t out_sz; do { out_sz = _webrepl_read(self_in, buf, size, errcode); } while (out_sz == -2); return out_sz; } STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { // We know that os.dupterm always calls with size = 1 assert(size == 1); mp_obj_webrepl_t *self = MP_OBJ_TO_PTR(self_in); const mp_stream_p_t *sock_stream = mp_get_stream(self->sock); mp_uint_t out_sz = sock_stream->read(self->sock, buf, size, errcode); // DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz); if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { return out_sz; } if (self->state == STATE_PASSWD) { char c = *(char *)buf; if (c == '\r' || c == '\n') { self->hdr.fname[self->data_to_recv] = 0; DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname); if (strcmp(self->hdr.fname, webrepl_passwd) != 0) { write_webrepl_str(self->sock, SSTR(denied_prompt)); return 0; } self->state = STATE_NORMAL; self->data_to_recv = 0; write_webrepl_str(self->sock, SSTR(connected_prompt)); } else if (self->data_to_recv < 10) { self->hdr.fname[self->data_to_recv++] = c; } return -2; } // If last read data belonged to text record (== REPL) int err; if (sock_stream->ioctl(self->sock, MP_STREAM_GET_DATA_OPTS, 0, &err) == 1) { return out_sz; } DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv); if (self->hdr_to_recv != 0) { char *p = (char *)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv; *p++ = *(char *)buf; if (--self->hdr_to_recv != 0) { mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode); if (hdr_sz == MP_STREAM_ERROR) { return hdr_sz; } self->hdr_to_recv -= hdr_sz; if (self->hdr_to_recv != 0) { return -2; } } DEBUG_printf("webrepl: op: %d, file: %s, chunk @%x, sz=%d\n", self->hdr.type, self->hdr.fname, (uint32_t)self->hdr.offset, self->hdr.size); handle_op(self); return -2; } if (self->data_to_recv != 0) { // Ports that don't have much available stack can make this filebuf static #if MICROPY_PY_WEBREPL_STATIC_FILEBUF static #endif byte filebuf[512]; filebuf[0] = *(byte *)buf; mp_uint_t buf_sz = 1; if (--self->data_to_recv != 0) { size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv); mp_uint_t sz = sock_stream->read(self->sock, filebuf + 1, to_read, errcode); if (sz == MP_STREAM_ERROR) { return sz; } self->data_to_recv -= sz; buf_sz += sz; } if (self->hdr.type == PUT_FILE) { DEBUG_printf("webrepl: Writing %lu bytes to file\n", buf_sz); int err; mp_uint_t res = mp_stream_write_exactly(self->cur_file, filebuf, buf_sz, &err); if (err != 0 || res != buf_sz) { assert(0); } } else if (self->hdr.type == GET_FILE) { assert(buf_sz == 1); assert(self->data_to_recv == 0); assert(filebuf[0] == 0); mp_uint_t out_sz = write_file_chunk(self); if (out_sz != 0) { self->data_to_recv = 1; } } check_file_op_finished(self); #ifdef MICROPY_PY_WEBREPL_DELAY // Some platforms may have broken drivers and easily gets // overloaded with modest traffic WebREPL file transfers // generate. The basic workaround is a crude rate control // done in such way. mp_hal_delay_ms(MICROPY_PY_WEBREPL_DELAY); #endif } return -2; } STATIC mp_uint_t webrepl_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { mp_obj_webrepl_t *self = MP_OBJ_TO_PTR(self_in); if (self->state == STATE_PASSWD) { // Don't forward output until passwd is entered return size; } const mp_stream_p_t *stream_p = mp_get_stream(self->sock); return stream_p->write(self->sock, buf, size, errcode); } STATIC mp_uint_t webrepl_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_webrepl_t *self = MP_OBJ_TO_PTR(o_in); (void)arg; switch (request) { case MP_STREAM_CLOSE: // TODO: This is a place to do cleanup mp_stream_close(self->sock); return 0; default: *errcode = MP_EINVAL; return MP_STREAM_ERROR; } } STATIC mp_obj_t webrepl_set_password(mp_obj_t passwd_in) { size_t len; const char *passwd = mp_obj_str_get_data(passwd_in, &len); if (len > sizeof(webrepl_passwd) - 1) { mp_raise_ValueError(NULL); } strcpy(webrepl_passwd, passwd); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(webrepl_set_password_obj, webrepl_set_password); STATIC const mp_rom_map_elem_t webrepl_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, }; STATIC MP_DEFINE_CONST_DICT(webrepl_locals_dict, webrepl_locals_dict_table); STATIC const mp_stream_p_t webrepl_stream_p = { .read = webrepl_read, .write = webrepl_write, .ioctl = webrepl_ioctl, }; STATIC const mp_obj_type_t webrepl_type = { { &mp_type_type }, .name = MP_QSTR__webrepl, .make_new = webrepl_make_new, .protocol = &webrepl_stream_p, .locals_dict = (mp_obj_dict_t *)&webrepl_locals_dict, }; STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__webrepl) }, { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&webrepl_type) }, { MP_ROM_QSTR(MP_QSTR_password), MP_ROM_PTR(&webrepl_set_password_obj) }, }; STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table); const mp_obj_module_t mp_module_webrepl = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t *)&webrepl_module_globals, }; #endif // MICROPY_PY_WEBREPL
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/modwebrepl.c
C
apache-2.0
12,597
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2020 Jim Mussared * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ // Default definitions in case a controller doesn't implement this. #include "py/mphal.h" #if MICROPY_PY_BLUETOOTH #define DEBUG_printf(...) // printf(__VA_ARGS__) #include "extmod/mpbthci.h" #endif // MICROPY_PY_BLUETOOTH
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/mpbthci.c
C
apache-2.0
1,451
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_MPBTHCI_H #define MICROPY_INCLUDED_EXTMOD_MPBTHCI_H // --- Optionally can be implemented by the driver. --------------------------- // Start/stop the HCI controller. // Requires the UART to this HCI controller is available. int mp_bluetooth_hci_controller_init(void); int mp_bluetooth_hci_controller_deinit(void); // Tell the controller to go to sleep (e.g. on RX if we don't think we're expecting anything more). int mp_bluetooth_hci_controller_sleep_maybe(void); // True if the controller woke us up. bool mp_bluetooth_hci_controller_woken(void); // Wake up the controller (e.g. we're about to TX). int mp_bluetooth_hci_controller_wakeup(void); // --- Bindings that need to be implemented by the port. ---------------------- int mp_bluetooth_hci_uart_init(uint32_t port, uint32_t baudrate); int mp_bluetooth_hci_uart_deinit(void); int mp_bluetooth_hci_uart_set_baudrate(uint32_t baudrate); int mp_bluetooth_hci_uart_readchar(void); int mp_bluetooth_hci_uart_write(const uint8_t *buf, size_t len); #endif // MICROPY_INCLUDED_EXTMOD_MPBTHCI_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/mpbthci.h
C
apache-2.0
2,306
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/objstr.h" #include "py/mphal.h" #if MICROPY_PY_NETWORK_CYW43 #include "lwip/netif.h" #include "drivers/cyw43/cyw43.h" #include "extmod/network_cyw43.h" #include "modnetwork.h" typedef struct _network_cyw43_obj_t { mp_obj_base_t base; cyw43_t *cyw; int itf; } network_cyw43_obj_t; STATIC const network_cyw43_obj_t network_cyw43_wl0 = { { &mp_network_cyw43_type }, &cyw43_state, 0 }; STATIC const network_cyw43_obj_t network_cyw43_wl1 = { { &mp_network_cyw43_type }, &cyw43_state, 1 }; STATIC void network_cyw43_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(self_in); struct netif *netif = &self->cyw->netif[self->itf]; int status = cyw43_tcpip_link_status(self->cyw, self->itf); const char *status_str; if (status == CYW43_LINK_DOWN) { status_str = "down"; } else if (status == CYW43_LINK_JOIN || status == CYW43_LINK_NOIP) { status_str = "join"; } else if (status == CYW43_LINK_UP) { status_str = "up"; } else if (status == CYW43_LINK_NONET) { status_str = "nonet"; } else if (status == CYW43_LINK_BADAUTH) { status_str = "badauth"; } else { status_str = "fail"; } mp_printf(print, "<CYW43 %s %s %u.%u.%u.%u>", self->itf == 0 ? "STA" : "AP", status_str, netif->ip_addr.addr & 0xff, netif->ip_addr.addr >> 8 & 0xff, netif->ip_addr.addr >> 16 & 0xff, netif->ip_addr.addr >> 24 ); } STATIC mp_obj_t network_cyw43_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); if (n_args == 0 || mp_obj_get_int(args[0]) == 0) { return MP_OBJ_FROM_PTR(&network_cyw43_wl0); } else { return MP_OBJ_FROM_PTR(&network_cyw43_wl1); } } STATIC mp_obj_t network_cyw43_send_ethernet(mp_obj_t self_in, mp_obj_t buf_in) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t buf; mp_get_buffer_raise(buf_in, &buf, MP_BUFFER_READ); int ret = cyw43_send_ethernet(self->cyw, self->itf, buf.len, buf.buf, false); if (ret) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(network_cyw43_send_ethernet_obj, network_cyw43_send_ethernet); STATIC mp_obj_t network_cyw43_ioctl(mp_obj_t self_in, mp_obj_t cmd_in, mp_obj_t buf_in) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t buf; mp_get_buffer_raise(buf_in, &buf, MP_BUFFER_READ | MP_BUFFER_WRITE); cyw43_ioctl(self->cyw, mp_obj_get_int(cmd_in), buf.len, buf.buf, self->itf); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(network_cyw43_ioctl_obj, network_cyw43_ioctl); /*******************************************************************************/ // network API STATIC mp_obj_t network_cyw43_deinit(mp_obj_t self_in) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(self_in); cyw43_deinit(self->cyw); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_cyw43_deinit_obj, network_cyw43_deinit); STATIC mp_obj_t network_cyw43_active(size_t n_args, const mp_obj_t *args) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(args[0]); if (n_args == 1) { return mp_obj_new_bool(cyw43_tcpip_link_status(self->cyw, self->itf)); } else { cyw43_wifi_set_up(self->cyw, self->itf, mp_obj_is_true(args[1])); return mp_const_none; } } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_cyw43_active_obj, 1, 2, network_cyw43_active); STATIC int network_cyw43_scan_cb(void *env, const cyw43_ev_scan_result_t *res) { mp_obj_t list = MP_OBJ_FROM_PTR(env); // Search for existing BSSID to remove duplicates bool found = false; size_t len; mp_obj_t *items; mp_obj_get_array(list, &len, &items); for (size_t i = 0; i < len; ++i) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(items[i]); if (memcmp(res->bssid, ((mp_obj_str_t *)MP_OBJ_TO_PTR(t->items[1]))->data, sizeof(res->bssid)) == 0) { if (res->rssi > MP_OBJ_SMALL_INT_VALUE(t->items[3])) { t->items[3] = MP_OBJ_NEW_SMALL_INT(res->rssi); } t->items[5] = MP_OBJ_NEW_SMALL_INT(MP_OBJ_SMALL_INT_VALUE(t->items[5]) + 1); found = true; break; } } // Add to list of results if wanted if (!found) { mp_obj_t tuple[6] = { mp_obj_new_bytes(res->ssid, res->ssid_len), mp_obj_new_bytes(res->bssid, sizeof(res->bssid)), MP_OBJ_NEW_SMALL_INT(res->channel), MP_OBJ_NEW_SMALL_INT(res->rssi), MP_OBJ_NEW_SMALL_INT(res->auth_mode), // mp_const_false, // hidden MP_OBJ_NEW_SMALL_INT(1), // N }; mp_obj_list_append(list, mp_obj_new_tuple(6, tuple)); } return 0; // continue scan } STATIC mp_obj_t network_cyw43_scan(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_passive, ARG_essid, ARG_bssid }; static const mp_arg_t allowed_args[] = { { MP_QSTR_passive, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_essid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, }; network_cyw43_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); cyw43_wifi_scan_options_t opts; opts.scan_type = args[ARG_passive].u_bool ? 1 : 0; if (args[ARG_essid].u_obj == mp_const_none) { opts.ssid_len = 0; } else { mp_buffer_info_t ssid; mp_get_buffer_raise(args[ARG_essid].u_obj, &ssid, MP_BUFFER_READ); opts.ssid_len = MIN(ssid.len, sizeof(opts.ssid)); memcpy(opts.ssid, ssid.buf, opts.ssid_len); } if (args[ARG_bssid].u_obj == mp_const_none) { memset(opts.bssid, 0xff, sizeof(opts.bssid)); } else { mp_buffer_info_t bssid; mp_get_buffer_raise(args[ARG_bssid].u_obj, &bssid, MP_BUFFER_READ); memcpy(opts.bssid, bssid.buf, sizeof(opts.bssid)); } mp_obj_t res = mp_obj_new_list(0, NULL); int scan_res = cyw43_wifi_scan(self->cyw, &opts, MP_OBJ_TO_PTR(res), network_cyw43_scan_cb); if (scan_res < 0) { mp_raise_OSError(-scan_res); } // Wait for scan to finish, with a 10s timeout uint32_t start = mp_hal_ticks_ms(); while (cyw43_wifi_scan_active(self->cyw) && mp_hal_ticks_ms() - start < 10000) { MICROPY_EVENT_POLL_HOOK } return res; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(network_cyw43_scan_obj, 1, network_cyw43_scan); STATIC mp_obj_t network_cyw43_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_essid, ARG_key, ARG_auth, ARG_bssid, ARG_channel }; static const mp_arg_t allowed_args[] = { { MP_QSTR_essid, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_key, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_auth, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} }, { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} }, }; network_cyw43_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_buffer_info_t ssid; mp_get_buffer_raise(args[ARG_essid].u_obj, &ssid, MP_BUFFER_READ); mp_buffer_info_t key; key.buf = NULL; if (args[ARG_key].u_obj != mp_const_none) { mp_get_buffer_raise(args[ARG_key].u_obj, &key, MP_BUFFER_READ); } mp_buffer_info_t bssid; bssid.buf = NULL; if (args[ARG_bssid].u_obj != mp_const_none) { mp_get_buffer_raise(args[ARG_bssid].u_obj, &bssid, MP_BUFFER_READ); if (bssid.len != 6) { mp_raise_ValueError(NULL); } } int ret = cyw43_wifi_join(self->cyw, ssid.len, ssid.buf, key.len, key.buf, args[ARG_auth].u_int, bssid.buf, args[ARG_channel].u_int); if (ret != 0) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(network_cyw43_connect_obj, 1, network_cyw43_connect); STATIC mp_obj_t network_cyw43_disconnect(mp_obj_t self_in) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(self_in); cyw43_wifi_leave(self->cyw, self->itf); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_cyw43_disconnect_obj, network_cyw43_disconnect); STATIC mp_obj_t network_cyw43_isconnected(mp_obj_t self_in) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_bool(cyw43_tcpip_link_status(self->cyw, self->itf) == 3); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_cyw43_isconnected_obj, network_cyw43_isconnected); STATIC mp_obj_t network_cyw43_ifconfig(size_t n_args, const mp_obj_t *args) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(args[0]); return mod_network_nic_ifconfig(&self->cyw->netif[self->itf], n_args - 1, args + 1); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_cyw43_ifconfig_obj, 1, 2, network_cyw43_ifconfig); STATIC mp_obj_t network_cyw43_status(size_t n_args, const mp_obj_t *args) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(args[0]); (void)self; if (n_args == 1) { // no arguments: return link status return MP_OBJ_NEW_SMALL_INT(cyw43_tcpip_link_status(self->cyw, self->itf)); } // one argument: return status based on query parameter switch (mp_obj_str_get_qstr(args[1])) { case MP_QSTR_stations: { // return list of connected stations if (self->itf != CYW43_ITF_AP) { mp_raise_ValueError(MP_ERROR_TEXT("AP required")); } int num_stas; uint8_t macs[32 * 6]; cyw43_wifi_ap_get_stas(self->cyw, &num_stas, macs); mp_obj_t list = mp_obj_new_list(num_stas, NULL); for (int i = 0; i < num_stas; ++i) { mp_obj_t tuple[1] = { mp_obj_new_bytes(&macs[i * 6], 6), }; ((mp_obj_list_t *)MP_OBJ_TO_PTR(list))->items[i] = mp_obj_new_tuple(1, tuple); } return list; } } mp_raise_ValueError(MP_ERROR_TEXT("unknown status param")); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_cyw43_status_obj, 1, 2, network_cyw43_status); static inline uint32_t nw_get_le32(const uint8_t *buf) { return buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24; } static inline void nw_put_le32(uint8_t *buf, uint32_t x) { buf[0] = x; buf[1] = x >> 8; buf[2] = x >> 16; buf[3] = x >> 24; } STATIC mp_obj_t network_cyw43_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { network_cyw43_obj_t *self = MP_OBJ_TO_PTR(args[0]); if (kwargs->used == 0) { // Get config value if (n_args != 2) { mp_raise_TypeError(MP_ERROR_TEXT("must query one param")); } switch (mp_obj_str_get_qstr(args[1])) { case MP_QSTR_antenna: { uint8_t buf[4]; cyw43_ioctl(self->cyw, CYW43_IOCTL_GET_ANTDIV, 4, buf, self->itf); return MP_OBJ_NEW_SMALL_INT(nw_get_le32(buf)); } case MP_QSTR_channel: { uint8_t buf[4]; cyw43_ioctl(self->cyw, CYW43_IOCTL_GET_CHANNEL, 4, buf, self->itf); return MP_OBJ_NEW_SMALL_INT(nw_get_le32(buf)); } case MP_QSTR_essid: { if (self->itf == CYW43_ITF_STA) { uint8_t buf[36]; cyw43_ioctl(self->cyw, CYW43_IOCTL_GET_SSID, 36, buf, self->itf); return mp_obj_new_str((const char *)buf + 4, nw_get_le32(buf)); } else { size_t len; const uint8_t *buf; cyw43_wifi_ap_get_ssid(self->cyw, &len, &buf); return mp_obj_new_str((const char *)buf, len); } } case MP_QSTR_mac: { uint8_t buf[6]; cyw43_wifi_get_mac(self->cyw, self->itf, buf); return mp_obj_new_bytes(buf, 6); } case MP_QSTR_txpower: { uint8_t buf[13]; memcpy(buf, "qtxpower\x00\x00\x00\x00\x00", 13); cyw43_ioctl(self->cyw, CYW43_IOCTL_GET_VAR, 13, buf, self->itf); return MP_OBJ_NEW_SMALL_INT(nw_get_le32(buf) / 4); } default: mp_raise_ValueError(MP_ERROR_TEXT("unknown config param")); } } else { // Set config value(s) if (n_args != 1) { mp_raise_TypeError(MP_ERROR_TEXT("can't specify pos and kw args")); } for (size_t i = 0; i < kwargs->alloc; ++i) { if (MP_MAP_SLOT_IS_FILLED(kwargs, i)) { mp_map_elem_t *e = &kwargs->table[i]; switch (mp_obj_str_get_qstr(e->key)) { case MP_QSTR_antenna: { uint8_t buf[4]; nw_put_le32(buf, mp_obj_get_int(e->value)); cyw43_ioctl(self->cyw, CYW43_IOCTL_SET_ANTDIV, 4, buf, self->itf); break; } case MP_QSTR_channel: { cyw43_wifi_ap_set_channel(self->cyw, mp_obj_get_int(e->value)); break; } case MP_QSTR_essid: { size_t len; const char *str = mp_obj_str_get_data(e->value, &len); cyw43_wifi_ap_set_ssid(self->cyw, len, (const uint8_t *)str); break; } case MP_QSTR_monitor: { mp_int_t value = mp_obj_get_int(e->value); uint8_t buf[9 + 4]; memcpy(buf, "allmulti\x00", 9); nw_put_le32(buf + 9, value); cyw43_ioctl(self->cyw, CYW43_IOCTL_SET_VAR, 9 + 4, buf, self->itf); nw_put_le32(buf, value); cyw43_ioctl(self->cyw, CYW43_IOCTL_SET_MONITOR, 4, buf, self->itf); if (value) { self->cyw->trace_flags |= CYW43_TRACE_MAC; } else { self->cyw->trace_flags &= ~CYW43_TRACE_MAC; } break; } case MP_QSTR_password: { size_t len; const char *str = mp_obj_str_get_data(e->value, &len); cyw43_wifi_ap_set_password(self->cyw, len, (const uint8_t *)str); break; } case MP_QSTR_pm: { cyw43_wifi_pm(self->cyw, mp_obj_get_int(e->value)); break; } case MP_QSTR_trace: { self->cyw->trace_flags = mp_obj_get_int(e->value); break; } case MP_QSTR_txpower: { mp_int_t dbm = mp_obj_get_int(e->value); uint8_t buf[9 + 4]; memcpy(buf, "qtxpower\x00", 9); nw_put_le32(buf + 9, dbm * 4); cyw43_ioctl(self->cyw, CYW43_IOCTL_SET_VAR, 9 + 4, buf, self->itf); break; } default: mp_raise_ValueError(MP_ERROR_TEXT("unknown config param")); } } } return mp_const_none; } } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(network_cyw43_config_obj, 1, network_cyw43_config); /*******************************************************************************/ // class bindings STATIC const mp_rom_map_elem_t network_cyw43_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_send_ethernet), MP_ROM_PTR(&network_cyw43_send_ethernet_obj) }, { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&network_cyw43_ioctl_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&network_cyw43_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&network_cyw43_active_obj) }, { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&network_cyw43_scan_obj) }, { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&network_cyw43_connect_obj) }, { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&network_cyw43_disconnect_obj) }, { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&network_cyw43_isconnected_obj) }, { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&network_cyw43_ifconfig_obj) }, { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&network_cyw43_status_obj) }, { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&network_cyw43_config_obj) }, }; STATIC MP_DEFINE_CONST_DICT(network_cyw43_locals_dict, network_cyw43_locals_dict_table); const mp_obj_type_t mp_network_cyw43_type = { { &mp_type_type }, .name = MP_QSTR_CYW43, .print = network_cyw43_print, .make_new = network_cyw43_make_new, .locals_dict = (mp_obj_dict_t *)&network_cyw43_locals_dict, }; #endif // MICROPY_PY_NETWORK_CYW43
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/network_cyw43.c
C
apache-2.0
18,853
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_NETWORK_CYW43_H #define MICROPY_INCLUDED_EXTMOD_NETWORK_CYW43_H extern const mp_obj_type_t mp_network_cyw43_type; #endif // MICROPY_INCLUDED_EXTMOD_NETWORK_CYW43_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/network_cyw43.h
C
apache-2.0
1,423
// empty
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/bsp/bsp.h
C
apache-2.0
9
// empty
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/hal/hal_gpio.h
C
apache-2.0
9
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/mphal.h" #include "nimble/ble.h" #include "extmod/nimble/modbluetooth_nimble.h" #include "extmod/nimble/hal/hal_uart.h" #include "extmod/nimble/nimble/nimble_npl_os.h" #include "extmod/mpbthci.h" #if MICROPY_PY_BLUETOOTH && MICROPY_BLUETOOTH_NIMBLE #define HCI_TRACE (0) static hal_uart_tx_cb_t hal_uart_tx_cb; static void *hal_uart_tx_arg; static hal_uart_rx_cb_t hal_uart_rx_cb; static void *hal_uart_rx_arg; // Provided by the port, and also possibly shared with the driver. extern uint8_t mp_bluetooth_hci_cmd_buf[4 + 256]; int hal_uart_init_cbs(uint32_t port, hal_uart_tx_cb_t tx_cb, void *tx_arg, hal_uart_rx_cb_t rx_cb, void *rx_arg) { hal_uart_tx_cb = tx_cb; hal_uart_tx_arg = tx_arg; hal_uart_rx_cb = rx_cb; hal_uart_rx_arg = rx_arg; return 0; // success } int hal_uart_config(uint32_t port, uint32_t baudrate, uint32_t bits, uint32_t stop, uint32_t parity, uint32_t flow) { return mp_bluetooth_hci_uart_init(port, baudrate); } void hal_uart_start_tx(uint32_t port) { size_t len = 0; for (;;) { int data = hal_uart_tx_cb(hal_uart_tx_arg); if (data == -1) { break; } mp_bluetooth_hci_cmd_buf[len++] = data; } #if HCI_TRACE printf("< [% 8d] %02x", (int)mp_hal_ticks_ms(), mp_bluetooth_hci_cmd_buf[0]); for (size_t i = 1; i < len; ++i) { printf(":%02x", mp_bluetooth_hci_cmd_buf[i]); } printf("\n"); #endif mp_bluetooth_hci_uart_write(mp_bluetooth_hci_cmd_buf, len); if (len > 0) { // Allow modbluetooth bindings to hook "sent packet" (e.g. to unstall l2cap channels). mp_bluetooth_nimble_sent_hci_packet(); } } int hal_uart_close(uint32_t port) { return 0; // success } void mp_bluetooth_nimble_hci_uart_process(bool run_events) { bool host_wake = mp_bluetooth_hci_controller_woken(); int chr; while ((chr = mp_bluetooth_hci_uart_readchar()) >= 0) { #if HCI_TRACE printf("> %02x\n", chr); #endif hal_uart_rx_cb(hal_uart_rx_arg, chr); // Incoming data may result in events being enqueued. If we're in // scheduler context then we can run those events immediately. if (run_events) { mp_bluetooth_nimble_os_eventq_run_all(); } } if (host_wake) { mp_bluetooth_hci_controller_sleep_maybe(); } } #endif // MICROPY_PY_BLUETOOTH && MICROPY_BLUETOOTH_NIMBLE
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/hal/hal_uart.c
C
apache-2.0
3,692
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2020 Jim Mussared * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_NIMBLE_HAL_HAL_UART_H #define MICROPY_INCLUDED_EXTMOD_NIMBLE_HAL_HAL_UART_H #include <stdint.h> #define SYSINIT_PANIC_ASSERT_MSG(cond, msg) #define HAL_UART_PARITY_NONE (0) typedef int (*hal_uart_tx_cb_t)(void *arg); typedef int (*hal_uart_rx_cb_t)(void *arg, uint8_t data); // --- Called by NimBLE, implemented in hal_uart.c. --------------------------- int hal_uart_init_cbs(uint32_t port, hal_uart_tx_cb_t tx_cb, void *tx_arg, hal_uart_rx_cb_t rx_cb, void *rx_arg); int hal_uart_config(uint32_t port, uint32_t baud, uint32_t bits, uint32_t stop, uint32_t parity, uint32_t flow); void hal_uart_start_tx(uint32_t port); int hal_uart_close(uint32_t port); // --- Called by the MicroPython port when UART data is available ------------- void mp_bluetooth_nimble_hci_uart_process(bool run_events); #endif // MICROPY_INCLUDED_EXTMOD_NIMBLE_HAL_HAL_UART_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/hal/hal_uart.h
C
apache-2.0
2,113
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 Damien P. George * Copyright (c) 2019-2020 Jim Mussared * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/mperrno.h" #include "py/mphal.h" #if MICROPY_PY_BLUETOOTH && MICROPY_BLUETOOTH_NIMBLE #include "extmod/nimble/modbluetooth_nimble.h" #include "extmod/modbluetooth.h" #include "extmod/mpbthci.h" #include "host/ble_hs.h" #include "host/util/util.h" #include "nimble/ble.h" #include "nimble/nimble_port.h" #include "services/gap/ble_svc_gap.h" #include "services/gatt/ble_svc_gatt.h" #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS // We need the definition of "struct ble_l2cap_chan". // See l2cap_channel_event() for details. #include "nimble/host/src/ble_l2cap_priv.h" #endif #if MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD || MICROPY_BLUETOOTH_USE_ZEPHYR_STATIC_ADDRESS // For ble_hs_hci_cmd_tx #include "nimble/host/src/ble_hs_hci_priv.h" #endif #ifndef MICROPY_PY_BLUETOOTH_DEFAULT_GAP_NAME #define MICROPY_PY_BLUETOOTH_DEFAULT_GAP_NAME "MPY NIMBLE" #endif #define DEBUG_printf(...) // printf("nimble: " __VA_ARGS__) #define ERRNO_BLUETOOTH_NOT_ACTIVE MP_ENODEV STATIC uint8_t nimble_address_mode = BLE_OWN_ADDR_RANDOM; #define NIMBLE_STARTUP_TIMEOUT 2000 // Any BLE_HS_xxx code not in this table will default to MP_EIO. STATIC int8_t ble_hs_err_to_errno_table[] = { [BLE_HS_EAGAIN] = MP_EAGAIN, [BLE_HS_EALREADY] = MP_EALREADY, [BLE_HS_EINVAL] = MP_EINVAL, [BLE_HS_ENOENT] = MP_ENOENT, [BLE_HS_ENOMEM] = MP_ENOMEM, [BLE_HS_ENOTCONN] = MP_ENOTCONN, [BLE_HS_ENOTSUP] = MP_EOPNOTSUPP, [BLE_HS_ETIMEOUT] = MP_ETIMEDOUT, [BLE_HS_EDONE] = MP_EIO, // TODO: Maybe should be MP_EISCONN (connect uses this for "already connected"). [BLE_HS_EBUSY] = MP_EBUSY, [BLE_HS_EBADDATA] = MP_EINVAL, }; STATIC int ble_hs_err_to_errno(int err); STATIC ble_uuid_t *create_nimble_uuid(const mp_obj_bluetooth_uuid_t *uuid, ble_uuid_any_t *storage); STATIC void reverse_addr_byte_order(uint8_t *addr_out, const uint8_t *addr_in); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE STATIC mp_obj_bluetooth_uuid_t create_mp_uuid(const ble_uuid_any_t *uuid); STATIC ble_addr_t create_nimble_addr(uint8_t addr_type, const uint8_t *addr); #endif STATIC void reset_cb(int reason); STATIC bool has_public_address(void); STATIC void set_random_address(bool nrpa); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING STATIC int load_irk(void); #endif STATIC void sync_cb(void); #if !MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY STATIC void ble_hs_shutdown_stop_cb(int status, void *arg); #endif // Successfully registered service/char/desc handles. STATIC void gatts_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg); // Events about a connected central (we're in peripheral role). STATIC int central_gap_event_cb(struct ble_gap_event *event, void *arg); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE // Events about a connected peripheral (we're in central role). STATIC int peripheral_gap_event_cb(struct ble_gap_event *event, void *arg); #endif // Used by both of the above. STATIC int commmon_gap_event_cb(struct ble_gap_event *event, void *arg); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE // Scan results. STATIC int gap_scan_cb(struct ble_gap_event *event, void *arg); #endif #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT // Data available (either due to notify/indicate or successful read). STATIC void gattc_on_data_available(uint8_t event, uint16_t conn_handle, uint16_t value_handle, const struct os_mbuf *om); // Client discovery callbacks. STATIC int ble_gattc_service_cb(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_svc *service, void *arg); STATIC int ble_gattc_characteristic_cb(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_chr *characteristic, void *arg); STATIC int ble_gattc_descriptor_cb(uint16_t conn_handle, const struct ble_gatt_error *error, uint16_t characteristic_val_handle, const struct ble_gatt_dsc *descriptor, void *arg); // Client read/write handlers. STATIC int ble_gattc_attr_read_cb(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg); STATIC int ble_gattc_attr_write_cb(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg); #endif #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // Bonding store. STATIC int ble_store_ram_read(int obj_type, const union ble_store_key *key, union ble_store_value *value); STATIC int ble_store_ram_write(int obj_type, const union ble_store_value *val); STATIC int ble_store_ram_delete(int obj_type, const union ble_store_key *key); #endif STATIC int ble_hs_err_to_errno(int err) { DEBUG_printf("ble_hs_err_to_errno: %d\n", err); if (!err) { return 0; } if (err >= 0 && (unsigned)err < MP_ARRAY_SIZE(ble_hs_err_to_errno_table) && ble_hs_err_to_errno_table[err]) { // Return an MP_Exxx error code. return ble_hs_err_to_errno_table[err]; } else { // Pass through the BLE error code. return -err; } } // Note: modbluetooth UUIDs store their data in LE. STATIC ble_uuid_t *create_nimble_uuid(const mp_obj_bluetooth_uuid_t *uuid, ble_uuid_any_t *storage) { if (uuid->type == MP_BLUETOOTH_UUID_TYPE_16) { ble_uuid16_t *result = storage ? &storage->u16 : m_new(ble_uuid16_t, 1); result->u.type = BLE_UUID_TYPE_16; result->value = (uuid->data[1] << 8) | uuid->data[0]; return (ble_uuid_t *)result; } else if (uuid->type == MP_BLUETOOTH_UUID_TYPE_32) { ble_uuid32_t *result = storage ? &storage->u32 : m_new(ble_uuid32_t, 1); result->u.type = BLE_UUID_TYPE_32; result->value = (uuid->data[1] << 24) | (uuid->data[1] << 16) | (uuid->data[1] << 8) | uuid->data[0]; return (ble_uuid_t *)result; } else if (uuid->type == MP_BLUETOOTH_UUID_TYPE_128) { ble_uuid128_t *result = storage ? &storage->u128 : m_new(ble_uuid128_t, 1); result->u.type = BLE_UUID_TYPE_128; memcpy(result->value, uuid->data, 16); return (ble_uuid_t *)result; } else { return NULL; } } // modbluetooth (and the layers above it) work in BE for addresses, Nimble works in LE. STATIC void reverse_addr_byte_order(uint8_t *addr_out, const uint8_t *addr_in) { for (int i = 0; i < 6; ++i) { addr_out[i] = addr_in[5 - i]; } } #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE STATIC mp_obj_bluetooth_uuid_t create_mp_uuid(const ble_uuid_any_t *uuid) { mp_obj_bluetooth_uuid_t result; result.base.type = &mp_type_bluetooth_uuid; switch (uuid->u.type) { case BLE_UUID_TYPE_16: result.type = MP_BLUETOOTH_UUID_TYPE_16; result.data[0] = uuid->u16.value & 0xff; result.data[1] = (uuid->u16.value >> 8) & 0xff; break; case BLE_UUID_TYPE_32: result.type = MP_BLUETOOTH_UUID_TYPE_32; result.data[0] = uuid->u32.value & 0xff; result.data[1] = (uuid->u32.value >> 8) & 0xff; result.data[2] = (uuid->u32.value >> 16) & 0xff; result.data[3] = (uuid->u32.value >> 24) & 0xff; break; case BLE_UUID_TYPE_128: result.type = MP_BLUETOOTH_UUID_TYPE_128; memcpy(result.data, uuid->u128.value, 16); break; default: assert(false); } return result; } STATIC ble_addr_t create_nimble_addr(uint8_t addr_type, const uint8_t *addr) { ble_addr_t addr_nimble; addr_nimble.type = addr_type; // Incoming addr is from modbluetooth (BE), so copy and convert to LE for Nimble. reverse_addr_byte_order(addr_nimble.val, addr); return addr_nimble; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE volatile int mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF; STATIC void reset_cb(int reason) { (void)reason; } STATIC bool has_public_address(void) { return ble_hs_id_copy_addr(BLE_ADDR_PUBLIC, NULL, NULL) == 0; } STATIC void set_random_address(bool nrpa) { int rc; (void)rc; ble_addr_t addr; #if MICROPY_BLUETOOTH_USE_MP_HAL_GET_MAC_STATIC_ADDRESS if (!nrpa) { DEBUG_printf("set_random_address: Generating static address using mp_hal_get_mac\n"); uint8_t hal_mac_addr[6]; mp_hal_get_mac(MP_HAL_MAC_BDADDR, hal_mac_addr); addr = create_nimble_addr(BLE_ADDR_RANDOM, hal_mac_addr); // Mark it as STATIC (not RPA or NRPA). addr.val[5] |= 0xc0; } else #elif MICROPY_BLUETOOTH_USE_ZEPHYR_STATIC_ADDRESS if (!nrpa) { DEBUG_printf("set_random_address: Generating static address from Zephyr controller\n"); uint8_t buf[23]; rc = ble_hs_hci_cmd_tx(BLE_HCI_OP(BLE_HCI_OGF_VENDOR, 0x09), NULL, 0, buf, sizeof(buf)); assert(rc == 0); memcpy(addr.val, buf + 1, 6); } else #endif { DEBUG_printf("set_random_address: Generating random static address\n"); rc = ble_hs_id_gen_rnd(nrpa ? 1 : 0, &addr); assert(rc == 0); } rc = ble_hs_id_set_rnd(addr.val); assert(rc == 0); rc = ble_hs_util_ensure_addr(1); assert(rc == 0); } #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING // For ble_hs_pvcy_set_our_irk #include "nimble/host/src/ble_hs_pvcy_priv.h" // For ble_hs_hci_util_rand #include "nimble/host/src/ble_hs_hci_priv.h" // For ble_hs_misc_restore_irks #include "nimble/host/src/ble_hs_priv.h" // Must be distinct to BLE_STORE_OBJ_TYPE_ in ble_store.h. #define SECRET_TYPE_OUR_IRK 10 STATIC int load_irk(void) { // NimBLE unconditionally loads a fixed IRK on startup. // See https://github.com/apache/mynewt-nimble/issues/887 // Dummy key to use for the store. // Technically the secret type is enough as there will only be // one IRK so the key doesn't matter, but a NULL (None) key means "search". const uint8_t key[3] = {'i', 'r', 'k'}; int rc; const uint8_t *irk; size_t irk_len; if (mp_bluetooth_gap_on_get_secret(SECRET_TYPE_OUR_IRK, 0, key, sizeof(key), &irk, &irk_len) && irk_len == 16) { DEBUG_printf("load_irk: Applying IRK from store.\n"); rc = ble_hs_pvcy_set_our_irk(irk); if (rc) { return rc; } } else { DEBUG_printf("load_irk: Generating new IRK.\n"); uint8_t rand_irk[16]; rc = ble_hs_hci_util_rand(rand_irk, 16); if (rc) { return rc; } DEBUG_printf("load_irk: Saving new IRK.\n"); if (!mp_bluetooth_gap_on_set_secret(SECRET_TYPE_OUR_IRK, key, sizeof(key), rand_irk, 16)) { // Code that doesn't implement pairing/bonding won't support set/get secret. // So they'll just get the default fixed IRK. return 0; } DEBUG_printf("load_irk: Applying new IRK.\n"); rc = ble_hs_pvcy_set_our_irk(rand_irk); if (rc) { return rc; } } // Loading an IRK will clear all peer IRKs, so reload them from the store. rc = ble_hs_misc_restore_irks(); return rc; } #endif STATIC void sync_cb(void) { int rc; (void)rc; DEBUG_printf("sync_cb: state=%d\n", mp_bluetooth_nimble_ble_state); if (mp_bluetooth_nimble_ble_state != MP_BLUETOOTH_NIMBLE_BLE_STATE_WAITING_FOR_SYNC) { return; } #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING rc = load_irk(); assert(rc == 0); #endif if (has_public_address()) { nimble_address_mode = BLE_OWN_ADDR_PUBLIC; } else { nimble_address_mode = BLE_OWN_ADDR_RANDOM; set_random_address(false); } if (MP_BLUETOOTH_DEFAULT_ATTR_LEN > 20) { DEBUG_printf("sync_cb: Setting MTU\n"); rc = ble_att_set_preferred_mtu(MP_BLUETOOTH_DEFAULT_ATTR_LEN + 3); assert(rc == 0); } DEBUG_printf("sync_cb: Setting device name\n"); ble_svc_gap_device_name_set(MICROPY_PY_BLUETOOTH_DEFAULT_GAP_NAME); mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_ACTIVE; } STATIC void gatts_register_cb(struct ble_gatt_register_ctxt *ctxt, void *arg) { if (!mp_bluetooth_is_active()) { return; } switch (ctxt->op) { case BLE_GATT_REGISTER_OP_SVC: // Called when a service is successfully registered. DEBUG_printf("gatts_register_cb: svc uuid=%p handle=%d\n", &ctxt->svc.svc_def->uuid, ctxt->svc.handle); break; case BLE_GATT_REGISTER_OP_CHR: // Called when a characteristic is successfully registered. DEBUG_printf("gatts_register_cb: chr uuid=%p def_handle=%d val_handle=%d\n", &ctxt->chr.chr_def->uuid, ctxt->chr.def_handle, ctxt->chr.val_handle); // Note: We will get this event for the default GAP Service, meaning that we allocate storage for the // "device name" and "appearance" characteristics, even though we never see the reads for them. // TODO: Possibly check if the service UUID is 0x1801 and ignore? // Allocate the gatts_db storage for this characteristic. // Although this function is a callback, it's called synchronously from ble_hs_sched_start/ble_gatts_start, so safe to allocate. mp_bluetooth_gatts_db_create_entry(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, ctxt->chr.val_handle, MP_BLUETOOTH_DEFAULT_ATTR_LEN); break; case BLE_GATT_REGISTER_OP_DSC: // Called when a descriptor is successfully registered. // Note: This is event is not called for the CCCD. DEBUG_printf("gatts_register_cb: dsc uuid=%p handle=%d\n", &ctxt->dsc.dsc_def->uuid, ctxt->dsc.handle); // See above, safe to alloc. mp_bluetooth_gatts_db_create_entry(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, ctxt->dsc.handle, MP_BLUETOOTH_DEFAULT_ATTR_LEN); // Unlike characteristics, we have to manually provide a way to get the handle back to the register method. *((uint16_t *)ctxt->dsc.dsc_def->arg) = ctxt->dsc.handle; break; default: DEBUG_printf("gatts_register_cb: unknown op %d\n", ctxt->op); break; } } STATIC int commmon_gap_event_cb(struct ble_gap_event *event, void *arg) { struct ble_gap_conn_desc desc; switch (event->type) { #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT case BLE_GAP_EVENT_NOTIFY_RX: { uint16_t ev = event->notify_rx.indication == 0 ? MP_BLUETOOTH_IRQ_GATTC_NOTIFY : MP_BLUETOOTH_IRQ_GATTC_INDICATE; gattc_on_data_available(ev, event->notify_rx.conn_handle, event->notify_rx.attr_handle, event->notify_rx.om); return 0; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT case BLE_GAP_EVENT_CONN_UPDATE: { DEBUG_printf("commmon_gap_event_cb: connection update: status=%d\n", event->conn_update.status); if (ble_gap_conn_find(event->conn_update.conn_handle, &desc) == 0) { mp_bluetooth_gap_on_connection_update(event->conn_update.conn_handle, desc.conn_itvl, desc.conn_latency, desc.supervision_timeout, event->conn_update.status == 0 ? 0 : 1); } return 0; } case BLE_GAP_EVENT_MTU: { if (event->mtu.channel_id == BLE_L2CAP_CID_ATT) { DEBUG_printf("commmon_gap_event_cb: mtu update: conn_handle=%d cid=%d mtu=%d\n", event->mtu.conn_handle, event->mtu.channel_id, event->mtu.value); mp_bluetooth_gatts_on_mtu_exchanged(event->mtu.conn_handle, event->mtu.value); } return 0; } case BLE_GAP_EVENT_ENC_CHANGE: { DEBUG_printf("commmon_gap_event_cb: enc change: status=%d\n", event->enc_change.status); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING if (ble_gap_conn_find(event->enc_change.conn_handle, &desc) == 0) { mp_bluetooth_gatts_on_encryption_update(event->conn_update.conn_handle, desc.sec_state.encrypted, desc.sec_state.authenticated, desc.sec_state.bonded, desc.sec_state.key_size); } #endif return 0; } default: DEBUG_printf("commmon_gap_event_cb: unknown type %d\n", event->type); return 0; } } STATIC int central_gap_event_cb(struct ble_gap_event *event, void *arg) { DEBUG_printf("central_gap_event_cb: type=%d\n", event->type); if (!mp_bluetooth_is_active()) { return 0; } struct ble_gap_conn_desc desc; uint8_t addr[6] = {0}; switch (event->type) { case BLE_GAP_EVENT_CONNECT: DEBUG_printf("central_gap_event_cb: connect: status=%d\n", event->connect.status); if (event->connect.status == 0) { // Connection established. ble_gap_conn_find(event->connect.conn_handle, &desc); reverse_addr_byte_order(addr, desc.peer_id_addr.val); mp_bluetooth_gap_on_connected_disconnected(MP_BLUETOOTH_IRQ_CENTRAL_CONNECT, event->connect.conn_handle, desc.peer_id_addr.type, addr); } else { // Connection failed. mp_bluetooth_gap_on_connected_disconnected(MP_BLUETOOTH_IRQ_CENTRAL_DISCONNECT, event->connect.conn_handle, 0xff, addr); } return 0; case BLE_GAP_EVENT_DISCONNECT: // Disconnect. DEBUG_printf("central_gap_event_cb: disconnect: reason=%d\n", event->disconnect.reason); reverse_addr_byte_order(addr, event->disconnect.conn.peer_id_addr.val); mp_bluetooth_gap_on_connected_disconnected(MP_BLUETOOTH_IRQ_CENTRAL_DISCONNECT, event->disconnect.conn.conn_handle, event->disconnect.conn.peer_id_addr.type, addr); return 0; case BLE_GAP_EVENT_NOTIFY_TX: { DEBUG_printf("central_gap_event_cb: notify_tx: %d %d\n", event->notify_tx.indication, event->notify_tx.status); // This event corresponds to either a sent notify/indicate (status == 0), or an indication confirmation (status != 0). if (event->notify_tx.indication && event->notify_tx.status != 0) { // Map "done/ack" to 0, otherwise pass the status directly. mp_bluetooth_gatts_on_indicate_complete(event->notify_tx.conn_handle, event->notify_tx.attr_handle, event->notify_tx.status == BLE_HS_EDONE ? 0 : event->notify_tx.status); } return 0; } case BLE_GAP_EVENT_PHY_UPDATE_COMPLETE: DEBUG_printf("central_gap_event_cb: phy update: %d\n", event->phy_updated.tx_phy); return 0; case BLE_GAP_EVENT_REPEAT_PAIRING: { // We recognized this peer but the peer doesn't recognize us. DEBUG_printf("central_gap_event_cb: repeat pairing: conn_handle=%d\n", event->repeat_pairing.conn_handle); // TODO: Consider returning BLE_GAP_REPEAT_PAIRING_IGNORE (and // possibly an API to configure this). // Delete the old bond. int rc = ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc); if (rc == 0) { ble_store_util_delete_peer(&desc.peer_id_addr); } // Allow re-pairing. return BLE_GAP_REPEAT_PAIRING_RETRY; } case BLE_GAP_EVENT_PASSKEY_ACTION: { DEBUG_printf("central_gap_event_cb: passkey action: conn_handle=%d action=%d num=" UINT_FMT "\n", event->passkey.conn_handle, event->passkey.params.action, (mp_uint_t)event->passkey.params.numcmp); #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING mp_bluetooth_gap_on_passkey_action(event->passkey.conn_handle, event->passkey.params.action, event->passkey.params.numcmp); #endif return 0; } case BLE_GAP_EVENT_SUBSCRIBE: { DEBUG_printf("central_gap_event_cb: subscribe: handle=%d, reason=%d notify=%d indicate=%d \n", event->subscribe.attr_handle, event->subscribe.reason, event->subscribe.cur_notify, event->subscribe.cur_indicate); return 0; } } return commmon_gap_event_cb(event, arg); } #if !MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY // On ports such as ESP32 where we only implement the bindings, then // the port must provide these functions. // But for STM32 / Unix-H4, we provide a default implementation of the // port-specific functionality. // TODO: In the future if a port ever needs to customise these functions // then investigate using MP_WEAK or splitting them out to another .c file. #include "transport/uart/ble_hci_uart.h" void mp_bluetooth_nimble_port_hci_init(void) { DEBUG_printf("mp_bluetooth_nimble_port_hci_init (nimble default)\n"); // This calls mp_bluetooth_hci_uart_init (via ble_hci_uart_init --> hal_uart_config --> mp_bluetooth_hci_uart_init). ble_hci_uart_init(); mp_bluetooth_hci_controller_init(); } void mp_bluetooth_nimble_port_hci_deinit(void) { DEBUG_printf("mp_bluetooth_nimble_port_hci_deinit (nimble default)\n"); mp_bluetooth_hci_controller_deinit(); mp_bluetooth_hci_uart_deinit(); } void mp_bluetooth_nimble_port_start(void) { DEBUG_printf("mp_bluetooth_nimble_port_start (nimble default)\n"); // By default, assume port is already running its own background task (e.g. SysTick on STM32). // ESP32 runs a FreeRTOS task, Unix has a thread. } // Called when the host stop procedure has completed. STATIC void ble_hs_shutdown_stop_cb(int status, void *arg) { (void)status; (void)arg; mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF; } STATIC struct ble_hs_stop_listener ble_hs_shutdown_stop_listener; void mp_bluetooth_nimble_port_shutdown(void) { DEBUG_printf("mp_bluetooth_nimble_port_shutdown (nimble default)\n"); // By default, just call ble_hs_stop directly and wait for the stack to stop. mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_STOPPING; ble_hs_stop(&ble_hs_shutdown_stop_listener, ble_hs_shutdown_stop_cb, NULL); while (mp_bluetooth_nimble_ble_state != MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF) { MICROPY_EVENT_POLL_HOOK } } #endif // !MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY void nimble_reset_gatts_bss(void) { // NimBLE assumes that service registration only ever happens once, so // we need to reset service registration state from a previous stack startup. // These variables are defined in ble_hs.c and are only ever incremented // (during service registration) and never reset. // See https://github.com/apache/mynewt-nimble/issues/896 extern uint16_t ble_hs_max_attrs; extern uint16_t ble_hs_max_services; extern uint16_t ble_hs_max_client_configs; ble_hs_max_attrs = 0; ble_hs_max_services = 0; ble_hs_max_client_configs = 0; } int mp_bluetooth_init(void) { DEBUG_printf("mp_bluetooth_init\n"); // Clean up if necessary. mp_bluetooth_deinit(); nimble_reset_gatts_bss(); mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_STARTING; ble_hs_cfg.reset_cb = reset_cb; ble_hs_cfg.sync_cb = sync_cb; ble_hs_cfg.gatts_register_cb = gatts_register_cb; ble_hs_cfg.store_status_cb = ble_store_util_status_rr; MP_STATE_PORT(bluetooth_nimble_root_pointers) = m_new0(mp_bluetooth_nimble_root_pointers_t, 1); mp_bluetooth_gatts_db_create(&MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db); #if !MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY // Dereference any previous NimBLE mallocs. MP_STATE_PORT(bluetooth_nimble_memory) = NULL; #endif // Allow port (ESP32) to override NimBLE's HCI init. // Otherwise default implementation above calls ble_hci_uart_init(). mp_bluetooth_nimble_port_hci_init(); // Static initialization is complete, can start processing events. mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_WAITING_FOR_SYNC; // Initialise NimBLE memory and data structures. DEBUG_printf("mp_bluetooth_init: nimble_port_init\n"); nimble_port_init(); // Make sure that the HCI UART and event handling task is running. mp_bluetooth_nimble_port_start(); // Run the scheduler while we wait for stack startup. // On non-ringbuffer builds (NimBLE on STM32/Unix) this will also poll the UART and run the event queue. mp_uint_t timeout_start_ticks_ms = mp_hal_ticks_ms(); while (mp_bluetooth_nimble_ble_state != MP_BLUETOOTH_NIMBLE_BLE_STATE_ACTIVE) { if (mp_hal_ticks_ms() - timeout_start_ticks_ms > NIMBLE_STARTUP_TIMEOUT) { break; } MICROPY_EVENT_POLL_HOOK } if (mp_bluetooth_nimble_ble_state != MP_BLUETOOTH_NIMBLE_BLE_STATE_ACTIVE) { mp_bluetooth_deinit(); return MP_ETIMEDOUT; } DEBUG_printf("mp_bluetooth_init: starting services\n"); // By default, just register the default gap/gatt service. ble_svc_gap_init(); ble_svc_gatt_init(); // The preceeding two calls allocate service definitions on the heap, // then we must now call gatts_start to register those services // and free the heap memory. // Otherwise it will be realloc'ed on the next stack startup. ble_gatts_start(); DEBUG_printf("mp_bluetooth_init: ready\n"); return 0; } void mp_bluetooth_deinit(void) { DEBUG_printf("mp_bluetooth_deinit %d\n", mp_bluetooth_nimble_ble_state); if (mp_bluetooth_nimble_ble_state == MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF) { return; } // Must call ble_hs_stop() in a port-specific way to stop the background // task. Default implementation provided above. if (mp_bluetooth_nimble_ble_state == MP_BLUETOOTH_NIMBLE_BLE_STATE_ACTIVE) { mp_bluetooth_gap_advertise_stop(); #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE mp_bluetooth_gap_scan_stop(); #endif DEBUG_printf("mp_bluetooth_deinit: starting port shutdown\n"); mp_bluetooth_nimble_port_shutdown(); assert(mp_bluetooth_nimble_ble_state == MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF); } else { mp_bluetooth_nimble_ble_state = MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF; } // Shutdown the HCI controller. mp_bluetooth_nimble_port_hci_deinit(); MP_STATE_PORT(bluetooth_nimble_root_pointers) = NULL; #if !MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY // Dereference any previous NimBLE mallocs. MP_STATE_PORT(bluetooth_nimble_memory) = NULL; #endif DEBUG_printf("mp_bluetooth_deinit: shut down\n"); } bool mp_bluetooth_is_active(void) { return mp_bluetooth_nimble_ble_state == MP_BLUETOOTH_NIMBLE_BLE_STATE_ACTIVE; } void mp_bluetooth_get_current_address(uint8_t *addr_type, uint8_t *addr) { if (!mp_bluetooth_is_active()) { mp_raise_OSError(ERRNO_BLUETOOTH_NOT_ACTIVE); } uint8_t addr_le[6]; switch (nimble_address_mode) { case BLE_OWN_ADDR_PUBLIC: *addr_type = BLE_ADDR_PUBLIC; break; case BLE_OWN_ADDR_RANDOM: *addr_type = BLE_ADDR_RANDOM; break; case BLE_OWN_ADDR_RPA_PUBLIC_DEFAULT: case BLE_OWN_ADDR_RPA_RANDOM_DEFAULT: default: // TODO: If RPA/NRPA in use, get the current value. // Is this even possible in NimBLE? mp_raise_OSError(MP_EINVAL); } int rc = ble_hs_id_copy_addr(*addr_type, addr_le, NULL); if (rc != 0) { mp_raise_OSError(MP_EINVAL); } reverse_addr_byte_order(addr, addr_le); } void mp_bluetooth_set_address_mode(uint8_t addr_mode) { switch (addr_mode) { case MP_BLUETOOTH_ADDRESS_MODE_PUBLIC: if (!has_public_address()) { // No public address available. mp_raise_OSError(MP_EINVAL); } nimble_address_mode = BLE_OWN_ADDR_PUBLIC; break; case MP_BLUETOOTH_ADDRESS_MODE_RANDOM: // Generate an static random address. set_random_address(false); nimble_address_mode = BLE_OWN_ADDR_RANDOM; break; case MP_BLUETOOTH_ADDRESS_MODE_RPA: if (has_public_address()) { nimble_address_mode = BLE_OWN_ADDR_RPA_PUBLIC_DEFAULT; } else { // Generate an static random address to use as the identity address. set_random_address(false); nimble_address_mode = BLE_OWN_ADDR_RPA_RANDOM_DEFAULT; } break; case MP_BLUETOOTH_ADDRESS_MODE_NRPA: // Generate an NRPA. set_random_address(true); // In NimBLE, NRPA is treated like a static random address that happens to be an NRPA. nimble_address_mode = BLE_OWN_ADDR_RANDOM; break; } } #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING void mp_bluetooth_set_bonding(bool enabled) { ble_hs_cfg.sm_bonding = enabled; } void mp_bluetooth_set_mitm_protection(bool enabled) { ble_hs_cfg.sm_mitm = enabled; } void mp_bluetooth_set_le_secure(bool enabled) { ble_hs_cfg.sm_sc = enabled; } void mp_bluetooth_set_io_capability(uint8_t capability) { ble_hs_cfg.sm_io_cap = capability; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING size_t mp_bluetooth_gap_get_device_name(const uint8_t **buf) { const char *name = ble_svc_gap_device_name(); *buf = (const uint8_t *)name; return strlen(name); } int mp_bluetooth_gap_set_device_name(const uint8_t *buf, size_t len) { char tmp_buf[MYNEWT_VAL(BLE_SVC_GAP_DEVICE_NAME_MAX_LENGTH) + 1]; if (len + 1 > sizeof(tmp_buf)) { return MP_EINVAL; } memcpy(tmp_buf, buf, len); tmp_buf[len] = '\0'; return ble_hs_err_to_errno(ble_svc_gap_device_name_set(tmp_buf)); } int mp_bluetooth_gap_advertise_start(bool connectable, int32_t interval_us, const uint8_t *adv_data, size_t adv_data_len, const uint8_t *sr_data, size_t sr_data_len) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } mp_bluetooth_gap_advertise_stop(); int ret; if (adv_data) { ret = ble_gap_adv_set_data(adv_data, adv_data_len); if (ret != 0) { return ble_hs_err_to_errno(ret); } } if (sr_data) { ret = ble_gap_adv_rsp_set_data(sr_data, sr_data_len); if (ret != 0) { return ble_hs_err_to_errno(ret); } } struct ble_gap_adv_params adv_params = { .conn_mode = connectable ? BLE_GAP_CONN_MODE_UND : BLE_GAP_CONN_MODE_NON, .disc_mode = BLE_GAP_DISC_MODE_GEN, .itvl_min = interval_us / BLE_HCI_ADV_ITVL, // convert to 625us units. .itvl_max = interval_us / BLE_HCI_ADV_ITVL, .channel_map = 7, // all 3 channels. }; ret = ble_gap_adv_start(nimble_address_mode, NULL, BLE_HS_FOREVER, &adv_params, central_gap_event_cb, NULL); if (ret == 0) { return 0; } DEBUG_printf("ble_gap_adv_start: %d\n", ret); return ble_hs_err_to_errno(ret); } void mp_bluetooth_gap_advertise_stop(void) { if (ble_gap_adv_active()) { ble_gap_adv_stop(); } } static int characteristic_access_cb(uint16_t conn_handle, uint16_t value_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) { DEBUG_printf("characteristic_access_cb: conn_handle=%u value_handle=%u op=%u\n", conn_handle, value_handle, ctxt->op); if (!mp_bluetooth_is_active()) { return 0; } mp_bluetooth_gatts_db_entry_t *entry; switch (ctxt->op) { case BLE_GATT_ACCESS_OP_READ_CHR: case BLE_GATT_ACCESS_OP_READ_DSC: { // Allow Python code to override (by using gatts_write), or deny (by returning false) the read. // Note this will be a no-op if the ringbuffer implementation is being used (i.e. the stack isn't // run in the scheduler). The ringbuffer is not used on STM32 and Unix-H4 only. int req = mp_bluetooth_gatts_on_read_request(conn_handle, value_handle); if (req) { return req; } entry = mp_bluetooth_gatts_db_lookup(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, value_handle); if (!entry) { return BLE_ATT_ERR_ATTR_NOT_FOUND; } if (os_mbuf_append(ctxt->om, entry->data, entry->data_len)) { return BLE_ATT_ERR_INSUFFICIENT_RES; } return 0; } case BLE_GATT_ACCESS_OP_WRITE_CHR: case BLE_GATT_ACCESS_OP_WRITE_DSC: entry = mp_bluetooth_gatts_db_lookup(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, value_handle); if (!entry) { return BLE_ATT_ERR_ATTR_NOT_FOUND; } size_t offset = 0; if (entry->append) { offset = entry->data_len; } entry->data_len = MIN(entry->data_alloc, OS_MBUF_PKTLEN(ctxt->om) + offset); os_mbuf_copydata(ctxt->om, 0, entry->data_len - offset, entry->data + offset); // TODO: Consider failing with BLE_ATT_ERR_INSUFFICIENT_RES if the buffer is full. mp_bluetooth_gatts_on_write(conn_handle, value_handle); return 0; } return BLE_ATT_ERR_UNLIKELY; } int mp_bluetooth_gatts_register_service_begin(bool append) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } if (append) { // Don't support append yet (modbluetooth.c doesn't support it yet anyway). // TODO: This should be possible with NimBLE. return MP_EOPNOTSUPP; } nimble_reset_gatts_bss(); int ret = ble_gatts_reset(); if (ret != 0) { return ble_hs_err_to_errno(ret); } // Reset the gatt characteristic value db. mp_bluetooth_gatts_db_reset(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db); // By default, just register the default gap/gatt service. ble_svc_gap_init(); ble_svc_gatt_init(); // Unref any previous service definitions. for (size_t i = 0; i < MP_STATE_PORT(bluetooth_nimble_root_pointers)->n_services; ++i) { MP_STATE_PORT(bluetooth_nimble_root_pointers)->services[i] = NULL; } MP_STATE_PORT(bluetooth_nimble_root_pointers)->n_services = 0; return 0; } int mp_bluetooth_gatts_register_service_end(void) { int ret = ble_gatts_start(); if (ret != 0) { return ble_hs_err_to_errno(ret); } return 0; } int mp_bluetooth_gatts_register_service(mp_obj_bluetooth_uuid_t *service_uuid, mp_obj_bluetooth_uuid_t **characteristic_uuids, uint16_t *characteristic_flags, mp_obj_bluetooth_uuid_t **descriptor_uuids, uint16_t *descriptor_flags, uint8_t *num_descriptors, uint16_t *handles, size_t num_characteristics) { if (MP_STATE_PORT(bluetooth_nimble_root_pointers)->n_services == MP_BLUETOOTH_NIMBLE_MAX_SERVICES) { return MP_E2BIG; } size_t handle_index = 0; size_t descriptor_index = 0; struct ble_gatt_chr_def *characteristics = m_new(struct ble_gatt_chr_def, num_characteristics + 1); for (size_t i = 0; i < num_characteristics; ++i) { characteristics[i].uuid = create_nimble_uuid(characteristic_uuids[i], NULL); characteristics[i].access_cb = characteristic_access_cb; characteristics[i].arg = NULL; // NimBLE flags match the MP_BLUETOOTH_CHARACTERISTIC_FLAG_ ones exactly (including the security/privacy options). characteristics[i].flags = characteristic_flags[i]; characteristics[i].min_key_size = 0; characteristics[i].val_handle = &handles[handle_index]; ++handle_index; if (num_descriptors[i] == 0) { characteristics[i].descriptors = NULL; } else { struct ble_gatt_dsc_def *descriptors = m_new(struct ble_gatt_dsc_def, num_descriptors[i] + 1); for (size_t j = 0; j < num_descriptors[i]; ++j) { descriptors[j].uuid = create_nimble_uuid(descriptor_uuids[descriptor_index], NULL); descriptors[j].access_cb = characteristic_access_cb; // NimBLE doesn't support security/privacy options on descriptors. descriptors[j].att_flags = (uint8_t)descriptor_flags[descriptor_index]; descriptors[j].min_key_size = 0; // Unlike characteristic, Nimble doesn't provide an automatic way to remember the handle, so use the arg. descriptors[j].arg = &handles[handle_index]; ++descriptor_index; ++handle_index; } descriptors[num_descriptors[i]].uuid = NULL; // no more descriptors characteristics[i].descriptors = descriptors; } } characteristics[num_characteristics].uuid = NULL; // no more characteristics struct ble_gatt_svc_def *service = m_new(struct ble_gatt_svc_def, 2); service[0].type = BLE_GATT_SVC_TYPE_PRIMARY; service[0].uuid = create_nimble_uuid(service_uuid, NULL); service[0].includes = NULL; service[0].characteristics = characteristics; service[1].type = 0; // no more services MP_STATE_PORT(bluetooth_nimble_root_pointers)->services[MP_STATE_PORT(bluetooth_nimble_root_pointers)->n_services++] = service; // Note: advertising must be stopped for gatts registration to work int ret = ble_gatts_count_cfg(service); if (ret != 0) { return ble_hs_err_to_errno(ret); } ret = ble_gatts_add_svcs(service); if (ret != 0) { return ble_hs_err_to_errno(ret); } return 0; } int mp_bluetooth_gap_disconnect(uint16_t conn_handle) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } return ble_hs_err_to_errno(ble_gap_terminate(conn_handle, BLE_ERR_REM_USER_CONN_TERM)); } int mp_bluetooth_gatts_read(uint16_t value_handle, uint8_t **value, size_t *value_len) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } return mp_bluetooth_gatts_db_read(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, value_handle, value, value_len); } int mp_bluetooth_gatts_write(uint16_t value_handle, const uint8_t *value, size_t value_len, bool send_update) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } int err = mp_bluetooth_gatts_db_write(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, value_handle, value, value_len); if (err == 0 && send_update) { ble_gatts_chr_updated(value_handle); } return err; } // TODO: Could use ble_gatts_chr_updated to send to all subscribed centrals. int mp_bluetooth_gatts_notify(uint16_t conn_handle, uint16_t value_handle) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } // Confusingly, notify/notify_custom/indicate are "gattc" function (even though they're used by peripherals (i.e. gatt servers)). // See https://www.mail-archive.com/dev@mynewt.apache.org/msg01293.html return ble_hs_err_to_errno(ble_gattc_notify(conn_handle, value_handle)); } int mp_bluetooth_gatts_notify_send(uint16_t conn_handle, uint16_t value_handle, const uint8_t *value, size_t value_len) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } struct os_mbuf *om = ble_hs_mbuf_from_flat(value, value_len); if (om == NULL) { return MP_ENOMEM; } return ble_hs_err_to_errno(ble_gattc_notify_custom(conn_handle, value_handle, om)); } int mp_bluetooth_gatts_indicate(uint16_t conn_handle, uint16_t value_handle) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } // This will raise BLE_GAP_EVENT_NOTIFY_TX with a status when it is // acknowledged (or timeout/error). return ble_hs_err_to_errno(ble_gattc_indicate(conn_handle, value_handle)); } int mp_bluetooth_gatts_set_buffer(uint16_t value_handle, size_t len, bool append) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } return mp_bluetooth_gatts_db_resize(MP_STATE_PORT(bluetooth_nimble_root_pointers)->gatts_db, value_handle, len, append); } int mp_bluetooth_get_preferred_mtu(void) { if (!mp_bluetooth_is_active()) { mp_raise_OSError(ERRNO_BLUETOOTH_NOT_ACTIVE); } return ble_att_preferred_mtu(); } int mp_bluetooth_set_preferred_mtu(uint16_t mtu) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } if (ble_att_set_preferred_mtu(mtu)) { return MP_EINVAL; } return 0; } #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING int mp_bluetooth_gap_pair(uint16_t conn_handle) { DEBUG_printf("mp_bluetooth_gap_pair: conn_handle=%d\n", conn_handle); return ble_hs_err_to_errno(ble_gap_security_initiate(conn_handle)); } int mp_bluetooth_gap_passkey(uint16_t conn_handle, uint8_t action, mp_int_t passkey) { struct ble_sm_io io = {0}; switch (action) { case MP_BLUETOOTH_PASSKEY_ACTION_INPUT: { io.passkey = passkey; break; } case MP_BLUETOOTH_PASSKEY_ACTION_DISPLAY: { io.passkey = passkey; break; } case MP_BLUETOOTH_PASSKEY_ACTION_NUMERIC_COMPARISON: { io.numcmp_accept = passkey != 0; break; } default: { return MP_EINVAL; } } io.action = action; DEBUG_printf("mp_bluetooth_gap_passkey: injecting IO: conn_handle=%d, action=%d, passkey=" UINT_FMT ", numcmp_accept=%d\n", conn_handle, io.action, (mp_uint_t)io.passkey, io.numcmp_accept); return ble_hs_err_to_errno(ble_sm_inject_io(conn_handle, &io)); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING #if MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE STATIC int gap_scan_cb(struct ble_gap_event *event, void *arg) { DEBUG_printf("gap_scan_cb: event=%d type=%d\n", event->type, event->type == BLE_GAP_EVENT_DISC ? event->disc.event_type : -1); if (!mp_bluetooth_is_active()) { return 0; } if (event->type == BLE_GAP_EVENT_DISC_COMPLETE) { mp_bluetooth_gap_on_scan_complete(); return 0; } if (event->type != BLE_GAP_EVENT_DISC) { return 0; } uint8_t addr[6]; reverse_addr_byte_order(addr, event->disc.addr.val); mp_bluetooth_gap_on_scan_result(event->disc.addr.type, addr, event->disc.event_type, event->disc.rssi, event->disc.data, event->disc.length_data); return 0; } int mp_bluetooth_gap_scan_start(int32_t duration_ms, int32_t interval_us, int32_t window_us, bool active_scan) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } if (duration_ms == 0) { duration_ms = BLE_HS_FOREVER; } struct ble_gap_disc_params discover_params = { .itvl = MAX(BLE_HCI_SCAN_ITVL_MIN, MIN(BLE_HCI_SCAN_ITVL_MAX, interval_us / BLE_HCI_SCAN_ITVL)), .window = MAX(BLE_HCI_SCAN_WINDOW_MIN, MIN(BLE_HCI_SCAN_WINDOW_MAX, window_us / BLE_HCI_SCAN_ITVL)), .filter_policy = BLE_HCI_CONN_FILT_NO_WL, .limited = 0, .passive = active_scan ? 0 : 1, .filter_duplicates = 0, }; int err = ble_gap_disc(nimble_address_mode, duration_ms, &discover_params, gap_scan_cb, NULL); return ble_hs_err_to_errno(err); } int mp_bluetooth_gap_scan_stop(void) { DEBUG_printf("mp_bluetooth_gap_scan_stop\n"); if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } if (!ble_gap_disc_active()) { return 0; } int err = ble_gap_disc_cancel(); if (err == 0) { mp_bluetooth_gap_on_scan_complete(); return 0; } return ble_hs_err_to_errno(err); } // Central role: GAP events for a connected peripheral. STATIC int peripheral_gap_event_cb(struct ble_gap_event *event, void *arg) { DEBUG_printf("peripheral_gap_event_cb: event=%d\n", event->type); if (!mp_bluetooth_is_active()) { return 0; } struct ble_gap_conn_desc desc; uint8_t addr[6] = {0}; switch (event->type) { case BLE_GAP_EVENT_CONNECT: DEBUG_printf("peripheral_gap_event_cb: status=%d\n", event->connect.status); if (event->connect.status == 0) { // Connection established. ble_gap_conn_find(event->connect.conn_handle, &desc); reverse_addr_byte_order(addr, desc.peer_id_addr.val); mp_bluetooth_gap_on_connected_disconnected(MP_BLUETOOTH_IRQ_PERIPHERAL_CONNECT, event->connect.conn_handle, desc.peer_id_addr.type, addr); } else { // Connection failed. mp_bluetooth_gap_on_connected_disconnected(MP_BLUETOOTH_IRQ_PERIPHERAL_DISCONNECT, event->connect.conn_handle, 0xff, addr); } return 0; case BLE_GAP_EVENT_DISCONNECT: // Disconnect. DEBUG_printf("peripheral_gap_event_cb: reason=%d\n", event->disconnect.reason); reverse_addr_byte_order(addr, event->disconnect.conn.peer_id_addr.val); mp_bluetooth_gap_on_connected_disconnected(MP_BLUETOOTH_IRQ_PERIPHERAL_DISCONNECT, event->disconnect.conn.conn_handle, event->disconnect.conn.peer_id_addr.type, addr); return 0; } return commmon_gap_event_cb(event, arg); } int mp_bluetooth_gap_peripheral_connect(uint8_t addr_type, const uint8_t *addr, int32_t duration_ms) { DEBUG_printf("mp_bluetooth_gap_peripheral_connect\n"); if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } if (ble_gap_disc_active()) { mp_bluetooth_gap_scan_stop(); } // TODO: This is the same as ble_gap_conn_params_dflt (i.e. passing NULL). STATIC const struct ble_gap_conn_params params = { .scan_itvl = 0x0010, .scan_window = 0x0010, .itvl_min = BLE_GAP_INITIAL_CONN_ITVL_MIN, .itvl_max = BLE_GAP_INITIAL_CONN_ITVL_MAX, .latency = BLE_GAP_INITIAL_CONN_LATENCY, .supervision_timeout = BLE_GAP_INITIAL_SUPERVISION_TIMEOUT, .min_ce_len = BLE_GAP_INITIAL_CONN_MIN_CE_LEN, .max_ce_len = BLE_GAP_INITIAL_CONN_MAX_CE_LEN, }; ble_addr_t addr_nimble = create_nimble_addr(addr_type, addr); int err = ble_gap_connect(nimble_address_mode, &addr_nimble, duration_ms, &params, &peripheral_gap_event_cb, NULL); return ble_hs_err_to_errno(err); } STATIC int ble_gattc_service_cb(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_svc *service, void *arg) { DEBUG_printf("ble_gattc_service_cb: conn_handle=%d status=%d start_handle=%d\n", conn_handle, error->status, service ? service->start_handle : -1); if (!mp_bluetooth_is_active()) { return 0; } if (error->status == 0) { mp_obj_bluetooth_uuid_t service_uuid = create_mp_uuid(&service->uuid); mp_bluetooth_gattc_on_primary_service_result(conn_handle, service->start_handle, service->end_handle, &service_uuid); } else { mp_bluetooth_gattc_on_discover_complete(MP_BLUETOOTH_IRQ_GATTC_SERVICE_DONE, conn_handle, error->status == BLE_HS_EDONE ? 0 : error->status); } return 0; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_CENTRAL_MODE #if MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT STATIC void gattc_on_data_available(uint8_t event, uint16_t conn_handle, uint16_t value_handle, const struct os_mbuf *om) { // When the HCI data for an ATT payload arrives, the L2CAP channel will // buffer it into its receive buffer. We set BLE_L2CAP_JOIN_RX_FRAGS=1 in // syscfg.h so it should be rare that the mbuf is fragmented, but we do need // to be able to handle it. We pass all the fragments up to modbluetooth.c // which will create a temporary buffer on the MicroPython heap if necessary // to re-assemble them. // Count how many links are in the mbuf chain. size_t n = 0; const struct os_mbuf *elem = om; while (elem) { n += 1; elem = SLIST_NEXT(elem, om_next); } // Grab data pointers and lengths for each of the links. const uint8_t **data = mp_local_alloc(sizeof(uint8_t *) * n); uint16_t *data_len = mp_local_alloc(sizeof(uint16_t) * n); for (size_t i = 0; i < n; ++i) { data[i] = OS_MBUF_DATA(om, const uint8_t *); data_len[i] = om->om_len; om = SLIST_NEXT(om, om_next); } // Pass all the fragments together. mp_bluetooth_gattc_on_data_available(event, conn_handle, value_handle, data, data_len, n); mp_local_free(data_len); mp_local_free(data); } int mp_bluetooth_gattc_discover_primary_services(uint16_t conn_handle, const mp_obj_bluetooth_uuid_t *uuid) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } int err; if (uuid) { ble_uuid_any_t nimble_uuid; create_nimble_uuid(uuid, &nimble_uuid); err = ble_gattc_disc_svc_by_uuid(conn_handle, &nimble_uuid.u, &ble_gattc_service_cb, NULL); } else { err = ble_gattc_disc_all_svcs(conn_handle, &ble_gattc_service_cb, NULL); } return ble_hs_err_to_errno(err); } STATIC int ble_gattc_characteristic_cb(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_chr *characteristic, void *arg) { DEBUG_printf("ble_gattc_characteristic_cb: conn_handle=%d status=%d def_handle=%d val_handle=%d\n", conn_handle, error->status, characteristic ? characteristic->def_handle : -1, characteristic ? characteristic->val_handle : -1); if (!mp_bluetooth_is_active()) { return 0; } if (error->status == 0) { mp_obj_bluetooth_uuid_t characteristic_uuid = create_mp_uuid(&characteristic->uuid); mp_bluetooth_gattc_on_characteristic_result(conn_handle, characteristic->def_handle, characteristic->val_handle, characteristic->properties, &characteristic_uuid); } else { mp_bluetooth_gattc_on_discover_complete(MP_BLUETOOTH_IRQ_GATTC_CHARACTERISTIC_DONE, conn_handle, error->status == BLE_HS_EDONE ? 0 : error->status); } return 0; } int mp_bluetooth_gattc_discover_characteristics(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle, const mp_obj_bluetooth_uuid_t *uuid) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } int err; if (uuid) { ble_uuid_any_t nimble_uuid; create_nimble_uuid(uuid, &nimble_uuid); err = ble_gattc_disc_chrs_by_uuid(conn_handle, start_handle, end_handle, &nimble_uuid.u, &ble_gattc_characteristic_cb, NULL); } else { err = ble_gattc_disc_all_chrs(conn_handle, start_handle, end_handle, &ble_gattc_characteristic_cb, NULL); } return ble_hs_err_to_errno(err); } STATIC int ble_gattc_descriptor_cb(uint16_t conn_handle, const struct ble_gatt_error *error, uint16_t characteristic_val_handle, const struct ble_gatt_dsc *descriptor, void *arg) { DEBUG_printf("ble_gattc_descriptor_cb: conn_handle=%d status=%d chr_handle=%d dsc_handle=%d\n", conn_handle, error->status, characteristic_val_handle, descriptor ? descriptor->handle : -1); if (!mp_bluetooth_is_active()) { return 0; } if (error->status == 0) { mp_obj_bluetooth_uuid_t descriptor_uuid = create_mp_uuid(&descriptor->uuid); mp_bluetooth_gattc_on_descriptor_result(conn_handle, descriptor->handle, &descriptor_uuid); } else { mp_bluetooth_gattc_on_discover_complete(MP_BLUETOOTH_IRQ_GATTC_DESCRIPTOR_DONE, conn_handle, error->status == BLE_HS_EDONE ? 0 : error->status); } return 0; } int mp_bluetooth_gattc_discover_descriptors(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } int err = ble_gattc_disc_all_dscs(conn_handle, start_handle, end_handle, &ble_gattc_descriptor_cb, NULL); return ble_hs_err_to_errno(err); } STATIC int ble_gattc_attr_read_cb(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) { uint16_t handle = attr ? attr->handle : (error ? error->att_handle : 0xffff); DEBUG_printf("ble_gattc_attr_read_cb: conn_handle=%d status=%d handle=%d\n", conn_handle, error->status, handle); if (!mp_bluetooth_is_active()) { return 0; } if (error->status == 0) { gattc_on_data_available(MP_BLUETOOTH_IRQ_GATTC_READ_RESULT, conn_handle, attr->handle, attr->om); } mp_bluetooth_gattc_on_read_write_status(MP_BLUETOOTH_IRQ_GATTC_READ_DONE, conn_handle, handle, error->status); return 0; } // Initiate read of a value from the remote peripheral. int mp_bluetooth_gattc_read(uint16_t conn_handle, uint16_t value_handle) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } int err = ble_gattc_read(conn_handle, value_handle, &ble_gattc_attr_read_cb, NULL); return ble_hs_err_to_errno(err); } STATIC int ble_gattc_attr_write_cb(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) { uint16_t handle = attr ? attr->handle : (error ? error->att_handle : 0xffff); DEBUG_printf("ble_gattc_attr_write_cb: conn_handle=%d status=%d handle=%d\n", conn_handle, error->status, handle); if (!mp_bluetooth_is_active()) { return 0; } mp_bluetooth_gattc_on_read_write_status(MP_BLUETOOTH_IRQ_GATTC_WRITE_DONE, conn_handle, handle, error->status); return 0; } // Write the value to the remote peripheral. int mp_bluetooth_gattc_write(uint16_t conn_handle, uint16_t value_handle, const uint8_t *value, size_t *value_len, unsigned int mode) { if (!mp_bluetooth_is_active()) { return ERRNO_BLUETOOTH_NOT_ACTIVE; } int err; if (mode == MP_BLUETOOTH_WRITE_MODE_NO_RESPONSE) { err = ble_gattc_write_no_rsp_flat(conn_handle, value_handle, value, *value_len); } else if (mode == MP_BLUETOOTH_WRITE_MODE_WITH_RESPONSE) { err = ble_gattc_write_flat(conn_handle, value_handle, value, *value_len, &ble_gattc_attr_write_cb, NULL); } else { err = BLE_HS_EINVAL; } return ble_hs_err_to_errno(err); } int mp_bluetooth_gattc_exchange_mtu(uint16_t conn_handle) { DEBUG_printf("mp_bluetooth_exchange_mtu: conn_handle=%d mtu=%d\n", conn_handle, ble_att_preferred_mtu()); // Using NULL callback (we'll get notified in gap_event_cb instead). return ble_hs_err_to_errno(ble_gattc_exchange_mtu(conn_handle, NULL, NULL)); } #endif // MICROPY_PY_BLUETOOTH_ENABLE_GATT_CLIENT #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS STATIC void unstall_l2cap_channel(void); #endif void mp_bluetooth_nimble_sent_hci_packet(void) { #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS if (os_msys_num_free() >= os_msys_count() * 3 / 4) { unstall_l2cap_channel(); } #endif } #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS // Fortunately NimBLE uses mbuf chains correctly with L2CAP COC (rather than // accessing the mbuf internals directly), so we can use a small block size to // avoid excessive fragmentation and rely on them chaining together for larger // payloads. #define L2CAP_BUF_BLOCK_SIZE (128) // This gives us enough room to have one MTU-size transmit buffer and two // MTU-sized receive buffers. Note that we use the local MTU to calculate // the buffer size. This means that if the peer MTU is larger, then // there might not be enough space in the pool to send a full peer-MTU // sized payload and mp_bluetooth_l2cap_send will return ENOMEM. #define L2CAP_BUF_SIZE_MTUS_PER_CHANNEL (3) typedef struct _mp_bluetooth_nimble_l2cap_channel_t { struct ble_l2cap_chan *chan; struct os_mbuf_pool sdu_mbuf_pool; struct os_mempool sdu_mempool; struct os_mbuf *rx_pending; bool irq_in_progress; bool mem_stalled; uint16_t mtu; os_membuf_t sdu_mem[]; } mp_bluetooth_nimble_l2cap_channel_t; STATIC void destroy_l2cap_channel(); STATIC int l2cap_channel_event(struct ble_l2cap_event *event, void *arg); STATIC mp_bluetooth_nimble_l2cap_channel_t *get_l2cap_channel_for_conn_cid(uint16_t conn_handle, uint16_t cid); STATIC int create_l2cap_channel(uint16_t mtu, mp_bluetooth_nimble_l2cap_channel_t **out); STATIC void destroy_l2cap_channel() { // Only free the l2cap channel if we're the one that initiated the connection. // Listeners continue listening on the same channel. if (!MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_listening) { MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_chan = NULL; } } STATIC void unstall_l2cap_channel(void) { // Whenever we send an HCI packet and the sys mempool is now less than 1/4 full, // we can unstall the L2CAP channel if it was marked as "mem_stalled" by // mp_bluetooth_l2cap_send. (This happens if the pool is half-empty). mp_bluetooth_nimble_l2cap_channel_t *chan = MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_chan; if (!chan || !chan->mem_stalled) { return; } DEBUG_printf("unstall_l2cap_channel: count %d, free: %d\n", os_msys_count(), os_msys_num_free()); chan->mem_stalled = false; mp_bluetooth_on_l2cap_send_ready(chan->chan->conn_handle, chan->chan->scid, 0); } STATIC int l2cap_channel_event(struct ble_l2cap_event *event, void *arg) { DEBUG_printf("l2cap_channel_event: type=%d\n", event->type); mp_bluetooth_nimble_l2cap_channel_t *chan = (mp_bluetooth_nimble_l2cap_channel_t *)arg; struct ble_l2cap_chan_info info; switch (event->type) { case BLE_L2CAP_EVENT_COC_CONNECTED: { DEBUG_printf("l2cap_channel_event: connect: conn_handle=%d status=%d\n", event->connect.conn_handle, event->connect.status); chan->chan = event->connect.chan; ble_l2cap_get_chan_info(event->connect.chan, &info); if (event->connect.status == 0) { mp_bluetooth_on_l2cap_connect(event->connect.conn_handle, info.scid, info.psm, info.our_coc_mtu, info.peer_coc_mtu); } else { mp_bluetooth_on_l2cap_disconnect(event->connect.conn_handle, info.scid, info.psm, event->connect.status); destroy_l2cap_channel(); } break; } case BLE_L2CAP_EVENT_COC_DISCONNECTED: { DEBUG_printf("l2cap_channel_event: disconnect: conn_handle=%d\n", event->disconnect.conn_handle); ble_l2cap_get_chan_info(event->disconnect.chan, &info); mp_bluetooth_on_l2cap_disconnect(event->disconnect.conn_handle, info.scid, info.psm, 0); destroy_l2cap_channel(); break; } case BLE_L2CAP_EVENT_COC_ACCEPT: { DEBUG_printf("l2cap_channel_event: accept: conn_handle=%d peer_sdu_size=%d\n", event->accept.conn_handle, event->accept.peer_sdu_size); chan->chan = event->accept.chan; ble_l2cap_get_chan_info(event->accept.chan, &info); int ret = mp_bluetooth_on_l2cap_accept(event->accept.conn_handle, info.scid, info.psm, info.our_coc_mtu, info.peer_coc_mtu); if (ret != 0) { return ret; } struct os_mbuf *sdu_rx = os_mbuf_get_pkthdr(&chan->sdu_mbuf_pool, 0); assert(sdu_rx); return ble_l2cap_recv_ready(chan->chan, sdu_rx); } case BLE_L2CAP_EVENT_COC_DATA_RECEIVED: { DEBUG_printf("l2cap_channel_event: receive: conn_handle=%d len=%d\n", event->receive.conn_handle, OS_MBUF_PKTLEN(event->receive.sdu_rx)); if (chan->rx_pending) { // Ideally this doesn't happen, as the sender should not get // any more credits to send more data until we call // ble_l2cap_recv_ready. However there might be multiple // in-flight packets if the sender was able to send more than // one before stalling. DEBUG_printf("l2cap_channel_event: receive: appending to rx pending\n"); // Note: os_mbuf_concat will just join the two together, so // sdu_rx is now "owned" by rx_pending. os_mbuf_concat(chan->rx_pending, event->receive.sdu_rx); } else { // Normal case is when the first payload arrives since calling // ble_l2cap_recv_ready. DEBUG_printf("l2cap_event: receive: new payload\n"); // Take ownership of sdu_rx. chan->rx_pending = event->receive.sdu_rx; } struct os_mbuf *sdu_rx = os_mbuf_get_pkthdr(&chan->sdu_mbuf_pool, 0); assert(sdu_rx); // ble_l2cap_coc_rx_fn invokes this event handler when a complete payload arrives. // However, it NULLs chan->chan->coc_rx.sdu before doing so, expecting that // ble_l2cap_recv_ready will be called to give it a new mbuf. // This means that if another payload arrives before we call ble_l2cap_recv_ready // then ble_l2cap_coc_rx_fn will NULL-deref coc_rx.sdu. // Because we're not yet ready to grant new credits to the channel, we can't call // ble_l2cap_recv_ready yet, so instead we just give it a new mbuf. This requires // ble_l2cap_priv.h for the definition of chan->chan (i.e. struct ble_l2cap_chan). chan->chan->coc_rx.sdu = sdu_rx; ble_l2cap_get_chan_info(event->receive.chan, &info); // Don't allow granting more credits until after the IRQ is handled. chan->irq_in_progress = true; mp_bluetooth_on_l2cap_recv(event->receive.conn_handle, info.scid); chan->irq_in_progress = false; // If all data has been consumed by the IRQ handler, then now allow // more credits. If the IRQ handler doesn't consume all available data // then rx_pending will be still set. if (!chan->rx_pending) { struct os_mbuf *sdu_rx = chan->chan->coc_rx.sdu; assert(sdu_rx); if (sdu_rx) { ble_l2cap_recv_ready(chan->chan, sdu_rx); } } break; } case BLE_L2CAP_EVENT_COC_TX_UNSTALLED: { DEBUG_printf("l2cap_channel_event: tx_unstalled: conn_handle=%d status=%d\n", event->tx_unstalled.conn_handle, event->tx_unstalled.status); assert(event->tx_unstalled.conn_handle == chan->chan->conn_handle); // Don't unstall if we're still waiting for room in the sys pool. if (!chan->mem_stalled) { ble_l2cap_get_chan_info(event->receive.chan, &info); // Map status to {0,1} (i.e. "sent everything", or "partial send"). mp_bluetooth_on_l2cap_send_ready(event->tx_unstalled.conn_handle, info.scid, event->tx_unstalled.status == 0 ? 0 : 1); } break; } case BLE_L2CAP_EVENT_COC_RECONFIG_COMPLETED: { DEBUG_printf("l2cap_channel_event: reconfig_completed: conn_handle=%d\n", event->reconfigured.conn_handle); break; } case BLE_L2CAP_EVENT_COC_PEER_RECONFIGURED: { DEBUG_printf("l2cap_channel_event: peer_reconfigured: conn_handle=%d\n", event->reconfigured.conn_handle); break; } default: { DEBUG_printf("l2cap_channel_event: unknown event\n"); break; } } return 0; } STATIC mp_bluetooth_nimble_l2cap_channel_t *get_l2cap_channel_for_conn_cid(uint16_t conn_handle, uint16_t cid) { // TODO: Support more than one concurrent L2CAP channel. At the moment we // just verify that the cid refers to the current channel. mp_bluetooth_nimble_l2cap_channel_t *chan = MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_chan; if (!chan) { return NULL; } struct ble_l2cap_chan_info info; ble_l2cap_get_chan_info(chan->chan, &info); if (info.scid != cid || ble_l2cap_get_conn_handle(chan->chan) != conn_handle) { return NULL; } return chan; } STATIC int create_l2cap_channel(uint16_t mtu, mp_bluetooth_nimble_l2cap_channel_t **out) { if (MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_chan) { // Only one L2CAP channel allowed. // Additionally, if we're listening, then no connections may be initiated. DEBUG_printf("create_l2cap_channel: channel already in use\n"); return MP_EALREADY; } // We want the TX and RX buffers to share a pool that is some multiple of // the MTU size. Figure out how many blocks per MTU (rounding up), then // multiply that by the "MTUs per channel" (set to 3 above). const size_t buf_blocks = MP_CEIL_DIVIDE(mtu, L2CAP_BUF_BLOCK_SIZE) * L2CAP_BUF_SIZE_MTUS_PER_CHANNEL; mp_bluetooth_nimble_l2cap_channel_t *chan = m_new_obj_var(mp_bluetooth_nimble_l2cap_channel_t, uint8_t, OS_MEMPOOL_SIZE(buf_blocks, L2CAP_BUF_BLOCK_SIZE) * sizeof(os_membuf_t)); MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_chan = chan; // Will be set in BLE_L2CAP_EVENT_COC_CONNECTED or BLE_L2CAP_EVENT_COC_ACCEPT. chan->chan = NULL; chan->mtu = mtu; chan->rx_pending = NULL; chan->irq_in_progress = false; int err = os_mempool_init(&chan->sdu_mempool, buf_blocks, L2CAP_BUF_BLOCK_SIZE, chan->sdu_mem, "l2cap_sdu_pool"); if (err != 0) { DEBUG_printf("mp_bluetooth_l2cap_connect: os_mempool_init failed %d\n", err); return MP_ENOMEM; } err = os_mbuf_pool_init(&chan->sdu_mbuf_pool, &chan->sdu_mempool, L2CAP_BUF_BLOCK_SIZE, buf_blocks); if (err != 0) { DEBUG_printf("mp_bluetooth_l2cap_connect: os_mbuf_pool_init failed %d\n", err); return MP_ENOMEM; } *out = chan; return 0; } int mp_bluetooth_l2cap_listen(uint16_t psm, uint16_t mtu) { DEBUG_printf("mp_bluetooth_l2cap_listen: psm=%d, mtu=%d\n", psm, mtu); mp_bluetooth_nimble_l2cap_channel_t *chan; int err = create_l2cap_channel(mtu, &chan); if (err != 0) { return err; } MP_STATE_PORT(bluetooth_nimble_root_pointers)->l2cap_listening = true; return ble_hs_err_to_errno(ble_l2cap_create_server(psm, mtu, &l2cap_channel_event, chan)); } int mp_bluetooth_l2cap_connect(uint16_t conn_handle, uint16_t psm, uint16_t mtu) { DEBUG_printf("mp_bluetooth_l2cap_connect: conn_handle=%d, psm=%d, mtu=%d\n", conn_handle, psm, mtu); mp_bluetooth_nimble_l2cap_channel_t *chan; int err = create_l2cap_channel(mtu, &chan); if (err != 0) { return err; } struct os_mbuf *sdu_rx = os_mbuf_get_pkthdr(&chan->sdu_mbuf_pool, 0); assert(sdu_rx); return ble_hs_err_to_errno(ble_l2cap_connect(conn_handle, psm, mtu, sdu_rx, &l2cap_channel_event, chan)); } int mp_bluetooth_l2cap_disconnect(uint16_t conn_handle, uint16_t cid) { DEBUG_printf("mp_bluetooth_l2cap_disconnect: conn_handle=%d, cid=%d\n", conn_handle, cid); mp_bluetooth_nimble_l2cap_channel_t *chan = get_l2cap_channel_for_conn_cid(conn_handle, cid); if (!chan) { return MP_EINVAL; } return ble_hs_err_to_errno(ble_l2cap_disconnect(chan->chan)); } int mp_bluetooth_l2cap_send(uint16_t conn_handle, uint16_t cid, const uint8_t *buf, size_t len, bool *stalled) { DEBUG_printf("mp_bluetooth_l2cap_send: conn_handle=%d, cid=%d, len=%d\n", conn_handle, cid, (int)len); mp_bluetooth_nimble_l2cap_channel_t *chan = get_l2cap_channel_for_conn_cid(conn_handle, cid); if (!chan) { return MP_EINVAL; } struct ble_l2cap_chan_info info; ble_l2cap_get_chan_info(chan->chan, &info); if (len > info.peer_coc_mtu) { // This is verified by ble_l2cap_send anyway, but this lets us // avoid copying a too-large buffer into an mbuf. return MP_EINVAL; } if (len > (L2CAP_BUF_SIZE_MTUS_PER_CHANNEL - 1) * info.our_coc_mtu) { // Always ensure there's at least one local MTU of space left in the buffer // for the RX buffer. return MP_EINVAL; } // Grab an mbuf from the pool, and append the incoming buffer to it. struct os_mbuf *sdu_tx = os_mbuf_get_pkthdr(&chan->sdu_mbuf_pool, 0); if (sdu_tx == NULL) { return MP_ENOMEM; } int err = os_mbuf_append(sdu_tx, buf, len); if (err) { os_mbuf_free_chain(sdu_tx); return MP_ENOMEM; } *stalled = false; err = ble_l2cap_send(chan->chan, sdu_tx); if (err == BLE_HS_ESTALLED) { // Stalled means that this one will still send but any future ones // will fail until we receive an unstalled event. DEBUG_printf("mp_bluetooth_l2cap_send: credit stall\n"); *stalled = true; err = 0; } else { if (err) { // Anything except stalled means it won't attempt to send, // so free the mbuf (we're failing the op entirely). os_mbuf_free_chain(sdu_tx); } } if (os_msys_num_free() <= os_msys_count() / 2) { // If the sys mempool is less than half-full, then back off sending more // on this channel. DEBUG_printf("mp_bluetooth_l2cap_send: forcing mem stall: count %d, free: %d\n", os_msys_count(), os_msys_num_free()); chan->mem_stalled = true; *stalled = true; } // Sometimes we see what looks like BLE_HS_EAGAIN (but it's actually // OS_ENOMEM in disguise). Fixed in NimBLE v1.4. if (err == OS_ENOMEM) { err = BLE_HS_ENOMEM; } // Other error codes such as BLE_HS_EBUSY (we're stalled) or BLE_HS_EBADDATA (bigger than MTU). return ble_hs_err_to_errno(err); } int mp_bluetooth_l2cap_recvinto(uint16_t conn_handle, uint16_t cid, uint8_t *buf, size_t *len) { mp_bluetooth_nimble_l2cap_channel_t *chan = get_l2cap_channel_for_conn_cid(conn_handle, cid); if (!chan) { return MP_EINVAL; } MICROPY_PY_BLUETOOTH_ENTER if (chan->rx_pending) { size_t avail = OS_MBUF_PKTLEN(chan->rx_pending); if (buf == NULL) { // Can use this to implement a poll - just find out how much is available. *len = avail; } else { // Have dest buffer and data available. // Figure out how much we should copy. *len = min(*len, avail); // Extract the required number of bytes. os_mbuf_copydata(chan->rx_pending, 0, *len, buf); if (*len == avail) { // That's all that's available -- free this mbuf and re-enable receiving. os_mbuf_free_chain(chan->rx_pending); chan->rx_pending = NULL; // If we're in the call stack of the l2cap_channel_event handler, then don't // re-enable receiving yet (as we need to complete the rest of IRQ handler first). if (!chan->irq_in_progress) { // We've already given the channel a new mbuf in l2cap_channel_event above, so // re-use that mbuf in the call to ble_l2cap_recv_ready. This will just // give the channel more credits. struct os_mbuf *sdu_rx = chan->chan->coc_rx.sdu; assert(sdu_rx); if (sdu_rx) { ble_l2cap_recv_ready(chan->chan, sdu_rx); } } } else { // Trim the used bytes from the start of the mbuf. // Positive argument means "trim this many from head". os_mbuf_adj(chan->rx_pending, *len); // Clean up any empty mbufs at the head. chan->rx_pending = os_mbuf_trim_front(chan->rx_pending); } } } else { // No pending data. *len = 0; } MICROPY_PY_BLUETOOTH_EXIT return 0; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS #if MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD int mp_bluetooth_hci_cmd(uint16_t ogf, uint16_t ocf, const uint8_t *req, size_t req_len, uint8_t *resp, size_t resp_len, uint8_t *status) { int rc = ble_hs_hci_cmd_tx(BLE_HCI_OP(ogf, ocf), req, req_len, resp, resp_len); if (rc < BLE_HS_ERR_HCI_BASE || rc >= BLE_HS_ERR_HCI_BASE + 0x100) { // The controller didn't handle the command (e.g. HCI timeout). return ble_hs_err_to_errno(rc); } else { // The command executed, but had an error (i.e. invalid parameter). *status = rc - BLE_HS_ERR_HCI_BASE; return 0; } } #endif // MICROPY_PY_BLUETOOTH_ENABLE_HCI_CMD #if MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING STATIC int ble_store_ram_read(int obj_type, const union ble_store_key *key, union ble_store_value *value) { DEBUG_printf("ble_store_ram_read: %d\n", obj_type); const uint8_t *key_data; size_t key_data_len; switch (obj_type) { case BLE_STORE_OBJ_TYPE_PEER_SEC: { if (ble_addr_cmp(&key->sec.peer_addr, BLE_ADDR_ANY)) { // <type=peer,addr,*> (single) // Find the entry for this specific peer. assert(key->sec.idx == 0); assert(!key->sec.ediv_rand_present); key_data = (const uint8_t *)&key->sec.peer_addr; key_data_len = sizeof(ble_addr_t); } else { // <type=peer,*> (with index) // Iterate all known peers. assert(!key->sec.ediv_rand_present); key_data = NULL; key_data_len = 0; } break; } case BLE_STORE_OBJ_TYPE_OUR_SEC: { // <type=our,addr,ediv_rand> // Find our secret for this remote device, matching this ediv/rand key. assert(ble_addr_cmp(&key->sec.peer_addr, BLE_ADDR_ANY)); // Must have address. assert(key->sec.idx == 0); assert(key->sec.ediv_rand_present); key_data = (const uint8_t *)&key->sec.peer_addr; key_data_len = sizeof(ble_addr_t); break; } case BLE_STORE_OBJ_TYPE_CCCD: { // TODO: Implement CCCD persistence. DEBUG_printf("ble_store_ram_read: CCCD not supported.\n"); return -1; } default: return BLE_HS_ENOTSUP; } const uint8_t *value_data; size_t value_data_len; if (!mp_bluetooth_gap_on_get_secret(obj_type, key->sec.idx, key_data, key_data_len, &value_data, &value_data_len)) { DEBUG_printf("ble_store_ram_read: Key not found: type=%d, index=%u, key=0x%p, len=" UINT_FMT "\n", obj_type, key->sec.idx, key_data, key_data_len); return BLE_HS_ENOENT; } if (value_data_len != sizeof(struct ble_store_value_sec)) { DEBUG_printf("ble_store_ram_read: Invalid key data: actual=" UINT_FMT " expected=" UINT_FMT "\n", value_data_len, sizeof(struct ble_store_value_sec)); return BLE_HS_ENOENT; } memcpy((uint8_t *)&value->sec, value_data, sizeof(struct ble_store_value_sec)); DEBUG_printf("ble_store_ram_read: found secret\n"); if (obj_type == BLE_STORE_OBJ_TYPE_OUR_SEC) { // TODO: Verify ediv_rand matches. } return 0; } STATIC int ble_store_ram_write(int obj_type, const union ble_store_value *val) { DEBUG_printf("ble_store_ram_write: %d\n", obj_type); switch (obj_type) { case BLE_STORE_OBJ_TYPE_PEER_SEC: case BLE_STORE_OBJ_TYPE_OUR_SEC: { // <type=peer,addr,edivrand> struct ble_store_key_sec key_sec; const struct ble_store_value_sec *value_sec = &val->sec; ble_store_key_from_value_sec(&key_sec, value_sec); assert(ble_addr_cmp(&key_sec.peer_addr, BLE_ADDR_ANY)); // Must have address. assert(key_sec.ediv_rand_present); if (!mp_bluetooth_gap_on_set_secret(obj_type, (const uint8_t *)&key_sec.peer_addr, sizeof(ble_addr_t), (const uint8_t *)value_sec, sizeof(struct ble_store_value_sec))) { DEBUG_printf("Failed to write key: type=%d\n", obj_type); return BLE_HS_ESTORE_CAP; } DEBUG_printf("ble_store_ram_write: wrote secret\n"); return 0; } case BLE_STORE_OBJ_TYPE_CCCD: { // TODO: Implement CCCD persistence. DEBUG_printf("ble_store_ram_write: CCCD not supported.\n"); // Just pretend we wrote it. return 0; } default: return BLE_HS_ENOTSUP; } } STATIC int ble_store_ram_delete(int obj_type, const union ble_store_key *key) { DEBUG_printf("ble_store_ram_delete: %d\n", obj_type); switch (obj_type) { case BLE_STORE_OBJ_TYPE_PEER_SEC: case BLE_STORE_OBJ_TYPE_OUR_SEC: { // <type=peer,addr,*> assert(ble_addr_cmp(&key->sec.peer_addr, BLE_ADDR_ANY)); // Must have address. // ediv_rand is optional (will not be present for delete). if (!mp_bluetooth_gap_on_set_secret(obj_type, (const uint8_t *)&key->sec.peer_addr, sizeof(ble_addr_t), NULL, 0)) { DEBUG_printf("Failed to delete key: type=%d\n", obj_type); return BLE_HS_ENOENT; } DEBUG_printf("ble_store_ram_delete: deleted secret\n"); return 0; } case BLE_STORE_OBJ_TYPE_CCCD: { // TODO: Implement CCCD persistence. DEBUG_printf("ble_store_ram_delete: CCCD not supported.\n"); // Just pretend it wasn't there. return BLE_HS_ENOENT; } default: return BLE_HS_ENOTSUP; } } // nimble_port_init always calls ble_store_ram_init. We provide this alternative // implementation rather than the one in nimble/store/ram/src/ble_store_ram.c. // TODO: Consider re-implementing nimble_port_init instead. void ble_store_ram_init(void) { ble_hs_cfg.store_read_cb = ble_store_ram_read; ble_hs_cfg.store_write_cb = ble_store_ram_write; ble_hs_cfg.store_delete_cb = ble_store_ram_delete; } #endif // MICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING #endif // MICROPY_PY_BLUETOOTH && MICROPY_BLUETOOTH_NIMBLE
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/modbluetooth_nimble.c
C
apache-2.0
79,213
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 Jim Mussared * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_NIMBLE_MODBLUETOOTH_NIMBLE_H #define MICROPY_INCLUDED_EXTMOD_NIMBLE_MODBLUETOOTH_NIMBLE_H #include "extmod/modbluetooth.h" #define MP_BLUETOOTH_NIMBLE_MAX_SERVICES (8) typedef struct _mp_bluetooth_nimble_root_pointers_t { // Characteristic (and descriptor) value storage. mp_gatts_db_t gatts_db; // Pending service definitions. size_t n_services; struct ble_gatt_svc_def *services[MP_BLUETOOTH_NIMBLE_MAX_SERVICES]; #if MICROPY_PY_BLUETOOTH_ENABLE_L2CAP_CHANNELS // L2CAP channels. struct _mp_bluetooth_nimble_l2cap_channel_t *l2cap_chan; bool l2cap_listening; #endif } mp_bluetooth_nimble_root_pointers_t; enum { MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF, MP_BLUETOOTH_NIMBLE_BLE_STATE_STARTING, MP_BLUETOOTH_NIMBLE_BLE_STATE_WAITING_FOR_SYNC, MP_BLUETOOTH_NIMBLE_BLE_STATE_ACTIVE, MP_BLUETOOTH_NIMBLE_BLE_STATE_STOPPING, }; extern volatile int mp_bluetooth_nimble_ble_state; // --- Optionally provided by the MicroPython port. --------------------------- // (default implementations provided by modbluetooth_nimble.c) // Tell the port to init the UART and start the HCI controller. void mp_bluetooth_nimble_port_hci_init(void); // Tell the port to deinit the UART and shutdown the HCI controller. void mp_bluetooth_nimble_port_hci_deinit(void); // Tell the port to run its background task (i.e. poll the UART and pump events). void mp_bluetooth_nimble_port_start(void); // Tell the port to stop its background task. void mp_bluetooth_nimble_port_shutdown(void); // --- Called by the HCI UART layer to let us know when packets have been sent. void mp_bluetooth_nimble_sent_hci_packet(void); #endif // MICROPY_INCLUDED_EXTMOD_NIMBLE_MODBLUETOOTH_NIMBLE_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/modbluetooth_nimble.h
C
apache-2.0
2,976
# Makefile directives for Apache Mynewt NimBLE component ifeq ($(MICROPY_BLUETOOTH_NIMBLE),1) EXTMOD_DIR = extmod NIMBLE_EXTMOD_DIR = $(EXTMOD_DIR)/nimble EXTMOD_SRC_C += $(NIMBLE_EXTMOD_DIR)/modbluetooth_nimble.c CFLAGS_MOD += -DMICROPY_BLUETOOTH_NIMBLE=1 # Use NimBLE from the submodule in lib/mynewt-nimble by default, # allowing a port to use their own system version (e.g. ESP32). MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY ?= 0 CFLAGS_MOD += -DMICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY=$(MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY) ifeq ($(MICROPY_BLUETOOTH_NIMBLE_BINDINGS_ONLY),0) # On all ports where we provide the full implementation (i.e. not just # bindings like on ESP32), then we don't need to use the ringbuffer. In this # case, all NimBLE events are run by the MicroPython scheduler. On Unix, the # scheduler is also responsible for polling the UART, whereas on STM32 the # UART is also polled by the RX IRQ. CFLAGS_MOD += -DMICROPY_PY_BLUETOOTH_USE_SYNC_EVENTS=1 # Without the ringbuffer, and with the full implementation, we can also # enable pairing and bonding. This requires both synchronous events and # some customisation of the key store. CFLAGS_MOD += -DMICROPY_PY_BLUETOOTH_ENABLE_PAIRING_BONDING=1 NIMBLE_LIB_DIR = lib/mynewt-nimble LIB_SRC_C += $(addprefix $(NIMBLE_LIB_DIR)/, \ $(addprefix ext/tinycrypt/src/, \ aes_encrypt.c \ cmac_mode.c \ ecc.c \ ecc_dh.c \ utils.c \ ) \ nimble/host/services/gap/src/ble_svc_gap.c \ nimble/host/services/gatt/src/ble_svc_gatt.c \ $(addprefix nimble/host/src/, \ ble_att.c \ ble_att_clt.c \ ble_att_cmd.c \ ble_att_svr.c \ ble_eddystone.c \ ble_gap.c \ ble_gattc.c \ ble_gatts.c \ ble_hs_adv.c \ ble_hs_atomic.c \ ble_hs.c \ ble_hs_cfg.c \ ble_hs_conn.c \ ble_hs_flow.c \ ble_hs_hci.c \ ble_hs_hci_cmd.c \ ble_hs_hci_evt.c \ ble_hs_hci_util.c \ ble_hs_id.c \ ble_hs_log.c \ ble_hs_mbuf.c \ ble_hs_misc.c \ ble_hs_mqueue.c \ ble_hs_pvcy.c \ ble_hs_startup.c \ ble_hs_stop.c \ ble_ibeacon.c \ ble_l2cap.c \ ble_l2cap_coc.c \ ble_l2cap_sig.c \ ble_l2cap_sig_cmd.c \ ble_monitor.c \ ble_sm_alg.c \ ble_sm.c \ ble_sm_cmd.c \ ble_sm_lgcy.c \ ble_sm_sc.c \ ble_store.c \ ble_store_util.c \ ble_uuid.c \ ) \ nimble/host/util/src/addr.c \ nimble/transport/uart/src/ble_hci_uart.c \ $(addprefix porting/nimble/src/, \ endian.c \ mem.c \ nimble_port.c \ os_mbuf.c \ os_mempool.c \ os_msys_init.c \ ) \ ) # nimble/host/store/ram/src/ble_store_ram.c \ EXTMOD_SRC_C += $(addprefix $(NIMBLE_EXTMOD_DIR)/, \ nimble/nimble_npl_os.c \ hal/hal_uart.c \ ) INC += -I$(TOP)/$(NIMBLE_EXTMOD_DIR) INC += -I$(TOP)/$(NIMBLE_LIB_DIR) INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/ext/tinycrypt/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/host/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/host/services/gap/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/host/services/gatt/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/host/store/ram/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/host/util/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/nimble/transport/uart/include INC += -I$(TOP)/$(NIMBLE_LIB_DIR)/porting/nimble/include $(BUILD)/$(NIMBLE_LIB_DIR)/%.o: CFLAGS += -Wno-maybe-uninitialized -Wno-pointer-arith -Wno-unused-but-set-variable -Wno-format -Wno-sign-compare -Wno-old-style-declaration endif endif
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/nimble.mk
Makefile
apache-2.0
3,420
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include "py/mphal.h" #include "py/runtime.h" #include "nimble/ble.h" #include "nimble/nimble_npl.h" #include "extmod/nimble/hal/hal_uart.h" #include "extmod/modbluetooth.h" #include "extmod/nimble/modbluetooth_nimble.h" #define DEBUG_OS_printf(...) // printf(__VA_ARGS__) #define DEBUG_MALLOC_printf(...) // printf(__VA_ARGS__) #define DEBUG_EVENT_printf(...) // printf(__VA_ARGS__) #define DEBUG_MUTEX_printf(...) // printf(__VA_ARGS__) #define DEBUG_SEM_printf(...) // printf(__VA_ARGS__) #define DEBUG_CALLOUT_printf(...) // printf(__VA_ARGS__) #define DEBUG_TIME_printf(...) // printf(__VA_ARGS__) #define DEBUG_CRIT_printf(...) // printf(__VA_ARGS__) bool ble_npl_os_started(void) { DEBUG_OS_printf("ble_npl_os_started\n"); return true; } void *ble_npl_get_current_task_id(void) { DEBUG_OS_printf("ble_npl_get_current_task_id\n"); return NULL; } /******************************************************************************/ // malloc // Maintain a linked list of heap memory that we've passed to Nimble, // discoverable via the bluetooth_nimble_memory root pointer. typedef struct _mp_bluetooth_nimble_malloc_t { struct _mp_bluetooth_nimble_malloc_t *prev; struct _mp_bluetooth_nimble_malloc_t *next; size_t size; uint8_t data[]; } mp_bluetooth_nimble_malloc_t; // TODO: This is duplicated from mbedtls. Perhaps make this a generic feature? STATIC void *m_malloc_bluetooth(size_t size) { size += sizeof(mp_bluetooth_nimble_malloc_t); mp_bluetooth_nimble_malloc_t *alloc = m_malloc0(size); alloc->size = size; alloc->next = MP_STATE_PORT(bluetooth_nimble_memory); if (alloc->next) { alloc->next->prev = alloc; } MP_STATE_PORT(bluetooth_nimble_memory) = alloc; return alloc->data; } STATIC mp_bluetooth_nimble_malloc_t* get_nimble_malloc(void *ptr) { return (mp_bluetooth_nimble_malloc_t*)((uintptr_t)ptr - sizeof(mp_bluetooth_nimble_malloc_t)); } STATIC void m_free_bluetooth(void *ptr) { mp_bluetooth_nimble_malloc_t *alloc = get_nimble_malloc(ptr); if (alloc->next) { alloc->next->prev = alloc->prev; } if (alloc->prev) { alloc->prev->next = alloc->next; } else { MP_STATE_PORT(bluetooth_nimble_memory) = NULL; } m_free(alloc #if MICROPY_MALLOC_USES_ALLOCATED_SIZE , alloc->size #endif ); } // Check if a nimble ptr is tracked. // If it isn't, that means that it's from a previous soft-reset cycle. STATIC bool is_valid_nimble_malloc(void *ptr) { DEBUG_MALLOC_printf("NIMBLE is_valid_nimble_malloc(%p)\n", ptr); mp_bluetooth_nimble_malloc_t *alloc = MP_STATE_PORT(bluetooth_nimble_memory); while (alloc) { DEBUG_MALLOC_printf("NIMBLE checking: %p\n", alloc->data); if (alloc->data == ptr) { return true; } alloc = alloc->next; } return false; } void *nimble_malloc(size_t size) { DEBUG_MALLOC_printf("NIMBLE malloc(%u)\n", (uint)size); void* ptr = m_malloc_bluetooth(size); DEBUG_MALLOC_printf(" --> %p\n", ptr); return ptr; } // Only free if it's still a valid pointer. void nimble_free(void *ptr) { DEBUG_MALLOC_printf("NIMBLE free(%p)\n", ptr); if (ptr) { // After a stack re-init, NimBLE has variables in BSS that might be // still pointing to old allocations from a previous init. We can't do // anything about this (e.g. ble_gatts_free_mem is private). But we // can identify that this is a non-null, invalid alloc because it // won't be in our list, so ignore it because it is effectively free'd // anyway (it's not referenced by anything the GC can find). if (is_valid_nimble_malloc(ptr)) { m_free_bluetooth(ptr); } } } // Only realloc if it's still a valid pointer. Otherwise just malloc. void *nimble_realloc(void *ptr, size_t new_size) { DEBUG_MALLOC_printf("NIMBLE realloc(%p, %u)\n", ptr, (uint)new_size); if (!ptr) { return nimble_malloc(new_size); } assert(is_valid_nimble_malloc(ptr)); // Existing alloc is big enough. mp_bluetooth_nimble_malloc_t *alloc = get_nimble_malloc(ptr); size_t old_size = alloc->size - sizeof(mp_bluetooth_nimble_malloc_t); if (old_size >= new_size) { return ptr; } // Allocate a new, larger region. void *ptr2 = m_malloc_bluetooth(new_size); // Copy old, smaller region into new region. memcpy(ptr2, ptr, old_size); m_free_bluetooth(ptr); DEBUG_MALLOC_printf(" --> %p\n", ptr2); return ptr2; } // No-op implementation (only used by NimBLE logging). int nimble_sprintf(char *str, const char *fmt, ...) { str[0] = 0; return 0; } /******************************************************************************/ // EVENTQ struct ble_npl_eventq *global_eventq = NULL; // This must not be called recursively or concurrently with the UART handler. void mp_bluetooth_nimble_os_eventq_run_all(void) { if (mp_bluetooth_nimble_ble_state == MP_BLUETOOTH_NIMBLE_BLE_STATE_OFF) { return; } // Keep running while there are pending events. while (true) { struct ble_npl_event *ev = NULL; os_sr_t sr; OS_ENTER_CRITICAL(sr); // Search all queues for an event. for (struct ble_npl_eventq *evq = global_eventq; evq != NULL; evq = evq->nextq) { ev = evq->head; if (ev) { // Remove this event from the queue. evq->head = ev->next; if (ev->next) { ev->next->prev = NULL; ev->next = NULL; } ev->prev = NULL; ev->pending = false; // Stop searching and execute this event. break; } } OS_EXIT_CRITICAL(sr); if (!ev) { break; } // Run the event handler. DEBUG_EVENT_printf("event_run(%p)\n", ev); ev->fn(ev); DEBUG_EVENT_printf("event_run(%p) done\n", ev); if (ev->pending) { // If this event has been re-enqueued while it was running, then // stop running further events. This prevents an infinite loop // where the reset event re-enqueues itself on HCI timeout. break; } } } void ble_npl_eventq_init(struct ble_npl_eventq *evq) { DEBUG_EVENT_printf("ble_npl_eventq_init(%p)\n", evq); os_sr_t sr; OS_ENTER_CRITICAL(sr); evq->head = NULL; struct ble_npl_eventq **evq2; for (evq2 = &global_eventq; *evq2 != NULL; evq2 = &(*evq2)->nextq) { } *evq2 = evq; evq->nextq = NULL; OS_EXIT_CRITICAL(sr); } void ble_npl_eventq_put(struct ble_npl_eventq *evq, struct ble_npl_event *ev) { DEBUG_EVENT_printf("ble_npl_eventq_put(%p, %p (%p, %p))\n", evq, ev, ev->fn, ev->arg); os_sr_t sr; OS_ENTER_CRITICAL(sr); ev->next = NULL; ev->pending = true; if (evq->head == NULL) { // Empty list, make this the first item. evq->head = ev; ev->prev = NULL; } else { // Find the tail of this list. struct ble_npl_event *tail = evq->head; while (true) { if (tail == ev) { DEBUG_EVENT_printf(" --> already in queue\n"); // Already in the list (e.g. a fragmented ACL will enqueue an // event to process it for each fragment). break; } if (tail->next == NULL) { // Found the end of the list, add this event as the tail. tail->next = ev; ev->prev = tail; break; } DEBUG_EVENT_printf(" --> %p\n", tail->next); tail = tail->next; } } OS_EXIT_CRITICAL(sr); } void ble_npl_event_init(struct ble_npl_event *ev, ble_npl_event_fn *fn, void *arg) { DEBUG_EVENT_printf("ble_npl_event_init(%p, %p, %p)\n", ev, fn, arg); ev->fn = fn; ev->arg = arg; ev->next = NULL; ev->pending = false; } void *ble_npl_event_get_arg(struct ble_npl_event *ev) { DEBUG_EVENT_printf("ble_npl_event_get_arg(%p) -> %p\n", ev, ev->arg); return ev->arg; } void ble_npl_event_set_arg(struct ble_npl_event *ev, void *arg) { DEBUG_EVENT_printf("ble_npl_event_set_arg(%p, %p)\n", ev, arg); ev->arg = arg; } /******************************************************************************/ // MUTEX ble_npl_error_t ble_npl_mutex_init(struct ble_npl_mutex *mu) { DEBUG_MUTEX_printf("ble_npl_mutex_init(%p)\n", mu); mu->locked = 0; return BLE_NPL_OK; } ble_npl_error_t ble_npl_mutex_pend(struct ble_npl_mutex *mu, ble_npl_time_t timeout) { DEBUG_MUTEX_printf("ble_npl_mutex_pend(%p, %u) locked=%u\n", mu, (uint)timeout, (uint)mu->locked); // All NimBLE code is executed by the scheduler (and is therefore // implicitly mutexed) so this mutex implementation is a no-op. ++mu->locked; return BLE_NPL_OK; } ble_npl_error_t ble_npl_mutex_release(struct ble_npl_mutex *mu) { DEBUG_MUTEX_printf("ble_npl_mutex_release(%p) locked=%u\n", mu, (uint)mu->locked); assert(mu->locked > 0); --mu->locked; return BLE_NPL_OK; } /******************************************************************************/ // SEM ble_npl_error_t ble_npl_sem_init(struct ble_npl_sem *sem, uint16_t tokens) { DEBUG_SEM_printf("ble_npl_sem_init(%p, %u)\n", sem, (uint)tokens); sem->count = tokens; return BLE_NPL_OK; } ble_npl_error_t ble_npl_sem_pend(struct ble_npl_sem *sem, ble_npl_time_t timeout) { DEBUG_SEM_printf("ble_npl_sem_pend(%p, %u) count=%u\n", sem, (uint)timeout, (uint)sem->count); // This is only called by NimBLE in ble_hs_hci_cmd_tx to synchronously // wait for an HCI ACK. The corresponding ble_npl_sem_release is called // directly by the UART rx handler (i.e. hal_uart_rx_cb in // extmod/nimble/hal/hal_uart.c). So this loop needs to run only the HCI // UART processing but not run any events. if (sem->count == 0) { uint32_t t0 = mp_hal_ticks_ms(); while (sem->count == 0 && mp_hal_ticks_ms() - t0 < timeout) { if (sem->count != 0) { break; } mp_bluetooth_nimble_hci_uart_wfi(); } if (sem->count == 0) { DEBUG_SEM_printf("ble_npl_sem_pend: semaphore timeout\n"); return BLE_NPL_TIMEOUT; } DEBUG_SEM_printf("ble_npl_sem_pend: acquired in %u ms\n", (int)(mp_hal_ticks_ms() - t0)); } sem->count -= 1; return BLE_NPL_OK; } ble_npl_error_t ble_npl_sem_release(struct ble_npl_sem *sem) { DEBUG_SEM_printf("ble_npl_sem_release(%p)\n", sem); sem->count += 1; return BLE_NPL_OK; } uint16_t ble_npl_sem_get_count(struct ble_npl_sem *sem) { DEBUG_SEM_printf("ble_npl_sem_get_count(%p)\n", sem); return sem->count; } /******************************************************************************/ // CALLOUT static struct ble_npl_callout *global_callout = NULL; void mp_bluetooth_nimble_os_callout_process(void) { os_sr_t sr; OS_ENTER_CRITICAL(sr); uint32_t tnow = mp_hal_ticks_ms(); for (struct ble_npl_callout *c = global_callout; c != NULL; c = c->nextc) { if (!c->active) { continue; } if ((int32_t)(tnow - c->ticks) >= 0) { DEBUG_CALLOUT_printf("callout_run(%p) tnow=%u ticks=%u evq=%p\n", c, (uint)tnow, (uint)c->ticks, c->evq); c->active = false; if (c->evq) { // Enqueue this callout for execution in the event queue. ble_npl_eventq_put(c->evq, &c->ev); } else { // Execute this callout directly. OS_EXIT_CRITICAL(sr); c->ev.fn(&c->ev); OS_ENTER_CRITICAL(sr); } DEBUG_CALLOUT_printf("callout_run(%p) done\n", c); } } OS_EXIT_CRITICAL(sr); } void ble_npl_callout_init(struct ble_npl_callout *c, struct ble_npl_eventq *evq, ble_npl_event_fn *ev_cb, void *ev_arg) { DEBUG_CALLOUT_printf("ble_npl_callout_init(%p, %p, %p, %p)\n", c, evq, ev_cb, ev_arg); os_sr_t sr; OS_ENTER_CRITICAL(sr); c->active = false; c->ticks = 0; c->evq = evq; ble_npl_event_init(&c->ev, ev_cb, ev_arg); struct ble_npl_callout **c2; for (c2 = &global_callout; *c2 != NULL; c2 = &(*c2)->nextc) { if (c == *c2) { // callout already in linked list so don't link it in again OS_EXIT_CRITICAL(sr); return; } } *c2 = c; c->nextc = NULL; OS_EXIT_CRITICAL(sr); } ble_npl_error_t ble_npl_callout_reset(struct ble_npl_callout *c, ble_npl_time_t ticks) { DEBUG_CALLOUT_printf("ble_npl_callout_reset(%p, %u) tnow=%u\n", c, (uint)ticks, (uint)mp_hal_ticks_ms()); os_sr_t sr; OS_ENTER_CRITICAL(sr); c->active = true; c->ticks = ble_npl_time_get() + ticks; OS_EXIT_CRITICAL(sr); return BLE_NPL_OK; } void ble_npl_callout_stop(struct ble_npl_callout *c) { DEBUG_CALLOUT_printf("ble_npl_callout_stop(%p)\n", c); c->active = false; } bool ble_npl_callout_is_active(struct ble_npl_callout *c) { DEBUG_CALLOUT_printf("ble_npl_callout_is_active(%p)\n", c); return c->active; } ble_npl_time_t ble_npl_callout_get_ticks(struct ble_npl_callout *c) { DEBUG_CALLOUT_printf("ble_npl_callout_get_ticks(%p)\n", c); return c->ticks; } ble_npl_time_t ble_npl_callout_remaining_ticks(struct ble_npl_callout *c, ble_npl_time_t now) { DEBUG_CALLOUT_printf("ble_npl_callout_remaining_ticks(%p, %u)\n", c, (uint)now); if (c->ticks > now) { return c->ticks - now; } else { return 0; } } void *ble_npl_callout_get_arg(struct ble_npl_callout *c) { DEBUG_CALLOUT_printf("ble_npl_callout_get_arg(%p)\n", c); return ble_npl_event_get_arg(&c->ev); } void ble_npl_callout_set_arg(struct ble_npl_callout *c, void *arg) { DEBUG_CALLOUT_printf("ble_npl_callout_set_arg(%p, %p)\n", c, arg); ble_npl_event_set_arg(&c->ev, arg); } /******************************************************************************/ // TIME uint32_t ble_npl_time_get(void) { DEBUG_TIME_printf("ble_npl_time_get -> %u\n", (uint)mp_hal_ticks_ms()); return mp_hal_ticks_ms(); } ble_npl_error_t ble_npl_time_ms_to_ticks(uint32_t ms, ble_npl_time_t *out_ticks) { DEBUG_TIME_printf("ble_npl_time_ms_to_ticks(%u)\n", (uint)ms); *out_ticks = ms; return BLE_NPL_OK; } ble_npl_time_t ble_npl_time_ms_to_ticks32(uint32_t ms) { DEBUG_TIME_printf("ble_npl_time_ms_to_ticks32(%u)\n", (uint)ms); return ms; } uint32_t ble_npl_time_ticks_to_ms32(ble_npl_time_t ticks) { DEBUG_TIME_printf("ble_npl_time_ticks_to_ms32(%u)\n", (uint)ticks); return ticks; } void ble_npl_time_delay(ble_npl_time_t ticks) { mp_hal_delay_ms(ticks + 1); } /******************************************************************************/ // CRITICAL // This is used anywhere NimBLE modifies global data structures. // Currently all NimBLE code is invoked by the scheduler so there should be no // races, so on STM32 MICROPY_PY_BLUETOOTH_ENTER/MICROPY_PY_BLUETOOTH_EXIT are // no-ops. However, in the future we may wish to make HCI UART processing // happen asynchronously (e.g. on RX IRQ), so the port can implement these // macros accordingly. uint32_t ble_npl_hw_enter_critical(void) { DEBUG_CRIT_printf("ble_npl_hw_enter_critical()\n"); MICROPY_PY_BLUETOOTH_ENTER return atomic_state; } void ble_npl_hw_exit_critical(uint32_t atomic_state) { MICROPY_PY_BLUETOOTH_EXIT DEBUG_CRIT_printf("ble_npl_hw_exit_critical(%u)\n", (uint)atomic_state); }
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/nimble/nimble_npl_os.c
C
apache-2.0
17,014
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_STM32_NIMBLE_NIMBLE_NIMBLE_NPL_OS_H #define MICROPY_INCLUDED_STM32_NIMBLE_NIMBLE_NIMBLE_NPL_OS_H // This is included by nimble/nimble_npl.h -- include that rather than this file directly. #include <stdint.h> #include <limits.h> // --- Configuration of NimBLE data structures -------------------------------- // This is used at runtime to align allocations correctly. #define BLE_NPL_OS_ALIGNMENT (sizeof(uintptr_t)) #define BLE_NPL_TIME_FOREVER (0xffffffff) // This is used at compile time to force struct member alignment. See // os_mempool.h for where this is used (none of these three macros are defined // by default). #define OS_CFG_ALIGN_4 (4) #define OS_CFG_ALIGN_8 (8) #if (ULONG_MAX == 0xffffffffffffffff) #define OS_CFG_ALIGNMENT (OS_CFG_ALIGN_8) #else #define OS_CFG_ALIGNMENT (OS_CFG_ALIGN_4) #endif typedef uint32_t ble_npl_time_t; typedef int32_t ble_npl_stime_t; struct ble_npl_event { ble_npl_event_fn *fn; void *arg; bool pending; struct ble_npl_event *prev; struct ble_npl_event *next; }; struct ble_npl_eventq { struct ble_npl_event *head; struct ble_npl_eventq *nextq; }; struct ble_npl_callout { bool active; uint32_t ticks; struct ble_npl_eventq *evq; struct ble_npl_event ev; struct ble_npl_callout *nextc; }; struct ble_npl_mutex { volatile uint8_t locked; }; struct ble_npl_sem { volatile uint16_t count; }; // --- Called by the MicroPython port ----------------------------------------- void mp_bluetooth_nimble_os_eventq_run_all(void); void mp_bluetooth_nimble_os_callout_process(void); // --- Must be provided by the MicroPython port ------------------------------- void mp_bluetooth_nimble_hci_uart_wfi(void); #endif // MICROPY_INCLUDED_STM32_NIMBLE_NIMBLE_NPL_OS_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/nimble/nimble_npl_os.h
C
apache-2.0
3,023
#ifndef MICROPY_INCLUDED_EXTMOD_NIMBLE_SYSCFG_H #define MICROPY_INCLUDED_EXTMOD_NIMBLE_SYSCFG_H #include "py/mphal.h" #include "mpnimbleport.h" void *nimble_malloc(size_t size); void nimble_free(void *ptr); void *nimble_realloc(void *ptr, size_t size); // Redirect NimBLE malloc to the GC heap. #define malloc(size) nimble_malloc(size) #define free(ptr) nimble_free(ptr) #define realloc(ptr, size) nimble_realloc(ptr, size) int nimble_sprintf(char *str, const char *fmt, ...); #define sprintf(str, fmt, ...) nimble_sprintf(str, fmt, __VA_ARGS__) #define MYNEWT_VAL(x) MYNEWT_VAL_ ## x #define MYNEWT_VAL_LOG_LEVEL (255) /*** compiler/arm-none-eabi-m4 */ #define MYNEWT_VAL_HARDFLOAT (1) /*** kernel/os */ #define MYNEWT_VAL_FLOAT_USER (0) #define MYNEWT_VAL_MSYS_1_BLOCK_COUNT (12) #define MYNEWT_VAL_MSYS_1_BLOCK_SIZE (292) #define MYNEWT_VAL_MSYS_2_BLOCK_COUNT (0) #define MYNEWT_VAL_MSYS_2_BLOCK_SIZE (0) #define MYNEWT_VAL_OS_CPUTIME_FREQ (1000000) #define MYNEWT_VAL_OS_CPUTIME_TIMER_NUM (0) #define MYNEWT_VAL_OS_CTX_SW_STACK_CHECK (0) #define MYNEWT_VAL_OS_CTX_SW_STACK_GUARD (4) #define MYNEWT_VAL_OS_MAIN_STACK_SIZE (1024) #define MYNEWT_VAL_OS_MAIN_TASK_PRIO (127) #define MYNEWT_VAL_OS_MEMPOOL_CHECK (0) #define MYNEWT_VAL_OS_MEMPOOL_POISON (0) /*** nimble */ #define MYNEWT_VAL_BLE_EXT_ADV (0) #define MYNEWT_VAL_BLE_EXT_ADV_MAX_SIZE (31) #define MYNEWT_VAL_BLE_MAX_CONNECTIONS (4) #define MYNEWT_VAL_BLE_MULTI_ADV_INSTANCES (0) #define MYNEWT_VAL_BLE_ROLE_BROADCASTER (1) #define MYNEWT_VAL_BLE_ROLE_CENTRAL (1) #define MYNEWT_VAL_BLE_ROLE_OBSERVER (1) #define MYNEWT_VAL_BLE_ROLE_PERIPHERAL (1) #define MYNEWT_VAL_BLE_WHITELIST (1) /*** nimble/host */ #define MYNEWT_VAL_BLE_ATT_PREFERRED_MTU (256) #define MYNEWT_VAL_BLE_ATT_SVR_FIND_INFO (1) #define MYNEWT_VAL_BLE_ATT_SVR_FIND_TYPE (1) #define MYNEWT_VAL_BLE_ATT_SVR_INDICATE (1) #define MYNEWT_VAL_BLE_ATT_SVR_MAX_PREP_ENTRIES (64) #define MYNEWT_VAL_BLE_ATT_SVR_NOTIFY (1) #define MYNEWT_VAL_BLE_ATT_SVR_QUEUED_WRITE (1) #define MYNEWT_VAL_BLE_ATT_SVR_QUEUED_WRITE_TMO (30000) #define MYNEWT_VAL_BLE_ATT_SVR_READ (1) #define MYNEWT_VAL_BLE_ATT_SVR_READ_BLOB (1) #define MYNEWT_VAL_BLE_ATT_SVR_READ_GROUP_TYPE (1) #define MYNEWT_VAL_BLE_ATT_SVR_READ_MULT (1) #define MYNEWT_VAL_BLE_ATT_SVR_READ_TYPE (1) #define MYNEWT_VAL_BLE_ATT_SVR_SIGNED_WRITE (1) #define MYNEWT_VAL_BLE_ATT_SVR_WRITE (1) #define MYNEWT_VAL_BLE_ATT_SVR_WRITE_NO_RSP (1) #define MYNEWT_VAL_BLE_GAP_MAX_PENDING_CONN_PARAM_UPDATE (1) #define MYNEWT_VAL_BLE_GATT_DISC_ALL_CHRS (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_DISC_ALL_DSCS (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_DISC_ALL_SVCS (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_DISC_CHR_UUID (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_DISC_SVC_UUID (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_FIND_INC_SVCS (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_INDICATE (1) #define MYNEWT_VAL_BLE_GATT_MAX_PROCS (4) #define MYNEWT_VAL_BLE_GATT_NOTIFY (1) #define MYNEWT_VAL_BLE_GATT_READ (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_READ_LONG (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_READ_MAX_ATTRS (8) #define MYNEWT_VAL_BLE_GATT_READ_MULT (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_READ_UUID (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_RESUME_RATE (1000) #define MYNEWT_VAL_BLE_GATT_SIGNED_WRITE (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_WRITE (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_WRITE_LONG (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_WRITE_MAX_ATTRS (4) #define MYNEWT_VAL_BLE_GATT_WRITE_NO_RSP (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_GATT_WRITE_RELIABLE (MYNEWT_VAL_BLE_ROLE_CENTRAL) #define MYNEWT_VAL_BLE_HOST (1) #define MYNEWT_VAL_BLE_HS_AUTO_START (1) #define MYNEWT_VAL_BLE_HS_DEBUG (0) #define MYNEWT_VAL_BLE_HS_FLOW_CTRL (0) #define MYNEWT_VAL_BLE_HS_FLOW_CTRL_ITVL (1000) #define MYNEWT_VAL_BLE_HS_FLOW_CTRL_THRESH (2) #define MYNEWT_VAL_BLE_HS_FLOW_CTRL_TX_ON_DISCONNECT (0) #define MYNEWT_VAL_BLE_HS_PHONY_HCI_ACKS (0) #define MYNEWT_VAL_BLE_HS_REQUIRE_OS (1) #define MYNEWT_VAL_BLE_HS_STOP_ON_SHUTDOWN_TIMEOUT (2000) #define MYNEWT_VAL_BLE_L2CAP_COC_MAX_NUM (1) #define MYNEWT_VAL_BLE_L2CAP_COC_MPS (MYNEWT_VAL_MSYS_1_BLOCK_SIZE - 8) #define MYNEWT_VAL_BLE_L2CAP_ENHANCED_COC (0) #define MYNEWT_VAL_BLE_L2CAP_JOIN_RX_FRAGS (1) #define MYNEWT_VAL_BLE_L2CAP_MAX_CHANS (3 * MYNEWT_VAL_BLE_MAX_CONNECTIONS) #define MYNEWT_VAL_BLE_L2CAP_RX_FRAG_TIMEOUT (30000) #define MYNEWT_VAL_BLE_L2CAP_SIG_MAX_PROCS (1) #define MYNEWT_VAL_BLE_MONITOR_CONSOLE_BUFFER_SIZE (128) #define MYNEWT_VAL_BLE_MONITOR_RTT (0) #define MYNEWT_VAL_BLE_MONITOR_RTT_BUFFERED (1) #define MYNEWT_VAL_BLE_MONITOR_RTT_BUFFER_NAME ("monitor") #define MYNEWT_VAL_BLE_MONITOR_RTT_BUFFER_SIZE (256) #define MYNEWT_VAL_BLE_MONITOR_UART (0) #define MYNEWT_VAL_BLE_MONITOR_UART_BAUDRATE (1000000) #define MYNEWT_VAL_BLE_MONITOR_UART_BUFFER_SIZE (64) #define MYNEWT_VAL_BLE_MONITOR_UART_DEV ("uart0") #define MYNEWT_VAL_BLE_RPA_TIMEOUT (300) #define MYNEWT_VAL_BLE_SM_KEYPRESS (0) #define MYNEWT_VAL_BLE_SM_LEGACY (1) #define MYNEWT_VAL_BLE_SM_MAX_PROCS (1) #define MYNEWT_VAL_BLE_SM_OOB_DATA_FLAG (0) #define MYNEWT_VAL_BLE_SM_OUR_KEY_DIST (7) #define MYNEWT_VAL_BLE_SM_THEIR_KEY_DIST (7) #define MYNEWT_VAL_BLE_STORE_MAX_BONDS (3) #define MYNEWT_VAL_BLE_STORE_MAX_CCCDS (8) // These can be overridden at runtime with ble.config(le_secure, mitm, bond, io). #define MYNEWT_VAL_BLE_SM_SC (1) #define MYNEWT_VAL_BLE_SM_MITM (0) #define MYNEWT_VAL_BLE_SM_BONDING (0) #define MYNEWT_VAL_BLE_SM_IO_CAP (BLE_HS_IO_NO_INPUT_OUTPUT) /*** nimble/host/services/gap */ #define MYNEWT_VAL_BLE_SVC_GAP_APPEARANCE (0) #define MYNEWT_VAL_BLE_SVC_GAP_APPEARANCE_WRITE_PERM (-1) #define MYNEWT_VAL_BLE_SVC_GAP_CENTRAL_ADDRESS_RESOLUTION (-1) #define MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME ("pybd") #define MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_MAX_LENGTH (31) #define MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_WRITE_PERM (-1) #define MYNEWT_VAL_BLE_SVC_GAP_PPCP_MAX_CONN_INTERVAL (0) #define MYNEWT_VAL_BLE_SVC_GAP_PPCP_MIN_CONN_INTERVAL (0) #define MYNEWT_VAL_BLE_SVC_GAP_PPCP_SLAVE_LATENCY (0) #define MYNEWT_VAL_BLE_SVC_GAP_PPCP_SUPERVISION_TMO (0) /* Overridden by targets/porting-nimble (defined by nimble/transport) */ #define MYNEWT_VAL_BLE_HCI_TRANSPORT_NIMBLE_BUILTIN (0) #define MYNEWT_VAL_BLE_HCI_TRANSPORT_RAM (0) #define MYNEWT_VAL_BLE_HCI_TRANSPORT_SOCKET (0) #define MYNEWT_VAL_BLE_HCI_TRANSPORT_UART (1) /*** nimble/transport/uart */ #define MYNEWT_VAL_BLE_ACL_BUF_COUNT (12) #define MYNEWT_VAL_BLE_ACL_BUF_SIZE (255) #define MYNEWT_VAL_BLE_HCI_ACL_OUT_COUNT (12) #define MYNEWT_VAL_BLE_HCI_EVT_BUF_SIZE (70) #define MYNEWT_VAL_BLE_HCI_EVT_HI_BUF_COUNT (8) #define MYNEWT_VAL_BLE_HCI_EVT_LO_BUF_COUNT (8) /* Overridden by targets/porting-nimble (defined by nimble/transport/uart) */ #define MYNEWT_VAL_BLE_HCI_UART_BAUD (MICROPY_HW_BLE_UART_BAUDRATE) #define MYNEWT_VAL_BLE_HCI_UART_DATA_BITS (8) #define MYNEWT_VAL_BLE_HCI_UART_FLOW_CTRL (1) #define MYNEWT_VAL_BLE_HCI_UART_PARITY (HAL_UART_PARITY_NONE) #define MYNEWT_VAL_BLE_HCI_UART_PORT (MICROPY_HW_BLE_UART_ID) #define MYNEWT_VAL_BLE_HCI_UART_STOP_BITS (1) /* Required for code that uses BLE_HS_LOG */ #define MYNEWT_VAL_NEWT_FEATURE_LOGCFG (1) #endif // MICROPY_INCLUDED_EXTMOD_NIMBLE_SYSCFG_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/nimble/syscfg/syscfg.h
C
apache-2.0
7,418
# MicroPython uasyncio module # MIT license; Copyright (c) 2019 Damien P. George from .core import * __version__ = (3, 0, 0) _attrs = { "wait_for": "funcs", "wait_for_ms": "funcs", "gather": "funcs", "Event": "event", "ThreadSafeFlag": "event", "Lock": "lock", "open_connection": "stream", "start_server": "stream", "StreamReader": "stream", "StreamWriter": "stream", } # Lazy loader, effectively does: # global attr # from .mod import attr def __getattr__(attr): mod = _attrs.get(attr, None) if mod is None: raise AttributeError(attr) value = getattr(__import__(mod, None, None, True, 1), attr) globals()[attr] = value return value
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/__init__.py
Python
apache-2.0
709
# MicroPython uasyncio module # MIT license; Copyright (c) 2019 Damien P. George from time import ticks_ms as ticks, ticks_diff, ticks_add import sys, select # Import TaskQueue and Task, preferring built-in C code over Python code try: from _uasyncio import TaskQueue, Task except: from .task import TaskQueue, Task ################################################################################ # Exceptions class CancelledError(BaseException): pass class TimeoutError(Exception): pass # Used when calling Loop.call_exception_handler _exc_context = {"message": "Task exception wasn't retrieved", "exception": None, "future": None} ################################################################################ # Sleep functions # "Yield" once, then raise StopIteration class SingletonGenerator: def __init__(self): self.state = None self.exc = StopIteration() def __iter__(self): return self def __next__(self): if self.state is not None: _task_queue.push_sorted(cur_task, self.state) self.state = None return None else: self.exc.__traceback__ = None raise self.exc # Pause task execution for the given time (integer in milliseconds, uPy extension) # Use a SingletonGenerator to do it without allocating on the heap def sleep_ms(t, sgen=SingletonGenerator()): assert sgen.state is None sgen.state = ticks_add(ticks(), max(0, t)) return sgen # Pause task execution for the given time (in seconds) def sleep(t): return sleep_ms(int(t * 1000)) ################################################################################ # Queue and poller for stream IO class IOQueue: def __init__(self): self.poller = select.poll() self.map = {} # maps id(stream) to [task_waiting_read, task_waiting_write, stream] def _enqueue(self, s, idx): if id(s) not in self.map: entry = [None, None, s] entry[idx] = cur_task self.map[id(s)] = entry self.poller.register(s, select.POLLIN if idx == 0 else select.POLLOUT) else: sm = self.map[id(s)] assert sm[idx] is None assert sm[1 - idx] is not None sm[idx] = cur_task self.poller.modify(s, select.POLLIN | select.POLLOUT) # Link task to this IOQueue so it can be removed if needed cur_task.data = self def _dequeue(self, s): del self.map[id(s)] self.poller.unregister(s) def queue_read(self, s): self._enqueue(s, 0) def queue_write(self, s): self._enqueue(s, 1) def remove(self, task): while True: del_s = None for k in self.map: # Iterate without allocating on the heap q0, q1, s = self.map[k] if q0 is task or q1 is task: del_s = s break if del_s is not None: self._dequeue(s) else: break def wait_io_event(self, dt): for s, ev in self.poller.ipoll(dt): sm = self.map[id(s)] # print('poll', s, sm, ev) if ev & ~select.POLLOUT and sm[0] is not None: # POLLIN or error _task_queue.push_head(sm[0]) sm[0] = None if ev & ~select.POLLIN and sm[1] is not None: # POLLOUT or error _task_queue.push_head(sm[1]) sm[1] = None if sm[0] is None and sm[1] is None: self._dequeue(s) elif sm[0] is None: self.poller.modify(s, select.POLLOUT) else: self.poller.modify(s, select.POLLIN) ################################################################################ # Main run loop # Ensure the awaitable is a task def _promote_to_task(aw): return aw if isinstance(aw, Task) else create_task(aw) # Create and schedule a new task from a coroutine def create_task(coro): if not hasattr(coro, "send"): raise TypeError("coroutine expected") t = Task(coro, globals()) _task_queue.push_head(t) return t # Keep scheduling tasks until there are none left to schedule def run_until_complete(main_task=None): global cur_task excs_all = (CancelledError, Exception) # To prevent heap allocation in loop excs_stop = (CancelledError, StopIteration) # To prevent heap allocation in loop while True: # Wait until the head of _task_queue is ready to run dt = 1 while dt > 0: dt = -1 t = _task_queue.peek() if t: # A task waiting on _task_queue; "ph_key" is time to schedule task at dt = max(0, ticks_diff(t.ph_key, ticks())) elif not _io_queue.map: # No tasks can be woken so finished running return # print('(poll {})'.format(dt), len(_io_queue.map)) _io_queue.wait_io_event(dt) # Get next task to run and continue it t = _task_queue.pop_head() cur_task = t try: # Continue running the coroutine, it's responsible for rescheduling itself exc = t.data if not exc: t.coro.send(None) else: # If the task is finished and on the run queue and gets here, then it # had an exception and was not await'ed on. Throwing into it now will # raise StopIteration and the code below will catch this and run the # call_exception_handler function. t.data = None t.coro.throw(exc) except excs_all as er: # Check the task is not on any event queue assert t.data is None # This task is done, check if it's the main task and then loop should stop if t is main_task: if isinstance(er, StopIteration): return er.value raise er if t.state: # Task was running but is now finished. waiting = False if t.state is True: # "None" indicates that the task is complete and not await'ed on (yet). t.state = None else: # Schedule any other tasks waiting on the completion of this task. while t.state.peek(): _task_queue.push_head(t.state.pop_head()) waiting = True # "False" indicates that the task is complete and has been await'ed on. t.state = False if not waiting and not isinstance(er, excs_stop): # An exception ended this detached task, so queue it for later # execution to handle the uncaught exception if no other task retrieves # the exception in the meantime (this is handled by Task.throw). _task_queue.push_head(t) # Save return value of coro to pass up to caller. t.data = er elif t.state is None: # Task is already finished and nothing await'ed on the task, # so call the exception handler. _exc_context["exception"] = exc _exc_context["future"] = t Loop.call_exception_handler(_exc_context) # Create a new task from a coroutine and run it until it finishes def run(coro): return run_until_complete(create_task(coro)) ################################################################################ # Event loop wrapper async def _stopper(): pass _stop_task = None class Loop: _exc_handler = None def create_task(coro): return create_task(coro) def run_forever(): global _stop_task _stop_task = Task(_stopper(), globals()) run_until_complete(_stop_task) # TODO should keep running until .stop() is called, even if there're no tasks left def run_until_complete(aw): return run_until_complete(_promote_to_task(aw)) def stop(): global _stop_task if _stop_task is not None: _task_queue.push_head(_stop_task) # If stop() is called again, do nothing _stop_task = None def close(): pass def set_exception_handler(handler): Loop._exc_handler = handler def get_exception_handler(): return Loop._exc_handler def default_exception_handler(loop, context): print(context["message"]) print("future:", context["future"], "coro=", context["future"].coro) sys.print_exception(context["exception"]) def call_exception_handler(context): (Loop._exc_handler or Loop.default_exception_handler)(Loop, context) # The runq_len and waitq_len arguments are for legacy uasyncio compatibility def get_event_loop(runq_len=0, waitq_len=0): return Loop def current_task(): return cur_task def new_event_loop(): global _task_queue, _io_queue # TaskQueue of Task instances _task_queue = TaskQueue() # Task queue and poller for stream IO _io_queue = IOQueue() return Loop # Initialise default event loop new_event_loop()
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/core.py
Python
apache-2.0
9,399
# MicroPython uasyncio module # MIT license; Copyright (c) 2019-2020 Damien P. George from . import core # Event class for primitive events that can be waited on, set, and cleared class Event: def __init__(self): self.state = False # False=unset; True=set self.waiting = core.TaskQueue() # Queue of Tasks waiting on completion of this event def is_set(self): return self.state def set(self): # Event becomes set, schedule any tasks waiting on it # Note: This must not be called from anything except the thread running # the asyncio loop (i.e. neither hard or soft IRQ, or a different thread). while self.waiting.peek(): core._task_queue.push_head(self.waiting.pop_head()) self.state = True def clear(self): self.state = False async def wait(self): if not self.state: # Event not set, put the calling task on the event's waiting queue self.waiting.push_head(core.cur_task) # Set calling task's data to the event's queue so it can be removed if needed core.cur_task.data = self.waiting yield return True # MicroPython-extension: This can be set from outside the asyncio event loop, # such as other threads, IRQs or scheduler context. Implementation is a stream # that asyncio will poll until a flag is set. # Note: Unlike Event, this is self-clearing. try: import uio class ThreadSafeFlag(uio.IOBase): def __init__(self): self._flag = 0 def ioctl(self, req, flags): if req == 3: # MP_STREAM_POLL return self._flag * flags return None def set(self): self._flag = 1 async def wait(self): if not self._flag: yield core._io_queue.queue_read(self) self._flag = 0 except ImportError: pass
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/event.py
Python
apache-2.0
1,926
# MicroPython uasyncio module # MIT license; Copyright (c) 2019-2020 Damien P. George from . import core async def wait_for(aw, timeout, sleep=core.sleep): aw = core._promote_to_task(aw) if timeout is None: return await aw def runner(waiter, aw): nonlocal status, result try: result = await aw s = True except BaseException as er: s = er if status is None: # The waiter is still waiting, set status for it and cancel it. status = s waiter.cancel() # Run aw in a separate runner task that manages its exceptions. status = None result = None runner_task = core.create_task(runner(core.cur_task, aw)) try: # Wait for the timeout to elapse. await sleep(timeout) except core.CancelledError as er: if status is True: # aw completed successfully and cancelled the sleep, so return aw's result. return result elif status is None: # This wait_for was cancelled externally, so cancel aw and re-raise. status = True runner_task.cancel() raise er else: # aw raised an exception, propagate it out to the caller. raise status # The sleep finished before aw, so cancel aw and raise TimeoutError. status = True runner_task.cancel() await runner_task raise core.TimeoutError def wait_for_ms(aw, timeout): return wait_for(aw, timeout, core.sleep_ms) async def gather(*aws, return_exceptions=False): ts = [core._promote_to_task(aw) for aw in aws] for i in range(len(ts)): try: # TODO handle cancel of gather itself # if ts[i].coro: # iter(ts[i]).waiting.push_head(cur_task) # try: # yield # except CancelledError as er: # # cancel all waiting tasks # raise er ts[i] = await ts[i] except Exception as er: if return_exceptions: ts[i] = er else: raise er return ts
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/funcs.py
Python
apache-2.0
2,184
# MicroPython uasyncio module # MIT license; Copyright (c) 2019-2020 Damien P. George from . import core # Lock class for primitive mutex capability class Lock: def __init__(self): # The state can take the following values: # - 0: unlocked # - 1: locked # - <Task>: unlocked but this task has been scheduled to acquire the lock next self.state = 0 # Queue of Tasks waiting to acquire this Lock self.waiting = core.TaskQueue() def locked(self): return self.state == 1 def release(self): if self.state != 1: raise RuntimeError("Lock not acquired") if self.waiting.peek(): # Task(s) waiting on lock, schedule next Task self.state = self.waiting.pop_head() core._task_queue.push_head(self.state) else: # No Task waiting so unlock self.state = 0 async def acquire(self): if self.state != 0: # Lock unavailable, put the calling Task on the waiting queue self.waiting.push_head(core.cur_task) # Set calling task's data to the lock's queue so it can be removed if needed core.cur_task.data = self.waiting try: yield except core.CancelledError as er: if self.state == core.cur_task: # Cancelled while pending on resume, schedule next waiting Task self.state = 1 self.release() raise er # Lock available, set it as locked self.state = 1 return True async def __aenter__(self): return await self.acquire() async def __aexit__(self, exc_type, exc, tb): return self.release()
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/lock.py
Python
apache-2.0
1,782
# This list of frozen files doesn't include task.py because that's provided by the C module. freeze( "..", ( "uasyncio/__init__.py", "uasyncio/core.py", "uasyncio/event.py", "uasyncio/funcs.py", "uasyncio/lock.py", "uasyncio/stream.py", ), opt=3, )
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/manifest.py
Python
apache-2.0
313
# MicroPython uasyncio module # MIT license; Copyright (c) 2019-2020 Damien P. George from . import core class Stream: def __init__(self, s, e={}): self.s = s self.e = e self.out_buf = b"" def get_extra_info(self, v): return self.e[v] async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): await self.close() def close(self): pass async def wait_closed(self): # TODO yield? self.s.close() async def read(self, n): yield core._io_queue.queue_read(self.s) return self.s.read(n) async def readinto(self, buf): yield core._io_queue.queue_read(self.s) return self.s.readinto(buf) async def readexactly(self, n): r = b"" while n: yield core._io_queue.queue_read(self.s) r2 = self.s.read(n) if r2 is not None: if not len(r2): raise EOFError r += r2 n -= len(r2) return r async def readline(self): l = b"" while True: yield core._io_queue.queue_read(self.s) l2 = self.s.readline() # may do multiple reads but won't block l += l2 if not l2 or l[-1] == 10: # \n (check l in case l2 is str) return l def write(self, buf): self.out_buf += buf async def drain(self): mv = memoryview(self.out_buf) off = 0 while off < len(mv): yield core._io_queue.queue_write(self.s) ret = self.s.write(mv[off:]) if ret is not None: off += ret self.out_buf = b"" # Stream can be used for both reading and writing to save code size StreamReader = Stream StreamWriter = Stream # Create a TCP stream connection to a remote host async def open_connection(host, port): from uerrno import EINPROGRESS import usocket as socket ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)[0] # TODO this is blocking! s = socket.socket(ai[0], ai[1], ai[2]) s.setblocking(False) ss = Stream(s) try: s.connect(ai[-1]) except OSError as er: if er.errno != EINPROGRESS: raise er yield core._io_queue.queue_write(s) return ss, ss # Class representing a TCP stream server, can be closed and used in "async with" class Server: async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): self.close() await self.wait_closed() def close(self): self.task.cancel() async def wait_closed(self): await self.task async def _serve(self, s, cb): # Accept incoming connections while True: try: yield core._io_queue.queue_read(s) except core.CancelledError: # Shutdown server s.close() return try: s2, addr = s.accept() except: # Ignore a failed accept continue s2.setblocking(False) s2s = Stream(s2, {"peername": addr}) core.create_task(cb(s2s, s2s)) # Helper function to start a TCP stream server, running as a new task # TODO could use an accept-callback on socket read activity instead of creating a task async def start_server(cb, host, port, backlog=5): import usocket as socket # Create and bind server socket. host = socket.getaddrinfo(host, port)[0] # TODO this is blocking! s = socket.socket() s.setblocking(False) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(host[-1]) s.listen(backlog) # Create and return server object and task. srv = Server() srv.task = core.create_task(srv._serve(s, cb)) return srv ################################################################################ # Legacy uasyncio compatibility async def stream_awrite(self, buf, off=0, sz=-1): if off != 0 or sz != -1: buf = memoryview(buf) if sz == -1: sz = len(buf) buf = buf[off : off + sz] self.write(buf) await self.drain() Stream.aclose = Stream.wait_closed Stream.awrite = stream_awrite Stream.awritestr = stream_awrite # TODO explicitly convert to bytes?
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/stream.py
Python
apache-2.0
4,391
# MicroPython uasyncio module # MIT license; Copyright (c) 2019-2020 Damien P. George # This file contains the core TaskQueue based on a pairing heap, and the core Task class. # They can optionally be replaced by C implementations. from . import core # pairing-heap meld of 2 heaps; O(1) def ph_meld(h1, h2): if h1 is None: return h2 if h2 is None: return h1 lt = core.ticks_diff(h1.ph_key, h2.ph_key) < 0 if lt: if h1.ph_child is None: h1.ph_child = h2 else: h1.ph_child_last.ph_next = h2 h1.ph_child_last = h2 h2.ph_next = None h2.ph_rightmost_parent = h1 return h1 else: h1.ph_next = h2.ph_child h2.ph_child = h1 if h1.ph_next is None: h2.ph_child_last = h1 h1.ph_rightmost_parent = h2 return h2 # pairing-heap pairing operation; amortised O(log N) def ph_pairing(child): heap = None while child is not None: n1 = child child = child.ph_next n1.ph_next = None if child is not None: n2 = child child = child.ph_next n2.ph_next = None n1 = ph_meld(n1, n2) heap = ph_meld(heap, n1) return heap # pairing-heap delete of a node; stable, amortised O(log N) def ph_delete(heap, node): if node is heap: child = heap.ph_child node.ph_child = None return ph_pairing(child) # Find parent of node parent = node while parent.ph_next is not None: parent = parent.ph_next parent = parent.ph_rightmost_parent # Replace node with pairing of its children if node is parent.ph_child and node.ph_child is None: parent.ph_child = node.ph_next node.ph_next = None return heap elif node is parent.ph_child: child = node.ph_child next = node.ph_next node.ph_child = None node.ph_next = None node = ph_pairing(child) parent.ph_child = node else: n = parent.ph_child while node is not n.ph_next: n = n.ph_next child = node.ph_child next = node.ph_next node.ph_child = None node.ph_next = None node = ph_pairing(child) if node is None: node = n else: n.ph_next = node node.ph_next = next if next is None: node.ph_rightmost_parent = parent parent.ph_child_last = node return heap # TaskQueue class based on the above pairing-heap functions. class TaskQueue: def __init__(self): self.heap = None def peek(self): return self.heap def push_sorted(self, v, key): v.data = None v.ph_key = key v.ph_child = None v.ph_next = None self.heap = ph_meld(v, self.heap) def push_head(self, v): self.push_sorted(v, core.ticks()) def pop_head(self): v = self.heap self.heap = ph_pairing(self.heap.ph_child) return v def remove(self, v): self.heap = ph_delete(self.heap, v) # Task class representing a coroutine, can be waited on and cancelled. class Task: def __init__(self, coro, globals=None): self.coro = coro # Coroutine of this Task self.data = None # General data for queue it is waiting on self.state = True # None, False, True or a TaskQueue instance self.ph_key = 0 # Pairing heap self.ph_child = None # Paring heap self.ph_child_last = None # Paring heap self.ph_next = None # Paring heap self.ph_rightmost_parent = None # Paring heap def __iter__(self): if not self.state: # Task finished, signal that is has been await'ed on. self.state = False elif self.state is True: # Allocated head of linked list of Tasks waiting on completion of this task. self.state = TaskQueue() return self def __next__(self): if not self.state: # Task finished, raise return value to caller so it can continue. raise self.data else: # Put calling task on waiting queue. self.state.push_head(core.cur_task) # Set calling task's data to this task that it waits on, to double-link it. core.cur_task.data = self def done(self): return not self.state def cancel(self): # Check if task is already finished. if not self.state: return False # Can't cancel self (not supported yet). if self is core.cur_task: raise RuntimeError("can't cancel self") # If Task waits on another task then forward the cancel to the one it's waiting on. while isinstance(self.data, Task): self = self.data # Reschedule Task as a cancelled task. if hasattr(self.data, "remove"): # Not on the main running queue, remove the task from the queue it's on. self.data.remove(self) core._task_queue.push_head(self) elif core.ticks_diff(self.ph_key, core.ticks()) > 0: # On the main running queue but scheduled in the future, so bring it forward to now. core._task_queue.remove(self) core._task_queue.push_head(self) self.data = core.CancelledError return True
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uasyncio/task.py
Python
apache-2.0
5,409
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * Copyright (c) 2017-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <string.h> #include "py/mpconfig.h" #include "py/runtime.h" #include "py/objtuple.h" #include "py/objarray.h" #include "py/stream.h" #include "extmod/misc.h" #include "shared/runtime/interrupt_char.h" #if MICROPY_PY_OS_DUPTERM void mp_uos_deactivate(size_t dupterm_idx, const char *msg, mp_obj_t exc) { mp_obj_t term = MP_STATE_VM(dupterm_objs[dupterm_idx]); MP_STATE_VM(dupterm_objs[dupterm_idx]) = MP_OBJ_NULL; mp_printf(&mp_plat_print, msg); if (exc != MP_OBJ_NULL) { mp_obj_print_exception(&mp_plat_print, exc); } nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_stream_close(term); nlr_pop(); } else { // Ignore any errors during stream closing } } uintptr_t mp_uos_dupterm_poll(uintptr_t poll_flags) { uintptr_t poll_flags_out = 0; for (size_t idx = 0; idx < MICROPY_PY_OS_DUPTERM; ++idx) { mp_obj_t s = MP_STATE_VM(dupterm_objs[idx]); if (s == MP_OBJ_NULL) { continue; } int errcode = 0; mp_uint_t ret = 0; const mp_stream_p_t *stream_p = mp_get_stream(s); #if MICROPY_PY_UOS_DUPTERM_BUILTIN_STREAM if (mp_uos_dupterm_is_builtin_stream(s)) { ret = stream_p->ioctl(s, MP_STREAM_POLL, poll_flags, &errcode); } else #endif { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { ret = stream_p->ioctl(s, MP_STREAM_POLL, poll_flags, &errcode); nlr_pop(); } else { // Ignore error with ioctl } } if (ret != MP_STREAM_ERROR) { poll_flags_out |= ret; if (poll_flags_out == poll_flags) { // Finish early if all requested flags are set break; } } } return poll_flags_out; } int mp_uos_dupterm_rx_chr(void) { for (size_t idx = 0; idx < MICROPY_PY_OS_DUPTERM; ++idx) { if (MP_STATE_VM(dupterm_objs[idx]) == MP_OBJ_NULL) { continue; } #if MICROPY_PY_UOS_DUPTERM_BUILTIN_STREAM if (mp_uos_dupterm_is_builtin_stream(MP_STATE_VM(dupterm_objs[idx]))) { byte buf[1]; int errcode = 0; const mp_stream_p_t *stream_p = mp_get_stream(MP_STATE_VM(dupterm_objs[idx])); mp_uint_t out_sz = stream_p->read(MP_STATE_VM(dupterm_objs[idx]), buf, 1, &errcode); if (errcode == 0 && out_sz != 0) { return buf[0]; } else { continue; } } #endif nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { byte buf[1]; int errcode; const mp_stream_p_t *stream_p = mp_get_stream(MP_STATE_VM(dupterm_objs[idx])); mp_uint_t out_sz = stream_p->read(MP_STATE_VM(dupterm_objs[idx]), buf, 1, &errcode); if (out_sz == 0) { nlr_pop(); mp_uos_deactivate(idx, "dupterm: EOF received, deactivating\n", MP_OBJ_NULL); } else if (out_sz == MP_STREAM_ERROR) { // errcode is valid if (mp_is_nonblocking_error(errcode)) { nlr_pop(); } else { mp_raise_OSError(errcode); } } else { // read 1 byte nlr_pop(); if (buf[0] == mp_interrupt_char) { // Signal keyboard interrupt to be raised as soon as the VM resumes mp_sched_keyboard_interrupt(); return -2; } return buf[0]; } } else { mp_uos_deactivate(idx, "dupterm: Exception in read() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } // No chars available return -1; } void mp_uos_dupterm_tx_strn(const char *str, size_t len) { for (size_t idx = 0; idx < MICROPY_PY_OS_DUPTERM; ++idx) { if (MP_STATE_VM(dupterm_objs[idx]) == MP_OBJ_NULL) { continue; } #if MICROPY_PY_UOS_DUPTERM_BUILTIN_STREAM if (mp_uos_dupterm_is_builtin_stream(MP_STATE_VM(dupterm_objs[idx]))) { int errcode = 0; const mp_stream_p_t *stream_p = mp_get_stream(MP_STATE_VM(dupterm_objs[idx])); stream_p->write(MP_STATE_VM(dupterm_objs[idx]), str, len, &errcode); continue; } #endif nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_stream_write(MP_STATE_VM(dupterm_objs[idx]), str, len, MP_STREAM_RW_WRITE); nlr_pop(); } else { mp_uos_deactivate(idx, "dupterm: Exception in write() method, deactivating: ", MP_OBJ_FROM_PTR(nlr.ret_val)); } } } STATIC mp_obj_t mp_uos_dupterm(size_t n_args, const mp_obj_t *args) { mp_int_t idx = 0; if (n_args == 2) { idx = mp_obj_get_int(args[1]); } if (idx < 0 || idx >= MICROPY_PY_OS_DUPTERM) { mp_raise_ValueError(MP_ERROR_TEXT("invalid dupterm index")); } mp_obj_t previous_obj = MP_STATE_VM(dupterm_objs[idx]); if (previous_obj == MP_OBJ_NULL) { previous_obj = mp_const_none; } if (args[0] == mp_const_none) { MP_STATE_VM(dupterm_objs[idx]) = MP_OBJ_NULL; } else { mp_get_stream_raise(args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); MP_STATE_VM(dupterm_objs[idx]) = args[0]; } return previous_obj; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_uos_dupterm_obj, 1, 2, mp_uos_dupterm); #endif
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/uos_dupterm.c
C
apache-2.0
6,859
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013-2016 Damien P. George * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_PY_UTIME_MP_HAL #include <string.h> #include "py/obj.h" #include "py/mphal.h" #include "py/smallint.h" #include "py/runtime.h" #include "extmod/utime_mphal.h" STATIC mp_obj_t time_sleep(mp_obj_t seconds_o) { #if MICROPY_PY_BUILTINS_FLOAT mp_hal_delay_ms((mp_uint_t)(1000 * mp_obj_get_float(seconds_o))); #else mp_hal_delay_ms(1000 * mp_obj_get_int(seconds_o)); #endif return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_utime_sleep_obj, time_sleep); STATIC mp_obj_t time_sleep_ms(mp_obj_t arg) { mp_int_t ms = mp_obj_get_int(arg); if (ms >= 0) { mp_hal_delay_ms(ms); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_utime_sleep_ms_obj, time_sleep_ms); STATIC mp_obj_t time_sleep_us(mp_obj_t arg) { mp_int_t us = mp_obj_get_int(arg); if (us > 0) { mp_hal_delay_us(us); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_utime_sleep_us_obj, time_sleep_us); STATIC mp_obj_t time_ticks_ms(void) { return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_ms() & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)); } MP_DEFINE_CONST_FUN_OBJ_0(mp_utime_ticks_ms_obj, time_ticks_ms); STATIC mp_obj_t time_ticks_us(void) { return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_us() & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)); } MP_DEFINE_CONST_FUN_OBJ_0(mp_utime_ticks_us_obj, time_ticks_us); STATIC mp_obj_t time_ticks_cpu(void) { return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_cpu() & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)); } MP_DEFINE_CONST_FUN_OBJ_0(mp_utime_ticks_cpu_obj, time_ticks_cpu); STATIC mp_obj_t time_ticks_diff(mp_obj_t end_in, mp_obj_t start_in) { // we assume that the arguments come from ticks_xx so are small ints mp_uint_t start = MP_OBJ_SMALL_INT_VALUE(start_in); mp_uint_t end = MP_OBJ_SMALL_INT_VALUE(end_in); // Optimized formula avoiding if conditions. We adjust difference "forward", // wrap it around and adjust back. mp_int_t diff = ((end - start + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)) - MICROPY_PY_UTIME_TICKS_PERIOD / 2; return MP_OBJ_NEW_SMALL_INT(diff); } MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff); STATIC mp_obj_t time_ticks_add(mp_obj_t ticks_in, mp_obj_t delta_in) { // we assume that first argument come from ticks_xx so is small int mp_uint_t ticks = MP_OBJ_SMALL_INT_VALUE(ticks_in); mp_uint_t delta = mp_obj_get_int(delta_in); return MP_OBJ_NEW_SMALL_INT((ticks + delta) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)); } MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_add_obj, time_ticks_add); // Returns the number of nanoseconds since the Epoch, as an integer. STATIC mp_obj_t time_time_ns(void) { return mp_obj_new_int_from_ull(mp_hal_time_ns()); } MP_DEFINE_CONST_FUN_OBJ_0(mp_utime_time_ns_obj, time_time_ns); #endif // MICROPY_PY_UTIME_MP_HAL
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/utime_mphal.c
C
apache-2.0
4,144
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013-2016 Damien P. George * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H #define MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H #include "py/obj.h" MP_DECLARE_CONST_FUN_OBJ_1(mp_utime_sleep_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_utime_sleep_ms_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_utime_sleep_us_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_ms_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_us_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_ticks_cpu_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_utime_ticks_add_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_utime_time_ns_obj); #endif // MICROPY_INCLUDED_EXTMOD_UTIME_MPHAL_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/utime_mphal.h
C
apache-2.0
1,890
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdint.h> #include <string.h> #include "py/runtime.h" #include "py/objstr.h" #include "py/mperrno.h" #include "extmod/vfs.h" #if MICROPY_VFS #if MICROPY_VFS_FAT #include "extmod/vfs_fat.h" #endif #if MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2 #include "extmod/vfs_lfs.h" #endif #if MICROPY_VFS_POSIX #include "extmod/vfs_posix.h" #endif // For mp_vfs_proxy_call, the maximum number of additional args that can be passed. // A fixed maximum size is used to avoid the need for a costly variable array. #define PROXY_MAX_ARGS (2) // path is the path to lookup and *path_out holds the path within the VFS // object (starts with / if an absolute path). // Returns MP_VFS_ROOT for root dir (and then path_out is undefined) and // MP_VFS_NONE for path not found. mp_vfs_mount_t *mp_vfs_lookup_path(const char *path, const char **path_out) { if (*path == '/' || MP_STATE_VM(vfs_cur) == MP_VFS_ROOT) { // an absolute path, or the current volume is root, so search root dir bool is_abs = 0; if (*path == '/') { ++path; is_abs = 1; } if (*path == '\0') { // path is "" or "/" so return virtual root return MP_VFS_ROOT; } for (mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) { size_t len = vfs->len - 1; if (len == 0) { *path_out = path - is_abs; return vfs; } if (strncmp(path, vfs->str + 1, len) == 0) { if (path[len] == '/') { *path_out = path + len; return vfs; } else if (path[len] == '\0') { *path_out = "/"; return vfs; } } } // if we get here then there's nothing mounted on /, so the path doesn't exist return MP_VFS_NONE; } // a relative path within a mounted device *path_out = path; return MP_STATE_VM(vfs_cur); } // Version of mp_vfs_lookup_path that takes and returns uPy string objects. STATIC mp_vfs_mount_t *lookup_path(mp_obj_t path_in, mp_obj_t *path_out) { const char *path = mp_obj_str_get_str(path_in); const char *p_out; mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out); if (vfs != MP_VFS_NONE && vfs != MP_VFS_ROOT) { *path_out = mp_obj_new_str_of_type(mp_obj_get_type(path_in), (const byte *)p_out, strlen(p_out)); } return vfs; } STATIC mp_obj_t mp_vfs_proxy_call(mp_vfs_mount_t *vfs, qstr meth_name, size_t n_args, const mp_obj_t *args) { assert(n_args <= PROXY_MAX_ARGS); if (vfs == MP_VFS_NONE) { // mount point not found mp_raise_OSError(MP_ENODEV); } if (vfs == MP_VFS_ROOT) { // can't do operation on root dir mp_raise_OSError(MP_EPERM); } mp_obj_t meth[2 + PROXY_MAX_ARGS]; mp_load_method(vfs->obj, meth_name, meth); if (args != NULL) { memcpy(meth + 2, args, n_args * sizeof(*args)); } return mp_call_method_n_kw(n_args, 0, meth); } mp_import_stat_t mp_vfs_import_stat(const char *path) { const char *path_out; mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &path_out); if (vfs == MP_VFS_NONE || vfs == MP_VFS_ROOT) { return MP_IMPORT_STAT_NO_EXIST; } // If the mounted object has the VFS protocol, call its import_stat helper const mp_vfs_proto_t *proto = mp_obj_get_type(vfs->obj)->protocol; if (proto != NULL) { return proto->import_stat(MP_OBJ_TO_PTR(vfs->obj), path_out); } // delegate to vfs.stat() method mp_obj_t path_o = mp_obj_new_str(path_out, strlen(path_out)); mp_obj_t stat; nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { stat = mp_vfs_proxy_call(vfs, MP_QSTR_stat, 1, &path_o); nlr_pop(); } else { // assume an exception means that the path is not found return MP_IMPORT_STAT_NO_EXIST; } mp_obj_t *items; mp_obj_get_array_fixed_n(stat, 10, &items); mp_int_t st_mode = mp_obj_get_int(items[0]); if (st_mode & MP_S_IFDIR) { return MP_IMPORT_STAT_DIR; } else { return MP_IMPORT_STAT_FILE; } } STATIC mp_obj_t mp_vfs_autodetect(mp_obj_t bdev_obj) { #if MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2 nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { // The superblock for littlefs is in both block 0 and 1, but block 0 may be erased // or partially written, so search both blocks 0 and 1 for the littlefs signature. mp_vfs_blockdev_t blockdev; mp_vfs_blockdev_init(&blockdev, bdev_obj); uint8_t buf[44]; for (size_t block_num = 0; block_num <= 1; ++block_num) { mp_vfs_blockdev_read_ext(&blockdev, block_num, 8, sizeof(buf), buf); #if MICROPY_VFS_LFS1 if (memcmp(&buf[32], "littlefs", 8) == 0) { // LFS1 mp_obj_t vfs = mp_type_vfs_lfs1.make_new(&mp_type_vfs_lfs1, 1, 0, &bdev_obj); nlr_pop(); return vfs; } #endif #if MICROPY_VFS_LFS2 if (memcmp(&buf[0], "littlefs", 8) == 0) { // LFS2 mp_obj_t vfs = mp_type_vfs_lfs2.make_new(&mp_type_vfs_lfs2, 1, 0, &bdev_obj); nlr_pop(); return vfs; } #endif } nlr_pop(); } else { // Ignore exception (eg block device doesn't support extended readblocks) } #endif #if MICROPY_VFS_FAT return mp_fat_vfs_type.make_new(&mp_fat_vfs_type, 1, 0, &bdev_obj); #endif // no filesystem found mp_raise_OSError(MP_ENODEV); } mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_readonly, ARG_mkfs }; static const mp_arg_t allowed_args[] = { { MP_QSTR_readonly, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_FALSE} }, { MP_QSTR_mkfs, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_FALSE} }, }; // parse args mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // get the mount point size_t mnt_len; const char *mnt_str = mp_obj_str_get_data(pos_args[1], &mnt_len); // see if we need to auto-detect and create the filesystem mp_obj_t vfs_obj = pos_args[0]; mp_obj_t dest[2]; mp_load_method_maybe(vfs_obj, MP_QSTR_mount, dest); if (dest[0] == MP_OBJ_NULL) { // Input object has no mount method, assume it's a block device and try to // auto-detect the filesystem and create the corresponding VFS entity. vfs_obj = mp_vfs_autodetect(vfs_obj); } // create new object mp_vfs_mount_t *vfs = m_new_obj(mp_vfs_mount_t); vfs->str = mnt_str; vfs->len = mnt_len; vfs->obj = vfs_obj; vfs->next = NULL; // call the underlying object to do any mounting operation mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args); // check that the destination mount point is unused const char *path_out; mp_vfs_mount_t *existing_mount = mp_vfs_lookup_path(mp_obj_str_get_str(pos_args[1]), &path_out); if (existing_mount != MP_VFS_NONE && existing_mount != MP_VFS_ROOT) { if (vfs->len != 1 && existing_mount->len == 1) { // if root dir is mounted, still allow to mount something within a subdir of root } else { // mount point in use mp_raise_OSError(MP_EPERM); } } // insert the vfs into the mount table mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); while (*vfsp != NULL) { if ((*vfsp)->len == 1) { // make sure anything mounted at the root stays at the end of the list vfs->next = *vfsp; break; } vfsp = &(*vfsp)->next; } *vfsp = vfs; return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_mount_obj, 2, mp_vfs_mount); mp_obj_t mp_vfs_umount(mp_obj_t mnt_in) { // remove vfs from the mount table mp_vfs_mount_t *vfs = NULL; size_t mnt_len; const char *mnt_str = NULL; if (mp_obj_is_str(mnt_in)) { mnt_str = mp_obj_str_get_data(mnt_in, &mnt_len); } for (mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); *vfsp != NULL; vfsp = &(*vfsp)->next) { if ((mnt_str != NULL && !memcmp(mnt_str, (*vfsp)->str, mnt_len + 1)) || (*vfsp)->obj == mnt_in) { vfs = *vfsp; *vfsp = (*vfsp)->next; break; } } if (vfs == NULL) { mp_raise_OSError(MP_EINVAL); } // if we unmounted the current device then set current to root if (MP_STATE_VM(vfs_cur) == vfs) { MP_STATE_VM(vfs_cur) = MP_VFS_ROOT; } // call the underlying object to do any unmounting operation mp_vfs_proxy_call(vfs, MP_QSTR_umount, 0, NULL); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_umount_obj, mp_vfs_umount); // Note: buffering and encoding args are currently ignored mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_file, ARG_mode, ARG_encoding }; static const mp_arg_t allowed_args[] = { { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_mode, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_QSTR(MP_QSTR_r)} }, { MP_QSTR_buffering, MP_ARG_INT, {.u_int = -1} }, { MP_QSTR_encoding, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, }; // parse args mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); #if MICROPY_VFS_POSIX // If the file is an integer then delegate straight to the POSIX handler if (mp_obj_is_small_int(args[ARG_file].u_obj)) { return mp_vfs_posix_file_open(&mp_type_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj); } #endif mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj); return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); } MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_open_obj, 0, mp_vfs_open); mp_obj_t mp_vfs_chdir(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); if (vfs == MP_VFS_ROOT) { // If we change to the root dir and a VFS is mounted at the root then // we must change that VFS's current dir to the root dir so that any // subsequent relative paths begin at the root of that VFS. for (vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) { if (vfs->len == 1) { mp_obj_t root = MP_OBJ_NEW_QSTR(MP_QSTR__slash_); mp_vfs_proxy_call(vfs, MP_QSTR_chdir, 1, &root); break; } } vfs = MP_VFS_ROOT; } else { mp_vfs_proxy_call(vfs, MP_QSTR_chdir, 1, &path_out); } MP_STATE_VM(vfs_cur) = vfs; return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_chdir_obj, mp_vfs_chdir); mp_obj_t mp_vfs_getcwd(void) { if (MP_STATE_VM(vfs_cur) == MP_VFS_ROOT) { return MP_OBJ_NEW_QSTR(MP_QSTR__slash_); } mp_obj_t cwd_o = mp_vfs_proxy_call(MP_STATE_VM(vfs_cur), MP_QSTR_getcwd, 0, NULL); if (MP_STATE_VM(vfs_cur)->len == 1) { // don't prepend "/" for vfs mounted at root return cwd_o; } const char *cwd = mp_obj_str_get_str(cwd_o); vstr_t vstr; vstr_init(&vstr, MP_STATE_VM(vfs_cur)->len + strlen(cwd) + 1); vstr_add_strn(&vstr, MP_STATE_VM(vfs_cur)->str, MP_STATE_VM(vfs_cur)->len); if (!(cwd[0] == '/' && cwd[1] == 0)) { vstr_add_str(&vstr, cwd); } return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); } MP_DEFINE_CONST_FUN_OBJ_0(mp_vfs_getcwd_obj, mp_vfs_getcwd); typedef struct _mp_vfs_ilistdir_it_t { mp_obj_base_t base; mp_fun_1_t iternext; union { mp_vfs_mount_t *vfs; mp_obj_t iter; } cur; bool is_str; bool is_iter; } mp_vfs_ilistdir_it_t; STATIC mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in) { mp_vfs_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); if (self->is_iter) { // continue delegating to root dir return mp_iternext(self->cur.iter); } else if (self->cur.vfs == NULL) { // finished iterating mount points and no root dir is mounted return MP_OBJ_STOP_ITERATION; } else { // continue iterating mount points mp_vfs_mount_t *vfs = self->cur.vfs; self->cur.vfs = vfs->next; if (vfs->len == 1) { // vfs is mounted at root dir, delegate to it mp_obj_t root = MP_OBJ_NEW_QSTR(MP_QSTR__slash_); self->is_iter = true; self->cur.iter = mp_vfs_proxy_call(vfs, MP_QSTR_ilistdir, 1, &root); return mp_iternext(self->cur.iter); } else { // a mounted directory mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = mp_obj_new_str_of_type( self->is_str ? &mp_type_str : &mp_type_bytes, (const byte *)vfs->str + 1, vfs->len - 1); t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number return MP_OBJ_FROM_PTR(t); } } } mp_obj_t mp_vfs_ilistdir(size_t n_args, const mp_obj_t *args) { mp_obj_t path_in; if (n_args == 1) { path_in = args[0]; } else { path_in = MP_OBJ_NEW_QSTR(MP_QSTR_); } mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); if (vfs == MP_VFS_ROOT) { // list the root directory mp_vfs_ilistdir_it_t *iter = m_new_obj(mp_vfs_ilistdir_it_t); iter->base.type = &mp_type_polymorph_iter; iter->iternext = mp_vfs_ilistdir_it_iternext; iter->cur.vfs = MP_STATE_VM(vfs_mount_table); iter->is_str = mp_obj_get_type(path_in) == &mp_type_str; iter->is_iter = false; return MP_OBJ_FROM_PTR(iter); } return mp_vfs_proxy_call(vfs, MP_QSTR_ilistdir, 1, &path_out); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_ilistdir_obj, 0, 1, mp_vfs_ilistdir); mp_obj_t mp_vfs_listdir(size_t n_args, const mp_obj_t *args) { mp_obj_t iter = mp_vfs_ilistdir(n_args, args); mp_obj_t dir_list = mp_obj_new_list(0, NULL); mp_obj_t next; while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) { mp_obj_list_append(dir_list, mp_obj_subscr(next, MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_SENTINEL)); } return dir_list; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_listdir_obj, 0, 1, mp_vfs_listdir); mp_obj_t mp_vfs_mkdir(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); if (vfs == MP_VFS_ROOT || (vfs != MP_VFS_NONE && !strcmp(mp_obj_str_get_str(path_out), "/"))) { mp_raise_OSError(MP_EEXIST); } return mp_vfs_proxy_call(vfs, MP_QSTR_mkdir, 1, &path_out); } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_mkdir_obj, mp_vfs_mkdir); mp_obj_t mp_vfs_remove(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); return mp_vfs_proxy_call(vfs, MP_QSTR_remove, 1, &path_out); } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_remove_obj, mp_vfs_remove); mp_obj_t mp_vfs_rename(mp_obj_t old_path_in, mp_obj_t new_path_in) { mp_obj_t args[2]; mp_vfs_mount_t *old_vfs = lookup_path(old_path_in, &args[0]); mp_vfs_mount_t *new_vfs = lookup_path(new_path_in, &args[1]); if (old_vfs != new_vfs) { // can't rename across filesystems mp_raise_OSError(MP_EPERM); } return mp_vfs_proxy_call(old_vfs, MP_QSTR_rename, 2, args); } MP_DEFINE_CONST_FUN_OBJ_2(mp_vfs_rename_obj, mp_vfs_rename); mp_obj_t mp_vfs_rmdir(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); return mp_vfs_proxy_call(vfs, MP_QSTR_rmdir, 1, &path_out); } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_rmdir_obj, mp_vfs_rmdir); mp_obj_t mp_vfs_stat(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); if (vfs == MP_VFS_ROOT) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); // st_mode for (int i = 1; i <= 9; ++i) { t->items[i] = MP_OBJ_NEW_SMALL_INT(0); // dev, nlink, uid, gid, size, atime, mtime, ctime } return MP_OBJ_FROM_PTR(t); } return mp_vfs_proxy_call(vfs, MP_QSTR_stat, 1, &path_out); } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_stat_obj, mp_vfs_stat); mp_obj_t mp_vfs_statvfs(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); if (vfs == MP_VFS_ROOT) { // statvfs called on the root directory, see if there's anything mounted there for (vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) { if (vfs->len == 1) { break; } } // If there's nothing mounted at root then return a mostly-empty tuple if (vfs == NULL) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); // fill in: bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flags for (int i = 0; i <= 8; ++i) { t->items[i] = MP_OBJ_NEW_SMALL_INT(0); } // Put something sensible in f_namemax t->items[9] = MP_OBJ_NEW_SMALL_INT(MICROPY_ALLOC_PATH_MAX); return MP_OBJ_FROM_PTR(t); } // VFS mounted at root so delegate the call to it path_out = MP_OBJ_NEW_QSTR(MP_QSTR__slash_); } return mp_vfs_proxy_call(vfs, MP_QSTR_statvfs, 1, &path_out); } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_statvfs_obj, mp_vfs_statvfs); // This is a C-level helper function for ports to use if needed. int mp_vfs_mount_and_chdir_protected(mp_obj_t bdev, mp_obj_t mount_point) { nlr_buf_t nlr; mp_int_t ret = -MP_EIO; if (nlr_push(&nlr) == 0) { mp_obj_t args[] = { bdev, mount_point }; mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map); mp_vfs_chdir(mount_point); ret = 0; // success nlr_pop(); } else { mp_obj_base_t *exc = nlr.ret_val; if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_OSError))) { mp_obj_t v = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(exc)); mp_obj_get_int_maybe(v, &ret); // get errno value ret = -ret; } } return ret; } #endif // MICROPY_VFS
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs.c
C
apache-2.0
19,964
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_VFS_H #define MICROPY_INCLUDED_EXTMOD_VFS_H #include "py/lexer.h" #include "py/obj.h" // return values of mp_vfs_lookup_path // ROOT is 0 so that the default current directory is the root directory #define MP_VFS_NONE ((mp_vfs_mount_t *)1) #define MP_VFS_ROOT ((mp_vfs_mount_t *)0) // MicroPython's port-standardized versions of stat constants #define MP_S_IFDIR (0x4000) #define MP_S_IFREG (0x8000) // these are the values for mp_vfs_blockdev_t.flags #define MP_BLOCKDEV_FLAG_NATIVE (0x0001) // readblocks[2]/writeblocks[2] contain native func #define MP_BLOCKDEV_FLAG_FREE_OBJ (0x0002) // fs_user_mount_t obj should be freed on umount #define MP_BLOCKDEV_FLAG_HAVE_IOCTL (0x0004) // new protocol with ioctl #define MP_BLOCKDEV_FLAG_NO_FILESYSTEM (0x0008) // the block device has no filesystem on it // constants for block protocol ioctl #define MP_BLOCKDEV_IOCTL_INIT (1) #define MP_BLOCKDEV_IOCTL_DEINIT (2) #define MP_BLOCKDEV_IOCTL_SYNC (3) #define MP_BLOCKDEV_IOCTL_BLOCK_COUNT (4) #define MP_BLOCKDEV_IOCTL_BLOCK_SIZE (5) #define MP_BLOCKDEV_IOCTL_BLOCK_ERASE (6) // At the moment the VFS protocol just has import_stat, but could be extended to other methods typedef struct _mp_vfs_proto_t { mp_import_stat_t (*import_stat)(void *self, const char *path); } mp_vfs_proto_t; typedef struct _mp_vfs_blockdev_t { uint16_t flags; size_t block_size; mp_obj_t readblocks[5]; mp_obj_t writeblocks[5]; // new protocol uses just ioctl, old uses sync (optional) and count union { mp_obj_t ioctl[4]; struct { mp_obj_t sync[2]; mp_obj_t count[2]; } old; } u; } mp_vfs_blockdev_t; typedef struct _mp_vfs_mount_t { const char *str; // mount point with leading / size_t len; mp_obj_t obj; struct _mp_vfs_mount_t *next; } mp_vfs_mount_t; void mp_vfs_blockdev_init(mp_vfs_blockdev_t *self, mp_obj_t bdev); int mp_vfs_blockdev_read(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, uint8_t *buf); int mp_vfs_blockdev_read_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, uint8_t *buf); int mp_vfs_blockdev_write(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, const uint8_t *buf); int mp_vfs_blockdev_write_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, const uint8_t *buf); mp_obj_t mp_vfs_blockdev_ioctl(mp_vfs_blockdev_t *self, uintptr_t cmd, uintptr_t arg); mp_vfs_mount_t *mp_vfs_lookup_path(const char *path, const char **path_out); mp_import_stat_t mp_vfs_import_stat(const char *path); mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); mp_obj_t mp_vfs_umount(mp_obj_t mnt_in); mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); mp_obj_t mp_vfs_chdir(mp_obj_t path_in); mp_obj_t mp_vfs_getcwd(void); mp_obj_t mp_vfs_ilistdir(size_t n_args, const mp_obj_t *args); mp_obj_t mp_vfs_listdir(size_t n_args, const mp_obj_t *args); mp_obj_t mp_vfs_mkdir(mp_obj_t path_in); mp_obj_t mp_vfs_remove(mp_obj_t path_in); mp_obj_t mp_vfs_rename(mp_obj_t old_path_in, mp_obj_t new_path_in); mp_obj_t mp_vfs_rmdir(mp_obj_t path_in); mp_obj_t mp_vfs_stat(mp_obj_t path_in); mp_obj_t mp_vfs_statvfs(mp_obj_t path_in); int mp_vfs_mount_and_chdir_protected(mp_obj_t bdev, mp_obj_t mount_point); MP_DECLARE_CONST_FUN_OBJ_KW(mp_vfs_mount_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_umount_obj); MP_DECLARE_CONST_FUN_OBJ_KW(mp_vfs_open_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_chdir_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_vfs_getcwd_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_ilistdir_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_listdir_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_mkdir_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_remove_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_vfs_rename_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_rmdir_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_stat_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_statvfs_obj); #endif // MICROPY_INCLUDED_EXTMOD_VFS_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs.h
C
apache-2.0
5,304
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013-2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/binary.h" #include "py/objarray.h" #include "py/mperrno.h" #include "extmod/vfs.h" #if MICROPY_VFS void mp_vfs_blockdev_init(mp_vfs_blockdev_t *self, mp_obj_t bdev) { mp_load_method(bdev, MP_QSTR_readblocks, self->readblocks); mp_load_method_maybe(bdev, MP_QSTR_writeblocks, self->writeblocks); mp_load_method_maybe(bdev, MP_QSTR_ioctl, self->u.ioctl); if (self->u.ioctl[0] != MP_OBJ_NULL) { // Device supports new block protocol, so indicate it self->flags |= MP_BLOCKDEV_FLAG_HAVE_IOCTL; } else { // No ioctl method, so assume the device uses the old block protocol mp_load_method_maybe(bdev, MP_QSTR_sync, self->u.old.sync); mp_load_method(bdev, MP_QSTR_count, self->u.old.count); } } int mp_vfs_blockdev_read(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, uint8_t *buf) { if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) { mp_uint_t (*f)(uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->readblocks[2]; return f(buf, block_num, num_blocks); } else { mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, buf}; self->readblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); self->readblocks[3] = MP_OBJ_FROM_PTR(&ar); mp_call_method_n_kw(2, 0, self->readblocks); // TODO handle error return return 0; } } int mp_vfs_blockdev_read_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, uint8_t *buf) { mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, buf}; self->readblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); self->readblocks[3] = MP_OBJ_FROM_PTR(&ar); self->readblocks[4] = MP_OBJ_NEW_SMALL_INT(block_off); mp_obj_t ret = mp_call_method_n_kw(3, 0, self->readblocks); if (ret == mp_const_none) { return 0; } else { return MP_OBJ_SMALL_INT_VALUE(ret); } } int mp_vfs_blockdev_write(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, const uint8_t *buf) { if (self->writeblocks[0] == MP_OBJ_NULL) { // read-only block device return -MP_EROFS; } if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) { mp_uint_t (*f)(const uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->writeblocks[2]; return f(buf, block_num, num_blocks); } else { mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, (void *)buf}; self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar); mp_call_method_n_kw(2, 0, self->writeblocks); // TODO handle error return return 0; } } int mp_vfs_blockdev_write_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, const uint8_t *buf) { if (self->writeblocks[0] == MP_OBJ_NULL) { // read-only block device return -MP_EROFS; } mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, (void *)buf}; self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar); self->writeblocks[4] = MP_OBJ_NEW_SMALL_INT(block_off); mp_obj_t ret = mp_call_method_n_kw(3, 0, self->writeblocks); if (ret == mp_const_none) { return 0; } else { return MP_OBJ_SMALL_INT_VALUE(ret); } } mp_obj_t mp_vfs_blockdev_ioctl(mp_vfs_blockdev_t *self, uintptr_t cmd, uintptr_t arg) { if (self->flags & MP_BLOCKDEV_FLAG_HAVE_IOCTL) { // New protocol with ioctl self->u.ioctl[2] = MP_OBJ_NEW_SMALL_INT(cmd); self->u.ioctl[3] = MP_OBJ_NEW_SMALL_INT(arg); return mp_call_method_n_kw(2, 0, self->u.ioctl); } else { // Old protocol with sync and count switch (cmd) { case MP_BLOCKDEV_IOCTL_SYNC: if (self->u.old.sync[0] != MP_OBJ_NULL) { mp_call_method_n_kw(0, 0, self->u.old.sync); } break; case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: return mp_call_method_n_kw(0, 0, self->u.old.count); case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: // Old protocol has fixed sector size of 512 bytes break; case MP_BLOCKDEV_IOCTL_INIT: // Old protocol doesn't have init break; } return mp_const_none; } } #endif // MICROPY_VFS
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_blockdev.c
C
apache-2.0
5,749
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2014 Damien P. George * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_VFS_FAT #if !MICROPY_VFS #error "with MICROPY_VFS_FAT enabled, must also enable MICROPY_VFS" #endif #include <string.h> #include "py/runtime.h" #include "py/mperrno.h" #include "lib/oofatfs/ff.h" #include "extmod/vfs_fat.h" #include "shared/timeutils/timeutils.h" #if FF_MAX_SS == FF_MIN_SS #define SECSIZE(fs) (FF_MIN_SS) #else #define SECSIZE(fs) ((fs)->ssize) #endif #define mp_obj_fat_vfs_t fs_user_mount_t STATIC mp_import_stat_t fat_vfs_import_stat(void *vfs_in, const char *path) { fs_user_mount_t *vfs = vfs_in; FILINFO fno; assert(vfs != NULL); FRESULT res = f_stat(&vfs->fatfs, path, &fno); if (res == FR_OK) { if ((fno.fattrib & AM_DIR) != 0) { return MP_IMPORT_STAT_DIR; } else { return MP_IMPORT_STAT_FILE; } } return MP_IMPORT_STAT_NO_EXIST; } STATIC mp_obj_t fat_vfs_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 1, 1, false); // create new object fs_user_mount_t *vfs = m_new_obj(fs_user_mount_t); vfs->base.type = type; vfs->fatfs.drv = vfs; // Initialise underlying block device vfs->blockdev.flags = MP_BLOCKDEV_FLAG_FREE_OBJ; vfs->blockdev.block_size = FF_MIN_SS; // default, will be populated by call to MP_BLOCKDEV_IOCTL_BLOCK_SIZE mp_vfs_blockdev_init(&vfs->blockdev, args[0]); // mount the block device so the VFS methods can be used FRESULT res = f_mount(&vfs->fatfs); if (res == FR_NO_FILESYSTEM) { // don't error out if no filesystem, to let mkfs()/mount() create one if wanted vfs->blockdev.flags |= MP_BLOCKDEV_FLAG_NO_FILESYSTEM; } else if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } return MP_OBJ_FROM_PTR(vfs); } #if _FS_REENTRANT STATIC mp_obj_t fat_vfs_del(mp_obj_t self_in) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(self_in); // f_umount only needs to be called to release the sync object f_umount(&self->fatfs); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_del_obj, fat_vfs_del); #endif STATIC mp_obj_t fat_vfs_mkfs(mp_obj_t bdev_in) { // create new object fs_user_mount_t *vfs = MP_OBJ_TO_PTR(fat_vfs_make_new(&mp_fat_vfs_type, 1, 0, &bdev_in)); // make the filesystem uint8_t working_buf[FF_MAX_SS]; FRESULT res = f_mkfs(&vfs->fatfs, FM_FAT | FM_SFD, 0, working_buf, sizeof(working_buf)); if (res == FR_MKFS_ABORTED) { // Probably doesn't support FAT16 res = f_mkfs(&vfs->fatfs, FM_FAT32, 0, working_buf, sizeof(working_buf)); } if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_mkfs_fun_obj, fat_vfs_mkfs); STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(fat_vfs_mkfs_obj, MP_ROM_PTR(&fat_vfs_mkfs_fun_obj)); typedef struct _mp_vfs_fat_ilistdir_it_t { mp_obj_base_t base; mp_fun_1_t iternext; bool is_str; FF_DIR dir; } mp_vfs_fat_ilistdir_it_t; STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) { mp_vfs_fat_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); for (;;) { FILINFO fno; FRESULT res = f_readdir(&self->dir, &fno); char *fn = fno.fname; if (res != FR_OK || fn[0] == 0) { // stop on error or end of dir break; } // Note that FatFS already filters . and .., so we don't need to // make 4-tuple with info about this entry mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); if (self->is_str) { t->items[0] = mp_obj_new_str(fn, strlen(fn)); } else { t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } if (fno.fattrib & AM_DIR) { // dir t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); } else { // file t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); } t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number t->items[3] = mp_obj_new_int_from_uint(fno.fsize); return MP_OBJ_FROM_PTR(t); } // ignore error because we may be closing a second time f_closedir(&self->dir); return MP_OBJ_STOP_ITERATION; } STATIC mp_obj_t fat_vfs_ilistdir_func(size_t n_args, const mp_obj_t *args) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(args[0]); bool is_str_type = true; const char *path; if (n_args == 2) { if (mp_obj_get_type(args[1]) == &mp_type_bytes) { is_str_type = false; } path = mp_obj_str_get_str(args[1]); } else { path = ""; } // Create a new iterator object to list the dir mp_vfs_fat_ilistdir_it_t *iter = m_new_obj(mp_vfs_fat_ilistdir_it_t); iter->base.type = &mp_type_polymorph_iter; iter->iternext = mp_vfs_fat_ilistdir_it_iternext; iter->is_str = is_str_type; FRESULT res = f_opendir(&self->fatfs, &iter->dir, path); if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } return MP_OBJ_FROM_PTR(iter); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fat_vfs_ilistdir_obj, 1, 2, fat_vfs_ilistdir_func); STATIC mp_obj_t fat_vfs_remove_internal(mp_obj_t vfs_in, mp_obj_t path_in, mp_int_t attr) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); const char *path = mp_obj_str_get_str(path_in); FILINFO fno; FRESULT res = f_stat(&self->fatfs, path, &fno); if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } // check if path is a file or directory if ((fno.fattrib & AM_DIR) == attr) { res = f_unlink(&self->fatfs, path); if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } return mp_const_none; } else { mp_raise_OSError(attr ? MP_ENOTDIR : MP_EISDIR); } } STATIC mp_obj_t fat_vfs_remove(mp_obj_t vfs_in, mp_obj_t path_in) { return fat_vfs_remove_internal(vfs_in, path_in, 0); // 0 == file attribute } STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_remove_obj, fat_vfs_remove); STATIC mp_obj_t fat_vfs_rmdir(mp_obj_t vfs_in, mp_obj_t path_in) { return fat_vfs_remove_internal(vfs_in, path_in, AM_DIR); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_rmdir_obj, fat_vfs_rmdir); STATIC mp_obj_t fat_vfs_rename(mp_obj_t vfs_in, mp_obj_t path_in, mp_obj_t path_out) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); const char *old_path = mp_obj_str_get_str(path_in); const char *new_path = mp_obj_str_get_str(path_out); FRESULT res = f_rename(&self->fatfs, old_path, new_path); if (res == FR_EXIST) { // if new_path exists then try removing it (but only if it's a file) fat_vfs_remove_internal(vfs_in, path_out, 0); // 0 == file attribute // try to rename again res = f_rename(&self->fatfs, old_path, new_path); } if (res == FR_OK) { return mp_const_none; } else { mp_raise_OSError(fresult_to_errno_table[res]); } } STATIC MP_DEFINE_CONST_FUN_OBJ_3(fat_vfs_rename_obj, fat_vfs_rename); STATIC mp_obj_t fat_vfs_mkdir(mp_obj_t vfs_in, mp_obj_t path_o) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); const char *path = mp_obj_str_get_str(path_o); FRESULT res = f_mkdir(&self->fatfs, path); if (res == FR_OK) { return mp_const_none; } else { mp_raise_OSError(fresult_to_errno_table[res]); } } STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_mkdir_obj, fat_vfs_mkdir); // Change current directory. STATIC mp_obj_t fat_vfs_chdir(mp_obj_t vfs_in, mp_obj_t path_in) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); const char *path; path = mp_obj_str_get_str(path_in); FRESULT res = f_chdir(&self->fatfs, path); if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_chdir_obj, fat_vfs_chdir); // Get the current directory. STATIC mp_obj_t fat_vfs_getcwd(mp_obj_t vfs_in) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); char buf[MICROPY_ALLOC_PATH_MAX + 1]; FRESULT res = f_getcwd(&self->fatfs, buf, sizeof(buf)); if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } return mp_obj_new_str(buf, strlen(buf)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_getcwd_obj, fat_vfs_getcwd); // Get the status of a file or directory. STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); const char *path = mp_obj_str_get_str(path_in); FILINFO fno; if (path[0] == 0 || (path[0] == '/' && path[1] == 0)) { // stat root directory fno.fsize = 0; fno.fdate = 0x2821; // Jan 1, 2000 fno.ftime = 0; fno.fattrib = AM_DIR; } else { FRESULT res = f_stat(&self->fatfs, path, &fno); if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } } mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); mp_int_t mode = 0; if (fno.fattrib & AM_DIR) { mode |= MP_S_IFDIR; } else { mode |= MP_S_IFREG; } mp_int_t seconds = timeutils_seconds_since_epoch( 1980 + ((fno.fdate >> 9) & 0x7f), (fno.fdate >> 5) & 0x0f, fno.fdate & 0x1f, (fno.ftime >> 11) & 0x1f, (fno.ftime >> 5) & 0x3f, 2 * (fno.ftime & 0x1f) ); t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid t->items[6] = mp_obj_new_int_from_uint(fno.fsize); // st_size t->items[7] = mp_obj_new_int_from_uint(seconds); // st_atime t->items[8] = mp_obj_new_int_from_uint(seconds); // st_mtime t->items[9] = mp_obj_new_int_from_uint(seconds); // st_ctime return MP_OBJ_FROM_PTR(t); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_stat_obj, fat_vfs_stat); // Get the status of a VFS. STATIC mp_obj_t fat_vfs_statvfs(mp_obj_t vfs_in, mp_obj_t path_in) { mp_obj_fat_vfs_t *self = MP_OBJ_TO_PTR(vfs_in); (void)path_in; DWORD nclst; FATFS *fatfs = &self->fatfs; FRESULT res = f_getfree(fatfs, &nclst); if (FR_OK != res) { mp_raise_OSError(fresult_to_errno_table[res]); } mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(fatfs->csize * SECSIZE(fatfs)); // f_bsize t->items[1] = t->items[0]; // f_frsize t->items[2] = MP_OBJ_NEW_SMALL_INT((fatfs->n_fatent - 2)); // f_blocks t->items[3] = MP_OBJ_NEW_SMALL_INT(nclst); // f_bfree t->items[4] = t->items[3]; // f_bavail t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // f_files t->items[6] = MP_OBJ_NEW_SMALL_INT(0); // f_ffree t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // f_favail t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags t->items[9] = MP_OBJ_NEW_SMALL_INT(FF_MAX_LFN); // f_namemax return MP_OBJ_FROM_PTR(t); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_statvfs_obj, fat_vfs_statvfs); STATIC mp_obj_t vfs_fat_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) { fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in); // Read-only device indicated by writeblocks[0] == MP_OBJ_NULL. // User can specify read-only device by: // 1. readonly=True keyword argument // 2. nonexistent writeblocks method (then writeblocks[0] == MP_OBJ_NULL already) if (mp_obj_is_true(readonly)) { self->blockdev.writeblocks[0] = MP_OBJ_NULL; } // check if we need to make the filesystem FRESULT res = (self->blockdev.flags & MP_BLOCKDEV_FLAG_NO_FILESYSTEM) ? FR_NO_FILESYSTEM : FR_OK; if (res == FR_NO_FILESYSTEM && mp_obj_is_true(mkfs)) { uint8_t working_buf[FF_MAX_SS]; res = f_mkfs(&self->fatfs, FM_FAT | FM_SFD, 0, working_buf, sizeof(working_buf)); } if (res != FR_OK) { mp_raise_OSError(fresult_to_errno_table[res]); } self->blockdev.flags &= ~MP_BLOCKDEV_FLAG_NO_FILESYSTEM; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_fat_mount_obj, vfs_fat_mount); STATIC mp_obj_t vfs_fat_umount(mp_obj_t self_in) { (void)self_in; // keep the FAT filesystem mounted internally so the VFS methods can still be used return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_umount_obj, vfs_fat_umount); STATIC const mp_rom_map_elem_t fat_vfs_locals_dict_table[] = { #if _FS_REENTRANT { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&fat_vfs_del_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_mkfs), MP_ROM_PTR(&fat_vfs_mkfs_obj) }, { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&fat_vfs_open_obj) }, { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&fat_vfs_ilistdir_obj) }, { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&fat_vfs_mkdir_obj) }, { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&fat_vfs_rmdir_obj) }, { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&fat_vfs_chdir_obj) }, { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&fat_vfs_getcwd_obj) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&fat_vfs_remove_obj) }, { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&fat_vfs_rename_obj) }, { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&fat_vfs_stat_obj) }, { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&fat_vfs_statvfs_obj) }, { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_fat_mount_obj) }, { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&fat_vfs_umount_obj) }, }; STATIC MP_DEFINE_CONST_DICT(fat_vfs_locals_dict, fat_vfs_locals_dict_table); STATIC const mp_vfs_proto_t fat_vfs_proto = { .import_stat = fat_vfs_import_stat, }; const mp_obj_type_t mp_fat_vfs_type = { { &mp_type_type }, .name = MP_QSTR_VfsFat, .make_new = fat_vfs_make_new, .protocol = &fat_vfs_proto, .locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict, }; #endif // MICROPY_VFS_FAT
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_fat.c
C
apache-2.0
15,384
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_VFS_FAT_H #define MICROPY_INCLUDED_EXTMOD_VFS_FAT_H #include "py/obj.h" #include "lib/oofatfs/ff.h" #include "extmod/vfs.h" typedef struct _fs_user_mount_t { mp_obj_base_t base; mp_vfs_blockdev_t blockdev; FATFS fatfs; } fs_user_mount_t; extern const byte fresult_to_errno_table[20]; extern const mp_obj_type_t mp_fat_vfs_type; extern const mp_obj_type_t mp_type_vfs_fat_fileio; extern const mp_obj_type_t mp_type_vfs_fat_textio; MP_DECLARE_CONST_FUN_OBJ_3(fat_vfs_open_obj); #endif // MICROPY_INCLUDED_EXTMOD_VFS_FAT_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_fat.h
C
apache-2.0
1,800
/* * This file is part of the MicroPython project, http://micropython.org/ * * Original template for this file comes from: * Low level disk I/O module skeleton for FatFs, (C)ChaN, 2013 * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_VFS && MICROPY_VFS_FAT #include <stdint.h> #include <stdio.h> #include "py/mphal.h" #include "py/runtime.h" #include "py/binary.h" #include "py/objarray.h" #include "py/mperrno.h" #include "lib/oofatfs/ff.h" #include "lib/oofatfs/diskio.h" #include "extmod/vfs_fat.h" typedef void *bdev_t; STATIC fs_user_mount_t *disk_get_device(void *bdev) { return (fs_user_mount_t *)bdev; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/ DRESULT disk_read( bdev_t pdrv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ UINT count /* Number of sectors to read (1..128) */ ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; } int ret = mp_vfs_blockdev_read(&vfs->blockdev, sector, count, buff); return ret == 0 ? RES_OK : RES_ERROR; } /*-----------------------------------------------------------------------*/ /* Write Sector(s) */ /*-----------------------------------------------------------------------*/ DRESULT disk_write( bdev_t pdrv, /* Physical drive nmuber (0..) */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ UINT count /* Number of sectors to write (1..128) */ ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; } int ret = mp_vfs_blockdev_write(&vfs->blockdev, sector, count, buff); if (ret == -MP_EROFS) { // read-only block device return RES_WRPRT; } return ret == 0 ? RES_OK : RES_ERROR; } /*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/ DRESULT disk_ioctl( bdev_t pdrv, /* Physical drive nmuber (0..) */ BYTE cmd, /* Control code */ void *buff /* Buffer to send/receive control data */ ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; } // First part: call the relevant method of the underlying block device static const uint8_t op_map[8] = { [CTRL_SYNC] = MP_BLOCKDEV_IOCTL_SYNC, [GET_SECTOR_COUNT] = MP_BLOCKDEV_IOCTL_BLOCK_COUNT, [GET_SECTOR_SIZE] = MP_BLOCKDEV_IOCTL_BLOCK_SIZE, [IOCTL_INIT] = MP_BLOCKDEV_IOCTL_INIT, }; uint8_t bp_op = op_map[cmd & 7]; mp_obj_t ret = mp_const_none; if (bp_op != 0) { ret = mp_vfs_blockdev_ioctl(&vfs->blockdev, bp_op, 0); } // Second part: convert the result for return switch (cmd) { case CTRL_SYNC: return RES_OK; case GET_SECTOR_COUNT: { *((DWORD *)buff) = mp_obj_get_int(ret); return RES_OK; } case GET_SECTOR_SIZE: { if (ret == mp_const_none) { // Default sector size *((WORD *)buff) = 512; } else { *((WORD *)buff) = mp_obj_get_int(ret); } // need to store ssize because we use it in disk_read/disk_write vfs->blockdev.block_size = *((WORD *)buff); return RES_OK; } case GET_BLOCK_SIZE: *((DWORD *)buff) = 1; // erase block size in units of sector size return RES_OK; case IOCTL_INIT: case IOCTL_STATUS: { DSTATUS stat; if (ret != mp_const_none && MP_OBJ_SMALL_INT_VALUE(ret) != 0) { // error initialising stat = STA_NOINIT; } else if (vfs->blockdev.writeblocks[0] == MP_OBJ_NULL) { stat = STA_PROTECT; } else { stat = 0; } *((DSTATUS *)buff) = stat; return RES_OK; } default: return RES_PARERR; } } #endif // MICROPY_VFS && MICROPY_VFS_FAT
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_fat_diskio.c
C
apache-2.0
5,668
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013, 2014 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mpconfig.h" #if MICROPY_VFS && MICROPY_VFS_FAT #include <stdio.h> #include "py/runtime.h" #include "py/stream.h" #include "py/mperrno.h" #include "lib/oofatfs/ff.h" #include "extmod/vfs_fat.h" // this table converts from FRESULT to POSIX errno const byte fresult_to_errno_table[20] = { [FR_OK] = 0, [FR_DISK_ERR] = MP_EIO, [FR_INT_ERR] = MP_EIO, [FR_NOT_READY] = MP_EBUSY, [FR_NO_FILE] = MP_ENOENT, [FR_NO_PATH] = MP_ENOENT, [FR_INVALID_NAME] = MP_EINVAL, [FR_DENIED] = MP_EACCES, [FR_EXIST] = MP_EEXIST, [FR_INVALID_OBJECT] = MP_EINVAL, [FR_WRITE_PROTECTED] = MP_EROFS, [FR_INVALID_DRIVE] = MP_ENODEV, [FR_NOT_ENABLED] = MP_ENODEV, [FR_NO_FILESYSTEM] = MP_ENODEV, [FR_MKFS_ABORTED] = MP_EIO, [FR_TIMEOUT] = MP_EIO, [FR_LOCKED] = MP_EIO, [FR_NOT_ENOUGH_CORE] = MP_ENOMEM, [FR_TOO_MANY_OPEN_FILES] = MP_EMFILE, [FR_INVALID_PARAMETER] = MP_EINVAL, }; typedef struct _pyb_file_obj_t { mp_obj_base_t base; FIL fp; } pyb_file_obj_t; STATIC void file_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_printf(print, "<io.%s %p>", mp_obj_get_type_str(self_in), MP_OBJ_TO_PTR(self_in)); } STATIC mp_uint_t file_obj_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { pyb_file_obj_t *self = MP_OBJ_TO_PTR(self_in); UINT sz_out; FRESULT res = f_read(&self->fp, buf, size, &sz_out); if (res != FR_OK) { *errcode = fresult_to_errno_table[res]; return MP_STREAM_ERROR; } return sz_out; } STATIC mp_uint_t file_obj_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { pyb_file_obj_t *self = MP_OBJ_TO_PTR(self_in); UINT sz_out; FRESULT res = f_write(&self->fp, buf, size, &sz_out); if (res != FR_OK) { *errcode = fresult_to_errno_table[res]; return MP_STREAM_ERROR; } if (sz_out != size) { // The FatFS documentation says that this means disk full. *errcode = MP_ENOSPC; return MP_STREAM_ERROR; } return sz_out; } STATIC mp_obj_t file_obj___exit__(size_t n_args, const mp_obj_t *args) { (void)n_args; return mp_stream_close(args[0]); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(file_obj___exit___obj, 4, 4, file_obj___exit__); STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { pyb_file_obj_t *self = MP_OBJ_TO_PTR(o_in); if (request == MP_STREAM_SEEK) { struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; switch (s->whence) { case 0: // SEEK_SET f_lseek(&self->fp, s->offset); break; case 1: // SEEK_CUR f_lseek(&self->fp, f_tell(&self->fp) + s->offset); break; case 2: // SEEK_END f_lseek(&self->fp, f_size(&self->fp) + s->offset); break; } s->offset = f_tell(&self->fp); return 0; } else if (request == MP_STREAM_FLUSH) { FRESULT res = f_sync(&self->fp); if (res != FR_OK) { *errcode = fresult_to_errno_table[res]; return MP_STREAM_ERROR; } return 0; } else if (request == MP_STREAM_CLOSE) { // if fs==NULL then the file is closed and in that case this method is a no-op if (self->fp.obj.fs != NULL) { FRESULT res = f_close(&self->fp); if (res != FR_OK) { *errcode = fresult_to_errno_table[res]; return MP_STREAM_ERROR; } } return 0; } else { *errcode = MP_EINVAL; return MP_STREAM_ERROR; } } // Note: encoding is ignored for now; it's also not a valid kwarg for CPython's FileIO, // but by adding it here we can use one single mp_arg_t array for open() and FileIO's constructor STATIC const mp_arg_t file_open_args[] = { { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_QSTR(MP_QSTR_r)} }, { MP_QSTR_encoding, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = MP_ROM_NONE} }, }; #define FILE_OPEN_NUM_ARGS MP_ARRAY_SIZE(file_open_args) STATIC mp_obj_t file_open(fs_user_mount_t *vfs, const mp_obj_type_t *type, mp_arg_val_t *args) { int mode = 0; const char *mode_s = mp_obj_str_get_str(args[1].u_obj); // TODO make sure only one of r, w, x, a, and b, t are specified while (*mode_s) { switch (*mode_s++) { case 'r': mode |= FA_READ; break; case 'w': mode |= FA_WRITE | FA_CREATE_ALWAYS; break; case 'x': mode |= FA_WRITE | FA_CREATE_NEW; break; case 'a': mode |= FA_WRITE | FA_OPEN_ALWAYS; break; case '+': mode |= FA_READ | FA_WRITE; break; #if MICROPY_PY_IO_FILEIO case 'b': type = &mp_type_vfs_fat_fileio; break; #endif case 't': type = &mp_type_vfs_fat_textio; break; } } pyb_file_obj_t *o = m_new_obj_with_finaliser(pyb_file_obj_t); o->base.type = type; const char *fname = mp_obj_str_get_str(args[0].u_obj); assert(vfs != NULL); FRESULT res = f_open(&vfs->fatfs, &o->fp, fname, mode); if (res != FR_OK) { m_del_obj(pyb_file_obj_t, o); mp_raise_OSError(fresult_to_errno_table[res]); } // for 'a' mode, we must begin at the end of the file if ((mode & FA_OPEN_ALWAYS) != 0) { f_lseek(&o->fp, f_size(&o->fp)); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t file_obj_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS]; mp_arg_parse_all_kw_array(n_args, n_kw, args, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals); return file_open(NULL, type, arg_vals); } // TODO gc hook to close the file if not already closed STATIC const mp_rom_map_elem_t vfs_fat_rawfile_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) }, { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) }, { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&file_obj___exit___obj) }, }; STATIC MP_DEFINE_CONST_DICT(vfs_fat_rawfile_locals_dict, vfs_fat_rawfile_locals_dict_table); #if MICROPY_PY_IO_FILEIO STATIC const mp_stream_p_t vfs_fat_fileio_stream_p = { .read = file_obj_read, .write = file_obj_write, .ioctl = file_obj_ioctl, }; const mp_obj_type_t mp_type_vfs_fat_fileio = { { &mp_type_type }, .name = MP_QSTR_FileIO, .print = file_obj_print, .make_new = file_obj_make_new, .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &vfs_fat_fileio_stream_p, .locals_dict = (mp_obj_dict_t *)&vfs_fat_rawfile_locals_dict, }; #endif STATIC const mp_stream_p_t vfs_fat_textio_stream_p = { .read = file_obj_read, .write = file_obj_write, .ioctl = file_obj_ioctl, .is_text = true, }; const mp_obj_type_t mp_type_vfs_fat_textio = { { &mp_type_type }, .name = MP_QSTR_TextIOWrapper, .print = file_obj_print, .make_new = file_obj_make_new, .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &vfs_fat_textio_stream_p, .locals_dict = (mp_obj_dict_t *)&vfs_fat_rawfile_locals_dict, }; // Factory function for I/O stream classes STATIC mp_obj_t fatfs_builtin_open_self(mp_obj_t self_in, mp_obj_t path, mp_obj_t mode) { // TODO: analyze buffering args and instantiate appropriate type fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in); mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS]; arg_vals[0].u_obj = path; arg_vals[1].u_obj = mode; arg_vals[2].u_obj = mp_const_none; return file_open(self, &mp_type_vfs_fat_textio, arg_vals); } MP_DEFINE_CONST_FUN_OBJ_3(fat_vfs_open_obj, fatfs_builtin_open_self); #endif // MICROPY_VFS && MICROPY_VFS_FAT
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_fat_file.c
C
apache-2.0
10,093
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019-2020 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/mphal.h" #include "shared/timeutils/timeutils.h" #include "extmod/vfs.h" #include "extmod/vfs_lfs.h" #if MICROPY_VFS && (MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2) enum { LFS_MAKE_ARG_bdev, LFS_MAKE_ARG_readsize, LFS_MAKE_ARG_progsize, LFS_MAKE_ARG_lookahead, LFS_MAKE_ARG_mtime }; static const mp_arg_t lfs_make_allowed_args[] = { { MP_QSTR_, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_readsize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 32} }, { MP_QSTR_progsize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 32} }, { MP_QSTR_lookahead, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 32} }, { MP_QSTR_mtime, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, }; #if MICROPY_VFS_LFS1 #include "lib/littlefs/lfs1.h" #define LFS_BUILD_VERSION (1) #define LFSx_MACRO(s) LFS1##s #define LFSx_API(s) lfs1_##s #define MP_VFS_LFSx(s) mp_vfs_lfs1_##s #define MP_OBJ_VFS_LFSx mp_obj_vfs_lfs1_t #define MP_OBJ_VFS_LFSx_FILE mp_obj_vfs_lfs1_file_t #define MP_TYPE_VFS_LFSx mp_type_vfs_lfs1 #define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs1##s typedef struct _mp_obj_vfs_lfs1_t { mp_obj_base_t base; mp_vfs_blockdev_t blockdev; vstr_t cur_dir; struct lfs1_config config; lfs1_t lfs; } mp_obj_vfs_lfs1_t; typedef struct _mp_obj_vfs_lfs1_file_t { mp_obj_base_t base; mp_obj_vfs_lfs1_t *vfs; lfs1_file_t file; struct lfs1_file_config cfg; uint8_t file_buffer[0]; } mp_obj_vfs_lfs1_file_t; const char *mp_vfs_lfs1_make_path(mp_obj_vfs_lfs1_t *self, mp_obj_t path_in); mp_obj_t mp_vfs_lfs1_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in); #include "extmod/vfs_lfsx.c" #include "extmod/vfs_lfsx_file.c" #undef LFS_BUILD_VERSION #undef LFSx_MACRO #undef LFSx_API #undef MP_VFS_LFSx #undef MP_OBJ_VFS_LFSx #undef MP_OBJ_VFS_LFSx_FILE #undef MP_TYPE_VFS_LFSx #undef MP_TYPE_VFS_LFSx_ #endif // MICROPY_VFS_LFS1 #if MICROPY_VFS_LFS2 #include "lib/littlefs/lfs2.h" #define LFS_BUILD_VERSION (2) #define LFSx_MACRO(s) LFS2##s #define LFSx_API(s) lfs2_##s #define MP_VFS_LFSx(s) mp_vfs_lfs2_##s #define MP_OBJ_VFS_LFSx mp_obj_vfs_lfs2_t #define MP_OBJ_VFS_LFSx_FILE mp_obj_vfs_lfs2_file_t #define MP_TYPE_VFS_LFSx mp_type_vfs_lfs2 #define MP_TYPE_VFS_LFSx_(s) mp_type_vfs_lfs2##s // Attribute ids for lfs2_attr.type. #define LFS_ATTR_MTIME (1) // 64-bit little endian, nanoseconds since 1970/1/1 typedef struct _mp_obj_vfs_lfs2_t { mp_obj_base_t base; mp_vfs_blockdev_t blockdev; bool enable_mtime; vstr_t cur_dir; struct lfs2_config config; lfs2_t lfs; } mp_obj_vfs_lfs2_t; typedef struct _mp_obj_vfs_lfs2_file_t { mp_obj_base_t base; mp_obj_vfs_lfs2_t *vfs; uint8_t mtime[8]; lfs2_file_t file; struct lfs2_file_config cfg; struct lfs2_attr attrs[1]; uint8_t file_buffer[0]; } mp_obj_vfs_lfs2_file_t; const char *mp_vfs_lfs2_make_path(mp_obj_vfs_lfs2_t *self, mp_obj_t path_in); mp_obj_t mp_vfs_lfs2_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in); STATIC void lfs_get_mtime(uint8_t buf[8]) { // On-disk storage of timestamps uses 1970 as the Epoch, so convert from host's Epoch. uint64_t ns = timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(mp_hal_time_ns()); // Store "ns" to "buf" in little-endian format (essentially htole64). for (size_t i = 0; i < 8; ++i) { buf[i] = ns; ns >>= 8; } } #include "extmod/vfs_lfsx.c" #include "extmod/vfs_lfsx_file.c" #endif // MICROPY_VFS_LFS2 #endif // MICROPY_VFS && (MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2)
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_lfs.c
C
apache-2.0
4,801
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_VFS_LFS_H #define MICROPY_INCLUDED_EXTMOD_VFS_LFS_H #include "py/obj.h" extern const mp_obj_type_t mp_type_vfs_lfs1; extern const mp_obj_type_t mp_type_vfs_lfs1_fileio; extern const mp_obj_type_t mp_type_vfs_lfs1_textio; extern const mp_obj_type_t mp_type_vfs_lfs2; extern const mp_obj_type_t mp_type_vfs_lfs2_fileio; extern const mp_obj_type_t mp_type_vfs_lfs2_textio; #endif // MICROPY_INCLUDED_EXTMOD_VFS_LFS_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_lfs.h
C
apache-2.0
1,675
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019-2020 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "py/binary.h" #include "py/objarray.h" #include "py/objstr.h" #include "py/mperrno.h" #include "extmod/vfs.h" #include "shared/timeutils/timeutils.h" STATIC int MP_VFS_LFSx(dev_ioctl)(const struct LFSx_API (config) * c, int cmd, int arg, bool must_return_int) { mp_obj_t ret = mp_vfs_blockdev_ioctl(c->context, cmd, arg); int ret_i = 0; if (must_return_int || ret != mp_const_none) { ret_i = mp_obj_get_int(ret); } return ret_i; } STATIC int MP_VFS_LFSx(dev_read)(const struct LFSx_API (config) * c, LFSx_API(block_t) block, LFSx_API(off_t) off, void *buffer, LFSx_API(size_t) size) { return mp_vfs_blockdev_read_ext(c->context, block, off, size, buffer); } STATIC int MP_VFS_LFSx(dev_prog)(const struct LFSx_API (config) * c, LFSx_API(block_t) block, LFSx_API(off_t) off, const void *buffer, LFSx_API(size_t) size) { return mp_vfs_blockdev_write_ext(c->context, block, off, size, buffer); } STATIC int MP_VFS_LFSx(dev_erase)(const struct LFSx_API (config) * c, LFSx_API(block_t) block) { return MP_VFS_LFSx(dev_ioctl)(c, MP_BLOCKDEV_IOCTL_BLOCK_ERASE, block, true); } STATIC int MP_VFS_LFSx(dev_sync)(const struct LFSx_API (config) * c) { return MP_VFS_LFSx(dev_ioctl)(c, MP_BLOCKDEV_IOCTL_SYNC, 0, false); } STATIC void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx * self, mp_obj_t bdev, size_t read_size, size_t prog_size, size_t lookahead) { self->blockdev.flags = MP_BLOCKDEV_FLAG_FREE_OBJ; mp_vfs_blockdev_init(&self->blockdev, bdev); struct LFSx_API (config) * config = &self->config; memset(config, 0, sizeof(*config)); config->context = &self->blockdev; config->read = MP_VFS_LFSx(dev_read); config->prog = MP_VFS_LFSx(dev_prog); config->erase = MP_VFS_LFSx(dev_erase); config->sync = MP_VFS_LFSx(dev_sync); MP_VFS_LFSx(dev_ioctl)(config, MP_BLOCKDEV_IOCTL_INIT, 1, false); // initialise block device int bs = MP_VFS_LFSx(dev_ioctl)(config, MP_BLOCKDEV_IOCTL_BLOCK_SIZE, 0, true); // get block size int bc = MP_VFS_LFSx(dev_ioctl)(config, MP_BLOCKDEV_IOCTL_BLOCK_COUNT, 0, true); // get block count self->blockdev.block_size = bs; config->read_size = read_size; config->prog_size = prog_size; config->block_size = bs; config->block_count = bc; #if LFS_BUILD_VERSION == 1 config->lookahead = lookahead; config->read_buffer = m_new(uint8_t, config->read_size); config->prog_buffer = m_new(uint8_t, config->prog_size); config->lookahead_buffer = m_new(uint8_t, config->lookahead / 8); #else config->block_cycles = 100; config->cache_size = 4 * MAX(read_size, prog_size); config->lookahead_size = lookahead; config->read_buffer = m_new(uint8_t, config->cache_size); config->prog_buffer = m_new(uint8_t, config->cache_size); config->lookahead_buffer = m_new(uint8_t, config->lookahead_size); #endif } const char *MP_VFS_LFSx(make_path)(MP_OBJ_VFS_LFSx * self, mp_obj_t path_in) { const char *path = mp_obj_str_get_str(path_in); if (path[0] != '/') { size_t l = vstr_len(&self->cur_dir); if (l > 0) { vstr_add_str(&self->cur_dir, path); path = vstr_null_terminated_str(&self->cur_dir); self->cur_dir.len = l; } } return path; } STATIC mp_obj_t MP_VFS_LFSx(make_new)(const mp_obj_type_t * type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { mp_arg_val_t args[MP_ARRAY_SIZE(lfs_make_allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(lfs_make_allowed_args), lfs_make_allowed_args, args); MP_OBJ_VFS_LFSx *self = m_new0(MP_OBJ_VFS_LFSx, 1); self->base.type = type; vstr_init(&self->cur_dir, 16); vstr_add_byte(&self->cur_dir, '/'); #if LFS_BUILD_VERSION == 2 self->enable_mtime = args[LFS_MAKE_ARG_mtime].u_bool; #endif MP_VFS_LFSx(init_config)(self, args[LFS_MAKE_ARG_bdev].u_obj, args[LFS_MAKE_ARG_readsize].u_int, args[LFS_MAKE_ARG_progsize].u_int, args[LFS_MAKE_ARG_lookahead].u_int); int ret = LFSx_API(mount)(&self->lfs, &self->config); if (ret < 0) { mp_raise_OSError(-ret); } return MP_OBJ_FROM_PTR(self); } STATIC mp_obj_t MP_VFS_LFSx(mkfs)(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_arg_val_t args[MP_ARRAY_SIZE(lfs_make_allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(lfs_make_allowed_args), lfs_make_allowed_args, args); MP_OBJ_VFS_LFSx self; MP_VFS_LFSx(init_config)(&self, args[LFS_MAKE_ARG_bdev].u_obj, args[LFS_MAKE_ARG_readsize].u_int, args[LFS_MAKE_ARG_progsize].u_int, args[LFS_MAKE_ARG_lookahead].u_int); int ret = LFSx_API(format)(&self.lfs, &self.config); if (ret < 0) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(MP_VFS_LFSx(mkfs_fun_obj), 0, MP_VFS_LFSx(mkfs)); STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(MP_VFS_LFSx(mkfs_obj), MP_ROM_PTR(&MP_VFS_LFSx(mkfs_fun_obj))); // Implementation of mp_vfs_lfs_file_open is provided in vfs_lfsx_file.c STATIC MP_DEFINE_CONST_FUN_OBJ_3(MP_VFS_LFSx(open_obj), MP_VFS_LFSx(file_open)); typedef struct MP_VFS_LFSx (_ilistdir_it_t) { mp_obj_base_t base; mp_fun_1_t iternext; bool is_str; MP_OBJ_VFS_LFSx *vfs; LFSx_API(dir_t) dir; } MP_VFS_LFSx(ilistdir_it_t); STATIC mp_obj_t MP_VFS_LFSx(ilistdir_it_iternext)(mp_obj_t self_in) { MP_VFS_LFSx(ilistdir_it_t) * self = MP_OBJ_TO_PTR(self_in); struct LFSx_API (info) info; for (;;) { int ret = LFSx_API(dir_read)(&self->vfs->lfs, &self->dir, &info); if (ret == 0) { LFSx_API(dir_close)(&self->vfs->lfs, &self->dir); return MP_OBJ_STOP_ITERATION; } if (!(info.name[0] == '.' && (info.name[1] == '\0' || (info.name[1] == '.' && info.name[2] == '\0')))) { break; } } // make 4-tuple with info about this entry mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); if (self->is_str) { t->items[0] = mp_obj_new_str(info.name, strlen(info.name)); } else { t->items[0] = mp_obj_new_bytes((const byte *)info.name, strlen(info.name)); } t->items[1] = MP_OBJ_NEW_SMALL_INT(info.type == LFSx_MACRO(_TYPE_REG) ? MP_S_IFREG : MP_S_IFDIR); t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number t->items[3] = MP_OBJ_NEW_SMALL_INT(info.size); return MP_OBJ_FROM_PTR(t); } STATIC mp_obj_t MP_VFS_LFSx(ilistdir_func)(size_t n_args, const mp_obj_t *args) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(args[0]); bool is_str_type = true; const char *path; if (n_args == 2) { if (mp_obj_get_type(args[1]) == &mp_type_bytes) { is_str_type = false; } path = MP_VFS_LFSx(make_path)(self, args[1]); } else { path = vstr_null_terminated_str(&self->cur_dir); } MP_VFS_LFSx(ilistdir_it_t) * iter = m_new_obj(MP_VFS_LFSx(ilistdir_it_t)); iter->base.type = &mp_type_polymorph_iter; iter->iternext = MP_VFS_LFSx(ilistdir_it_iternext); iter->is_str = is_str_type; iter->vfs = self; int ret = LFSx_API(dir_open)(&self->lfs, &iter->dir, path); if (ret < 0) { mp_raise_OSError(-ret); } return MP_OBJ_FROM_PTR(iter); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(MP_VFS_LFSx(ilistdir_obj), 1, 2, MP_VFS_LFSx(ilistdir_func)); STATIC mp_obj_t MP_VFS_LFSx(remove)(mp_obj_t self_in, mp_obj_t path_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); const char *path = MP_VFS_LFSx(make_path)(self, path_in); int ret = LFSx_API(remove)(&self->lfs, path); if (ret < 0) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(remove_obj), MP_VFS_LFSx(remove)); STATIC mp_obj_t MP_VFS_LFSx(rmdir)(mp_obj_t self_in, mp_obj_t path_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); const char *path = MP_VFS_LFSx(make_path)(self, path_in); int ret = LFSx_API(remove)(&self->lfs, path); if (ret < 0) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(rmdir_obj), MP_VFS_LFSx(rmdir)); STATIC mp_obj_t MP_VFS_LFSx(rename)(mp_obj_t self_in, mp_obj_t path_old_in, mp_obj_t path_new_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); const char *path_old = MP_VFS_LFSx(make_path)(self, path_old_in); const char *path = mp_obj_str_get_str(path_new_in); vstr_t path_new; vstr_init(&path_new, vstr_len(&self->cur_dir)); if (path[0] != '/') { vstr_add_strn(&path_new, vstr_str(&self->cur_dir), vstr_len(&self->cur_dir)); } vstr_add_str(&path_new, path); int ret = LFSx_API(rename)(&self->lfs, path_old, vstr_null_terminated_str(&path_new)); vstr_clear(&path_new); if (ret < 0) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(MP_VFS_LFSx(rename_obj), MP_VFS_LFSx(rename)); STATIC mp_obj_t MP_VFS_LFSx(mkdir)(mp_obj_t self_in, mp_obj_t path_o) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); const char *path = MP_VFS_LFSx(make_path)(self, path_o); int ret = LFSx_API(mkdir)(&self->lfs, path); if (ret < 0) { mp_raise_OSError(-ret); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(mkdir_obj), MP_VFS_LFSx(mkdir)); STATIC mp_obj_t MP_VFS_LFSx(chdir)(mp_obj_t self_in, mp_obj_t path_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); // Check path exists const char *path = MP_VFS_LFSx(make_path)(self, path_in); if (path[1] != '\0') { // Not at root, check it exists struct LFSx_API (info) info; int ret = LFSx_API(stat)(&self->lfs, path, &info); if (ret < 0 || info.type != LFSx_MACRO(_TYPE_DIR)) { mp_raise_OSError(-MP_ENOENT); } } // Update cur_dir with new path if (path == vstr_str(&self->cur_dir)) { self->cur_dir.len = strlen(path); } else { vstr_reset(&self->cur_dir); vstr_add_str(&self->cur_dir, path); } // If not at root add trailing / to make it easy to build paths // and then normalise the path if (vstr_len(&self->cur_dir) != 1) { vstr_add_byte(&self->cur_dir, '/'); #define CWD_LEN (vstr_len(&self->cur_dir)) size_t to = 1; size_t from = 1; char *cwd = vstr_str(&self->cur_dir); while (from < CWD_LEN) { for (; cwd[from] == '/' && from < CWD_LEN; ++from) { // Scan for the start } if (from > to) { // Found excessive slash chars, squeeze them out vstr_cut_out_bytes(&self->cur_dir, to, from - to); from = to; } for (; cwd[from] != '/' && from < CWD_LEN; ++from) { // Scan for the next / } if ((from - to) == 1 && cwd[to] == '.') { // './', ignore vstr_cut_out_bytes(&self->cur_dir, to, ++from - to); from = to; } else if ((from - to) == 2 && cwd[to] == '.' && cwd[to + 1] == '.') { // '../', skip back if (to > 1) { // Only skip back if not at the tip for (--to; to > 1 && cwd[to - 1] != '/'; --to) { // Skip back } } vstr_cut_out_bytes(&self->cur_dir, to, ++from - to); from = to; } else { // Normal element, keep it and just move the offset to = ++from; } } } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(chdir_obj), MP_VFS_LFSx(chdir)); STATIC mp_obj_t MP_VFS_LFSx(getcwd)(mp_obj_t self_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); if (vstr_len(&self->cur_dir) == 1) { return MP_OBJ_NEW_QSTR(MP_QSTR__slash_); } else { // don't include trailing / return mp_obj_new_str(self->cur_dir.buf, self->cur_dir.len - 1); } } STATIC MP_DEFINE_CONST_FUN_OBJ_1(MP_VFS_LFSx(getcwd_obj), MP_VFS_LFSx(getcwd)); STATIC mp_obj_t MP_VFS_LFSx(stat)(mp_obj_t self_in, mp_obj_t path_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); const char *path = MP_VFS_LFSx(make_path)(self, path_in); struct LFSx_API (info) info; int ret = LFSx_API(stat)(&self->lfs, path, &info); if (ret < 0) { mp_raise_OSError(-ret); } mp_uint_t mtime = 0; #if LFS_BUILD_VERSION == 2 uint8_t mtime_buf[8]; lfs2_ssize_t sz = lfs2_getattr(&self->lfs, path, LFS_ATTR_MTIME, &mtime_buf, sizeof(mtime_buf)); if (sz == sizeof(mtime_buf)) { uint64_t ns = 0; for (size_t i = sizeof(mtime_buf); i > 0; --i) { ns = ns << 8 | mtime_buf[i - 1]; } // On-disk storage of timestamps uses 1970 as the Epoch, so convert to host's Epoch. mtime = timeutils_seconds_since_epoch_from_nanoseconds_since_1970(ns); } #endif mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(info.type == LFSx_MACRO(_TYPE_REG) ? MP_S_IFREG : MP_S_IFDIR); // st_mode t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid t->items[6] = mp_obj_new_int_from_uint(info.size); // st_size t->items[7] = mp_obj_new_int_from_uint(mtime); // st_atime t->items[8] = mp_obj_new_int_from_uint(mtime); // st_mtime t->items[9] = mp_obj_new_int_from_uint(mtime); // st_ctime return MP_OBJ_FROM_PTR(t); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(stat_obj), MP_VFS_LFSx(stat)); STATIC int LFSx_API(traverse_cb)(void *data, LFSx_API(block_t) bl) { (void)bl; uint32_t *n = (uint32_t *)data; *n += 1; return LFSx_MACRO(_ERR_OK); } STATIC mp_obj_t MP_VFS_LFSx(statvfs)(mp_obj_t self_in, mp_obj_t path_in) { (void)path_in; MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); uint32_t n_used_blocks = 0; #if LFS_BUILD_VERSION == 1 int ret = LFSx_API(traverse)(&self->lfs, LFSx_API(traverse_cb), &n_used_blocks); #else int ret = LFSx_API(fs_traverse)(&self->lfs, LFSx_API(traverse_cb), &n_used_blocks); #endif if (ret < 0) { mp_raise_OSError(-ret); } mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(self->lfs.cfg->block_size); // f_bsize t->items[1] = t->items[0]; // f_frsize t->items[2] = MP_OBJ_NEW_SMALL_INT(self->lfs.cfg->block_count); // f_blocks t->items[3] = MP_OBJ_NEW_SMALL_INT(self->lfs.cfg->block_count - n_used_blocks); // f_bfree t->items[4] = t->items[3]; // f_bavail t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // f_files t->items[6] = MP_OBJ_NEW_SMALL_INT(0); // f_ffree t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // f_favail t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags t->items[9] = MP_OBJ_NEW_SMALL_INT(LFSx_MACRO(_NAME_MAX)); // f_namemax return MP_OBJ_FROM_PTR(t); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(statvfs_obj), MP_VFS_LFSx(statvfs)); STATIC mp_obj_t MP_VFS_LFSx(mount)(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); (void)mkfs; // Make block device read-only if requested. if (mp_obj_is_true(readonly)) { self->blockdev.writeblocks[0] = MP_OBJ_NULL; } // Already called LFSx_API(mount) in MP_VFS_LFSx(make_new) so the filesystem is ready. return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(MP_VFS_LFSx(mount_obj), MP_VFS_LFSx(mount)); STATIC mp_obj_t MP_VFS_LFSx(umount)(mp_obj_t self_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); // LFS unmount never fails LFSx_API(unmount)(&self->lfs); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(MP_VFS_LFSx(umount_obj), MP_VFS_LFSx(umount)); STATIC const mp_rom_map_elem_t MP_VFS_LFSx(locals_dict_table)[] = { { MP_ROM_QSTR(MP_QSTR_mkfs), MP_ROM_PTR(&MP_VFS_LFSx(mkfs_obj)) }, { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&MP_VFS_LFSx(open_obj)) }, { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&MP_VFS_LFSx(ilistdir_obj)) }, { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&MP_VFS_LFSx(mkdir_obj)) }, { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&MP_VFS_LFSx(rmdir_obj)) }, { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&MP_VFS_LFSx(chdir_obj)) }, { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&MP_VFS_LFSx(getcwd_obj)) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&MP_VFS_LFSx(remove_obj)) }, { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&MP_VFS_LFSx(rename_obj)) }, { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&MP_VFS_LFSx(stat_obj)) }, { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&MP_VFS_LFSx(statvfs_obj)) }, { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&MP_VFS_LFSx(mount_obj)) }, { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&MP_VFS_LFSx(umount_obj)) }, }; STATIC MP_DEFINE_CONST_DICT(MP_VFS_LFSx(locals_dict), MP_VFS_LFSx(locals_dict_table)); STATIC mp_import_stat_t MP_VFS_LFSx(import_stat)(void *self_in, const char *path) { MP_OBJ_VFS_LFSx *self = self_in; struct LFSx_API (info) info; mp_obj_str_t path_obj = { { &mp_type_str }, 0, 0, (const byte *)path }; path = MP_VFS_LFSx(make_path)(self, MP_OBJ_FROM_PTR(&path_obj)); int ret = LFSx_API(stat)(&self->lfs, path, &info); if (ret == 0) { if (info.type == LFSx_MACRO(_TYPE_REG)) { return MP_IMPORT_STAT_FILE; } else { return MP_IMPORT_STAT_DIR; } } return MP_IMPORT_STAT_NO_EXIST; } STATIC const mp_vfs_proto_t MP_VFS_LFSx(proto) = { .import_stat = MP_VFS_LFSx(import_stat), }; const mp_obj_type_t MP_TYPE_VFS_LFSx = { { &mp_type_type }, #if LFS_BUILD_VERSION == 1 .name = MP_QSTR_VfsLfs1, #else .name = MP_QSTR_VfsLfs2, #endif .make_new = MP_VFS_LFSx(make_new), .protocol = &MP_VFS_LFSx(proto), .locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(locals_dict), };
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_lfsx.c
C
apache-2.0
19,584
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2019-2020 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "py/mperrno.h" #include "extmod/vfs.h" STATIC void MP_VFS_LFSx(check_open)(MP_OBJ_VFS_LFSx_FILE * self) { if (self->vfs == NULL) { mp_raise_ValueError(NULL); } } STATIC void MP_VFS_LFSx(file_print)(const mp_print_t * print, mp_obj_t self_in, mp_print_kind_t kind) { (void)self_in; (void)kind; mp_printf(print, "<io.%s>", mp_obj_get_type_str(self_in)); } mp_obj_t MP_VFS_LFSx(file_open)(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); int flags = 0; const mp_obj_type_t *type = &MP_TYPE_VFS_LFSx_(_textio); const char *mode_str = mp_obj_str_get_str(mode_in); for (; *mode_str; ++mode_str) { int new_flags = 0; switch (*mode_str) { case 'r': new_flags = LFSx_MACRO(_O_RDONLY); break; case 'w': new_flags = LFSx_MACRO(_O_WRONLY) | LFSx_MACRO(_O_CREAT) | LFSx_MACRO(_O_TRUNC); break; case 'x': new_flags = LFSx_MACRO(_O_WRONLY) | LFSx_MACRO(_O_CREAT) | LFSx_MACRO(_O_EXCL); break; case 'a': new_flags = LFSx_MACRO(_O_WRONLY) | LFSx_MACRO(_O_CREAT) | LFSx_MACRO(_O_APPEND); break; case '+': flags |= LFSx_MACRO(_O_RDWR); break; #if MICROPY_PY_IO_FILEIO case 'b': type = &MP_TYPE_VFS_LFSx_(_fileio); break; #endif case 't': type = &MP_TYPE_VFS_LFSx_(_textio); break; } if (new_flags) { if (flags) { mp_raise_ValueError(NULL); } flags = new_flags; } } if (flags == 0) { flags = LFSx_MACRO(_O_RDONLY); } #if LFS_BUILD_VERSION == 1 MP_OBJ_VFS_LFSx_FILE *o = m_new_obj_var_with_finaliser(MP_OBJ_VFS_LFSx_FILE, uint8_t, self->lfs.cfg->prog_size); #else MP_OBJ_VFS_LFSx_FILE *o = m_new_obj_var_with_finaliser(MP_OBJ_VFS_LFSx_FILE, uint8_t, self->lfs.cfg->cache_size); #endif o->base.type = type; o->vfs = self; #if !MICROPY_GC_CONSERVATIVE_CLEAR memset(&o->file, 0, sizeof(o->file)); memset(&o->cfg, 0, sizeof(o->cfg)); #endif o->cfg.buffer = &o->file_buffer[0]; #if LFS_BUILD_VERSION == 2 if (self->enable_mtime) { lfs_get_mtime(&o->mtime[0]); o->attrs[0].type = LFS_ATTR_MTIME; o->attrs[0].buffer = &o->mtime[0]; o->attrs[0].size = sizeof(o->mtime); o->cfg.attrs = &o->attrs[0]; o->cfg.attr_count = MP_ARRAY_SIZE(o->attrs); } #endif const char *path = MP_VFS_LFSx(make_path)(self, path_in); int ret = LFSx_API(file_opencfg)(&self->lfs, &o->file, path, flags, &o->cfg); if (ret < 0) { o->vfs = NULL; mp_raise_OSError(-ret); } return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t MP_VFS_LFSx(file___exit__)(size_t n_args, const mp_obj_t *args) { (void)n_args; return mp_stream_close(args[0]); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(MP_VFS_LFSx(file___exit___obj), 4, 4, MP_VFS_LFSx(file___exit__)); STATIC mp_uint_t MP_VFS_LFSx(file_read)(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { MP_OBJ_VFS_LFSx_FILE *self = MP_OBJ_TO_PTR(self_in); MP_VFS_LFSx(check_open)(self); LFSx_API(ssize_t) sz = LFSx_API(file_read)(&self->vfs->lfs, &self->file, buf, size); if (sz < 0) { *errcode = -sz; return MP_STREAM_ERROR; } return sz; } STATIC mp_uint_t MP_VFS_LFSx(file_write)(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { MP_OBJ_VFS_LFSx_FILE *self = MP_OBJ_TO_PTR(self_in); MP_VFS_LFSx(check_open)(self); #if LFS_BUILD_VERSION == 2 if (self->vfs->enable_mtime) { lfs_get_mtime(&self->mtime[0]); } #endif LFSx_API(ssize_t) sz = LFSx_API(file_write)(&self->vfs->lfs, &self->file, buf, size); if (sz < 0) { *errcode = -sz; return MP_STREAM_ERROR; } return sz; } STATIC mp_uint_t MP_VFS_LFSx(file_ioctl)(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { MP_OBJ_VFS_LFSx_FILE *self = MP_OBJ_TO_PTR(self_in); if (request != MP_STREAM_CLOSE) { MP_VFS_LFSx(check_open)(self); } if (request == MP_STREAM_SEEK) { struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; int res = LFSx_API(file_seek)(&self->vfs->lfs, &self->file, s->offset, s->whence); if (res < 0) { *errcode = -res; return MP_STREAM_ERROR; } res = LFSx_API(file_tell)(&self->vfs->lfs, &self->file); if (res < 0) { *errcode = -res; return MP_STREAM_ERROR; } s->offset = res; return 0; } else if (request == MP_STREAM_FLUSH) { int res = LFSx_API(file_sync)(&self->vfs->lfs, &self->file); if (res < 0) { *errcode = -res; return MP_STREAM_ERROR; } return 0; } else if (request == MP_STREAM_CLOSE) { if (self->vfs == NULL) { return 0; } int res = LFSx_API(file_close)(&self->vfs->lfs, &self->file); self->vfs = NULL; // indicate a closed file if (res < 0) { *errcode = -res; return MP_STREAM_ERROR; } return 0; } else { *errcode = MP_EINVAL; return MP_STREAM_ERROR; } } STATIC const mp_rom_map_elem_t MP_VFS_LFSx(file_locals_dict_table)[] = { { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) }, { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) }, { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&MP_VFS_LFSx(file___exit___obj)) }, }; STATIC MP_DEFINE_CONST_DICT(MP_VFS_LFSx(file_locals_dict), MP_VFS_LFSx(file_locals_dict_table)); #if MICROPY_PY_IO_FILEIO STATIC const mp_stream_p_t MP_VFS_LFSx(fileio_stream_p) = { .read = MP_VFS_LFSx(file_read), .write = MP_VFS_LFSx(file_write), .ioctl = MP_VFS_LFSx(file_ioctl), }; const mp_obj_type_t MP_TYPE_VFS_LFSx_(_fileio) = { { &mp_type_type }, .name = MP_QSTR_FileIO, .print = MP_VFS_LFSx(file_print), .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &MP_VFS_LFSx(fileio_stream_p), .locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(file_locals_dict), }; #endif STATIC const mp_stream_p_t MP_VFS_LFSx(textio_stream_p) = { .read = MP_VFS_LFSx(file_read), .write = MP_VFS_LFSx(file_write), .ioctl = MP_VFS_LFSx(file_ioctl), .is_text = true, }; const mp_obj_type_t MP_TYPE_VFS_LFSx_(_textio) = { { &mp_type_type }, .name = MP_QSTR_TextIOWrapper, .print = MP_VFS_LFSx(file_print), .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &MP_VFS_LFSx(textio_stream_p), .locals_dict = (mp_obj_dict_t *)&MP_VFS_LFSx(file_locals_dict), };
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_lfsx_file.c
C
apache-2.0
8,995
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2017-2018 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/runtime.h" #include "py/mperrno.h" #include "py/mphal.h" #include "py/mpthread.h" #include "extmod/vfs.h" #include "extmod/vfs_posix.h" #if MICROPY_VFS_POSIX #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> typedef struct _mp_obj_vfs_posix_t { mp_obj_base_t base; vstr_t root; size_t root_len; bool readonly; } mp_obj_vfs_posix_t; static char g_mp_current_working_directory[256] = "/"; static char *mp_getcwd(char *buf, size_t size) { if (buf == NULL) { return NULL; } strncpy(buf, g_mp_current_working_directory, strlen(g_mp_current_working_directory) + 1); return buf; } static char g_mp_last_working_directory[512] = "/"; static int mp_up_one_level(char *abspath) { char *c, *last_slash; if (strcmp(abspath, "/") == 0) return -1; c = abspath + 1; last_slash = abspath; while (*c != '\0') { if ((*c == '/') && (*(c + 1) != '\0')) last_slash = c; c++; } *(last_slash + 1) = '\0'; return 0; } #define ROOT_DIR "/" static int mp_chdir(char *path) { char absolute[256] = {0}, *ret, *target, cwd_backup[256] = {0}; struct stat s; target = path; if (!target) { return -1; } ret = mp_getcwd(absolute, sizeof(absolute)); if (!ret) { return -1; } strncpy(cwd_backup, absolute, sizeof(cwd_backup)); if (target[0] != '/') { if (target[0] == '-') { memset(absolute, 0, sizeof(absolute)); strncpy(absolute, g_mp_last_working_directory, sizeof(absolute)); absolute[sizeof(absolute) - 1] = '\0'; goto check_and_cd; } if (absolute[strlen(absolute) - 1] != '/') { absolute[strlen(absolute)] = '/'; } // exclude heading "./" while (strncmp(target, "./", strlen("./")) == 0) { target += strlen("./"); while (target[0] == '/') target++; } // parse heading ".." while (target && strncmp(target, "..", strlen("..")) == 0) { if (mp_up_one_level(absolute) != 0) { return -1; } target += strlen(".."); while (target[0] == '/') target++; } if (target) strncpy(absolute + strlen(absolute), target, \ sizeof(absolute) - strlen(absolute)); } else { strncpy(absolute, target, sizeof(absolute)); } check_and_cd: if (stat(absolute, &s)) { return -1; } if (access(absolute, F_OK) != 0) { return -1; } if (!S_ISDIR(s.st_mode)) { return -1; } memset(g_mp_current_working_directory, 0, sizeof(g_mp_current_working_directory)); strncpy(g_mp_current_working_directory, absolute, strlen(absolute) + 1); memset(g_mp_last_working_directory, 0, sizeof(g_mp_last_working_directory)); strncpy(g_mp_last_working_directory, cwd_backup, sizeof(g_mp_last_working_directory)); return 0; } static int mp_get_cwd_dir(char *dir, size_t len) { char *ret; ret = mp_getcwd(dir, len); if (!ret) { return -1; } return 0; } static char *mp_get_realpath(const char *path, char *resolved_path, unsigned int len) { char *ret, *p = (char *)path, *r = resolved_path; if (!path || !r || len < 1) return NULL; memset(r, 0, len); // deal with heading char if (p[0] != '/') { // relative path ret = mp_getcwd(r, len); if (!ret) return NULL; // add tailing '/' if no if (r[strlen(r) - 1] != '/') { r[strlen(r)] = '/'; } r += strlen(r); } else { // absolute path r[0] = '/'; r++; } // iterate to exclude '.', '..'. '/' while (*p != '\0') { while (*p == '/') p++; if (*p == '\0') break; if (*p == '.') { p++; // end with '.' if (*p == '\0') break; if (*p == '.') { // '..' or '../' if ((*(p + 1) != '/') && (*(p + 1) != '\0')) { printf("Invalid path %s\r\n", path); return NULL; } else { // '..' case p++; // if (*p == '/') { if (mp_up_one_level(resolved_path) != 0) { printf("Failed to go up now. Invalid path %s\r\n", path); return NULL; } r = resolved_path + strlen(resolved_path); // } // end with '.' if (*p == '\0') { break; } } } else { if (*p == '/' || *p == '\0') { p++; } else { // '.xxx' might be hidden file or dir p--; goto copy_valid; } } } while (*p == '/') p++; if (*p == '\0') break; // if another round of ./.., just continue if (*p == '.') continue; copy_valid: // path string may be found now, save to r while ((*p != '/') && (*p != '\0')) *r++ = *p++; // add taling '/' if necessary if (*(r - 1) != '/') { *r++ = '/'; } } /** * considering "cd ../config" for tab key case, * we need set string EOF avoid out of control. */ *r = '\0'; // exclude the tailing '/', just in case it is a file if ((resolved_path[strlen(resolved_path) - 1] == '/') && (strlen(resolved_path) != 1)) { resolved_path[strlen(resolved_path) - 1] = '\0'; } return resolved_path; } static int mp_ls_predo(char *path, char *outpath, int size) { int index; bool curdir_available = true; char cur[256] = {0}; size_t curlen = 0; if (mp_get_cwd_dir(cur, sizeof(cur))) { curdir_available = false; } else { curlen = strlen(cur); } char *dir = path; char abspath[256] = {0}; dir = mp_get_realpath(dir, abspath, sizeof(abspath)); if (!dir) { return -1; } if (dir[0] != '/') { if (!curdir_available) { return -1; } // parse heading ".." while (dir && (strncmp(dir, "..", strlen(".."))) == 0) { if (mp_up_one_level(cur) != 0) { return -1; } curlen = strlen(cur); dir += strlen(".."); while (dir[0] == '/') dir++; } // deal with '.', './', './dir/file' cases if (dir && dir[0] == '.') { while (*(++dir) == '/') ; } if (dir) snprintf(cur + curlen, sizeof(cur) - curlen, "/%s", dir); curlen = strlen(cur); if (size >= curlen + 1) { strncpy(outpath, cur, curlen + 1); } else return -1; } else { curlen = strlen(dir); if (size >= curlen + 1) { strncpy(outpath, dir, curlen + 1); } else return -1; } return 0; } STATIC const char *vfs_posix_get_path_str(mp_obj_vfs_posix_t *self, mp_obj_t path) { if (self->root_len == 0) { return mp_obj_str_get_str(path); } else { self->root.len = self->root_len; vstr_add_str(&self->root, mp_obj_str_get_str(path)); return vstr_null_terminated_str(&self->root); } } STATIC mp_obj_t vfs_posix_get_path_obj(mp_obj_vfs_posix_t *self, mp_obj_t path) { if (self->root_len == 0) { return path; } else { self->root.len = self->root_len; vstr_add_str(&self->root, mp_obj_str_get_str(path)); return mp_obj_new_str(self->root.buf, self->root.len); } } STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char *)) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); int ret = f(vfs_posix_get_path_str(self, path_in)); if (ret != 0) { mp_raise_OSError(errno); } return mp_const_none; } STATIC mp_import_stat_t mp_vfs_posix_import_stat(void *self_in, const char *path) { mp_obj_vfs_posix_t *self = self_in; if (self->root_len != 0) { self->root.len = self->root_len; vstr_add_str(&self->root, path); path = vstr_null_terminated_str(&self->root); } struct stat st; if (stat(path, &st) == 0) { if (S_ISDIR(st.st_mode)) { return MP_IMPORT_STAT_DIR; } else if (S_ISREG(st.st_mode)) { return MP_IMPORT_STAT_FILE; } } return MP_IMPORT_STAT_NO_EXIST; } STATIC mp_obj_t vfs_posix_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_vfs_posix_t *vfs = m_new_obj(mp_obj_vfs_posix_t); vfs->base.type = type; vstr_init(&vfs->root, 0); if (n_args == 1) { vstr_add_str(&vfs->root, mp_obj_str_get_str(args[0])); vstr_add_char(&vfs->root, '/'); } vfs->root_len = vfs->root.len; vfs->readonly = false; return MP_OBJ_FROM_PTR(vfs); } STATIC mp_obj_t vfs_posix_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); if (mp_obj_is_true(readonly)) { self->readonly = true; } if (mp_obj_is_true(mkfs)) { mp_raise_OSError(MP_EPERM); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_posix_mount_obj, vfs_posix_mount); STATIC mp_obj_t vfs_posix_umount(mp_obj_t self_in) { (void)self_in; return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(vfs_posix_umount_obj, vfs_posix_umount); STATIC mp_obj_t vfs_posix_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *mode = mp_obj_str_get_str(mode_in); if (self->readonly && (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL || strchr(mode, '+') != NULL)) { mp_raise_OSError(MP_EROFS); } if (!mp_obj_is_small_int(path_in)) { path_in = vfs_posix_get_path_obj(self, path_in); } return mp_vfs_posix_file_open(&mp_type_textio, path_in, mode_in); } STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_posix_open_obj, vfs_posix_open); STATIC mp_obj_t vfs_posix_chdir(mp_obj_t self_in, mp_obj_t path_in) { return vfs_posix_fun1_helper(self_in, path_in, mp_chdir); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_chdir_obj, vfs_posix_chdir); STATIC mp_obj_t vfs_posix_getcwd(mp_obj_t self_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); char buf[MICROPY_ALLOC_PATH_MAX + 1]; const char *ret = mp_getcwd(buf, sizeof(buf)); if (ret == NULL) { mp_raise_OSError(errno); } ret += self->root_len; return mp_obj_new_str(ret, strlen(ret)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(vfs_posix_getcwd_obj, vfs_posix_getcwd); typedef struct _vfs_posix_iistdir_it_t { mp_obj_base_t base; mp_fun_1_t iternext; bool is_str; DIR *dir; } vfs_posix_ilistdir_it_t; STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { vfs_posix_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); if (self->dir == NULL) { return MP_OBJ_STOP_ITERATION; } for (;;) { MP_THREAD_GIL_EXIT(); struct dirent *dirent = readdir(self->dir); if (dirent == NULL) { closedir(self->dir); MP_THREAD_GIL_ENTER(); self->dir = NULL; return MP_OBJ_STOP_ITERATION; } MP_THREAD_GIL_ENTER(); const char *fn = dirent->d_name; if (fn[0] == '.' && (fn[1] == 0 || fn[1] == '.')) { // skip . and .. continue; } // make 3-tuple with info about this entry mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); if (self->is_str) { t->items[0] = mp_obj_new_str(fn, strlen(fn)); } else { t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } #ifdef _DIRENT_HAVE_D_TYPE #ifdef DTTOIF t->items[1] = MP_OBJ_NEW_SMALL_INT(DTTOIF(dirent->d_type)); #else if (dirent->d_type == DT_DIR) { t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); } else if (dirent->d_type == DT_REG) { t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); } else { t->items[1] = MP_OBJ_NEW_SMALL_INT(dirent->d_type); } #endif #else // DT_UNKNOWN should have 0 value on any reasonable system t->items[1] = MP_OBJ_NEW_SMALL_INT(0); #endif #ifdef _DIRENT_HAVE_D_INO t->items[2] = MP_OBJ_NEW_SMALL_INT(dirent->d_ino); #else t->items[2] = MP_OBJ_NEW_SMALL_INT(0); #endif return MP_OBJ_FROM_PTR(t); } } STATIC mp_obj_t vfs_posix_ilistdir(mp_obj_t self_in, mp_obj_t path_in) { static char tmp_path[512]; mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); vfs_posix_ilistdir_it_t *iter = m_new_obj(vfs_posix_ilistdir_it_t); iter->base.type = &mp_type_polymorph_iter; iter->iternext = vfs_posix_ilistdir_it_iternext; iter->is_str = mp_obj_get_type(path_in) == &mp_type_str; const char *path = vfs_posix_get_path_str(self, path_in); if (path[0] == '\0') { path = "."; } MP_THREAD_GIL_EXIT(); if (path[0] != '/') { int ret = 0; memset(tmp_path, 0, sizeof(tmp_path)); ret = mp_ls_predo(path, tmp_path, sizeof(tmp_path)); if (ret < 0) iter->dir = opendir(path); else iter->dir = opendir(tmp_path); } else { iter->dir = opendir(path); } MP_THREAD_GIL_ENTER(); if (iter->dir == NULL) { mp_raise_OSError(errno); } return MP_OBJ_FROM_PTR(iter); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_ilistdir_obj, vfs_posix_ilistdir); typedef struct _mp_obj_listdir_t { mp_obj_base_t base; mp_fun_1_t iternext; DIR *dir; } mp_obj_listdir_t; STATIC mp_obj_t vfs_posix_mkdir(mp_obj_t self_in, mp_obj_t path_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *path = vfs_posix_get_path_str(self, path_in); MP_THREAD_GIL_EXIT(); int ret = mkdir(path, 0777); MP_THREAD_GIL_ENTER(); if (ret != 0) { mp_raise_OSError(errno); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_mkdir_obj, vfs_posix_mkdir); STATIC mp_obj_t vfs_posix_remove(mp_obj_t self_in, mp_obj_t path_in) { return vfs_posix_fun1_helper(self_in, path_in, unlink); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_remove_obj, vfs_posix_remove); STATIC mp_obj_t vfs_posix_rename(mp_obj_t self_in, mp_obj_t old_path_in, mp_obj_t new_path_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *old_path = vfs_posix_get_path_str(self, old_path_in); const char *new_path = vfs_posix_get_path_str(self, new_path_in); MP_THREAD_GIL_EXIT(); int ret = rename(old_path, new_path); MP_THREAD_GIL_ENTER(); if (ret != 0) { mp_raise_OSError(errno); } return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_posix_rename_obj, vfs_posix_rename); STATIC mp_obj_t vfs_posix_rmdir(mp_obj_t self_in, mp_obj_t path_in) { return vfs_posix_fun1_helper(self_in, path_in, rmdir); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_rmdir_obj, vfs_posix_rmdir); STATIC mp_obj_t vfs_posix_stat(mp_obj_t self_in, mp_obj_t path_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); struct stat sb; const char *path = vfs_posix_get_path_str(self, path_in); int ret; MP_HAL_RETRY_SYSCALL(ret, stat(path, &sb), mp_raise_OSError(err)); mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(sb.st_mode); t->items[1] = mp_obj_new_int_from_uint(sb.st_ino); t->items[2] = mp_obj_new_int_from_uint(sb.st_dev); t->items[3] = mp_obj_new_int_from_uint(sb.st_nlink); t->items[4] = mp_obj_new_int_from_uint(sb.st_uid); t->items[5] = mp_obj_new_int_from_uint(sb.st_gid); t->items[6] = mp_obj_new_int_from_uint(sb.st_size); t->items[7] = mp_obj_new_int_from_uint(sb.st_atime); t->items[8] = mp_obj_new_int_from_uint(sb.st_mtime); t->items[9] = mp_obj_new_int_from_uint(sb.st_ctime); return MP_OBJ_FROM_PTR(t); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_stat_obj, vfs_posix_stat); // Modified bt HaaS begin // Add MICROPY_PY_HAAS_SPECIFIC #if USE_STATFS #include <sys/statfs.h> #define STRUCT_STATVFS struct statfs #define STATVFS statfs #define F_FAVAIL sb.f_ffree #define F_NAMEMAX sb.f_namelen STATIC mp_obj_t vfs_posix_statvfs(mp_obj_t self_in, mp_obj_t path_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); STRUCT_STATVFS sb; const char *path = vfs_posix_get_path_str(self, path_in); int ret; MP_HAL_RETRY_SYSCALL(ret, STATVFS(path, &sb), mp_raise_OSError(err)); mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(sb.f_bsize); t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // sb.f_frsize t->items[2] = MP_OBJ_NEW_SMALL_INT(sb.f_blocks); t->items[3] = MP_OBJ_NEW_SMALL_INT(sb.f_bfree); t->items[4] = MP_OBJ_NEW_SMALL_INT(sb.f_bavail); t->items[5] = MP_OBJ_NEW_SMALL_INT(sb.f_files); t->items[6] = MP_OBJ_NEW_SMALL_INT(sb.f_ffree); t->items[7] = MP_OBJ_NEW_SMALL_INT(F_FAVAIL); t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // F_FLAG t->items[9] = MP_OBJ_NEW_SMALL_INT(F_NAMEMAX); return MP_OBJ_FROM_PTR(t); } #else STATIC mp_obj_t vfs_posix_statvfs(mp_obj_t self_in, mp_obj_t path_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *path = vfs_posix_get_path_str(self, path_in); int ret; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(0); t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // sb.f_frsize t->items[2] = MP_OBJ_NEW_SMALL_INT(0); t->items[3] = MP_OBJ_NEW_SMALL_INT(0); t->items[4] = MP_OBJ_NEW_SMALL_INT(0); t->items[5] = MP_OBJ_NEW_SMALL_INT(0); t->items[6] = MP_OBJ_NEW_SMALL_INT(0); t->items[7] = MP_OBJ_NEW_SMALL_INT(0); t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // F_FLAG t->items[9] = MP_OBJ_NEW_SMALL_INT(0); return MP_OBJ_FROM_PTR(t); } #endif // Modified bt HaaS end STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_statvfs_obj, vfs_posix_statvfs); STATIC const mp_rom_map_elem_t vfs_posix_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_posix_mount_obj) }, { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&vfs_posix_umount_obj) }, { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&vfs_posix_open_obj) }, { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&vfs_posix_chdir_obj) }, { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&vfs_posix_getcwd_obj) }, { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&vfs_posix_ilistdir_obj) }, { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&vfs_posix_mkdir_obj) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&vfs_posix_remove_obj) }, { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&vfs_posix_rename_obj) }, { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&vfs_posix_rmdir_obj) }, { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&vfs_posix_stat_obj) }, { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&vfs_posix_statvfs_obj) }, }; STATIC MP_DEFINE_CONST_DICT(vfs_posix_locals_dict, vfs_posix_locals_dict_table); STATIC const mp_vfs_proto_t vfs_posix_proto = { .import_stat = mp_vfs_posix_import_stat, }; const mp_obj_type_t mp_type_vfs_posix = { { &mp_type_type }, .name = MP_QSTR_VfsPosix, .make_new = vfs_posix_make_new, .protocol = &vfs_posix_proto, .locals_dict = (mp_obj_dict_t *)&vfs_posix_locals_dict, }; #endif // MICROPY_VFS_POSIX
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_posix.c
C
apache-2.0
21,439
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2018 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_VFS_POSIX_H #define MICROPY_INCLUDED_EXTMOD_VFS_POSIX_H #include "py/lexer.h" #include "py/obj.h" extern const mp_obj_type_t mp_type_vfs_posix; extern const mp_obj_type_t mp_type_vfs_posix_fileio; extern const mp_obj_type_t mp_type_vfs_posix_textio; mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_obj_t mode_in); #endif // MICROPY_INCLUDED_EXTMOD_VFS_POSIX_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_posix.h
C
apache-2.0
1,653
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013-2018 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "py/mphal.h" #include "py/mpthread.h" #include "py/runtime.h" #include "py/stream.h" #include "extmod/vfs_posix.h" #if MICROPY_VFS_POSIX || MICROPY_VFS_POSIX_FILE #include <fcntl.h> #include <unistd.h> #ifdef _WIN32 #define fsync _commit #endif typedef struct _mp_obj_vfs_posix_file_t { mp_obj_base_t base; int fd; } mp_obj_vfs_posix_file_t; #ifdef MICROPY_CPYTHON_COMPAT STATIC void check_fd_is_open(const mp_obj_vfs_posix_file_t *o) { if (o->fd < 0) { mp_raise_ValueError(MP_ERROR_TEXT("I/O operation on closed file")); } } #else #define check_fd_is_open(o) #endif STATIC void vfs_posix_file_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_vfs_posix_file_t *self = MP_OBJ_TO_PTR(self_in); mp_printf(print, "<io.%s %d>", mp_obj_get_type_str(self_in), self->fd); } mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_obj_t mode_in) { mp_obj_vfs_posix_file_t *o = m_new_obj(mp_obj_vfs_posix_file_t); const char *mode_s = mp_obj_str_get_str(mode_in); int mode_rw = 0, mode_x = 0; while (*mode_s) { switch (*mode_s++) { case 'r': mode_rw = O_RDONLY; break; case 'w': mode_rw = O_WRONLY; mode_x = O_CREAT | O_TRUNC; break; case 'a': mode_rw = O_WRONLY; mode_x = O_CREAT | O_APPEND; break; case '+': mode_rw = O_RDWR; break; #if MICROPY_PY_IO_FILEIO // If we don't have io.FileIO, then files are in text mode implicitly case 'b': type = &mp_type_vfs_posix_fileio; break; case 't': type = &mp_type_vfs_posix_textio; break; #endif } } o->base.type = type; mp_obj_t fid = file_in; if (mp_obj_is_small_int(fid)) { o->fd = MP_OBJ_SMALL_INT_VALUE(fid); return MP_OBJ_FROM_PTR(o); } const char *fname = mp_obj_str_get_str(fid); int fd; MP_HAL_RETRY_SYSCALL(fd, open(fname, mode_x | mode_rw, 0644), mp_raise_OSError(err)); o->fd = fd; return MP_OBJ_FROM_PTR(o); } STATIC mp_obj_t vfs_posix_file_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_rom_obj = MP_ROM_NONE} }, { MP_QSTR_mode, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_QSTR(MP_QSTR_r)} }, }; mp_arg_val_t arg_vals[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, args, MP_ARRAY_SIZE(allowed_args), allowed_args, arg_vals); return mp_vfs_posix_file_open(type, arg_vals[0].u_obj, arg_vals[1].u_obj); } STATIC mp_obj_t vfs_posix_file_fileno(mp_obj_t self_in) { mp_obj_vfs_posix_file_t *self = MP_OBJ_TO_PTR(self_in); check_fd_is_open(self); return MP_OBJ_NEW_SMALL_INT(self->fd); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(vfs_posix_file_fileno_obj, vfs_posix_file_fileno); STATIC mp_obj_t vfs_posix_file___exit__(size_t n_args, const mp_obj_t *args) { (void)n_args; return mp_stream_close(args[0]); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(vfs_posix_file___exit___obj, 4, 4, vfs_posix_file___exit__); STATIC mp_uint_t vfs_posix_file_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { mp_obj_vfs_posix_file_t *o = MP_OBJ_TO_PTR(o_in); check_fd_is_open(o); ssize_t r; MP_HAL_RETRY_SYSCALL(r, read(o->fd, buf, size), { *errcode = err; return MP_STREAM_ERROR; }); return (mp_uint_t)r; } STATIC mp_uint_t vfs_posix_file_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { mp_obj_vfs_posix_file_t *o = MP_OBJ_TO_PTR(o_in); check_fd_is_open(o); #if MICROPY_PY_OS_DUPTERM if (o->fd <= STDERR_FILENO) { mp_hal_stdout_tx_strn(buf, size); return size; } #endif ssize_t r; MP_HAL_RETRY_SYSCALL(r, write(o->fd, buf, size), { *errcode = err; return MP_STREAM_ERROR; }); return (mp_uint_t)r; } STATIC mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_vfs_posix_file_t *o = MP_OBJ_TO_PTR(o_in); if (request != MP_STREAM_CLOSE) { check_fd_is_open(o); } switch (request) { case MP_STREAM_FLUSH: { int ret; MP_HAL_RETRY_SYSCALL(ret, fsync(o->fd), { if (err == EINVAL && (o->fd == STDIN_FILENO || o->fd == STDOUT_FILENO || o->fd == STDERR_FILENO)) { // fsync(stdin/stdout/stderr) may fail with EINVAL, but don't propagate that // error out. Because data is not buffered by us, and stdin/out/err.flush() // should just be a no-op. return 0; } *errcode = err; return MP_STREAM_ERROR; }); return 0; } case MP_STREAM_SEEK: { struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; MP_THREAD_GIL_EXIT(); off_t off = lseek(o->fd, s->offset, s->whence); MP_THREAD_GIL_ENTER(); if (off == (off_t)-1) { *errcode = errno; return MP_STREAM_ERROR; } s->offset = off; return 0; } case MP_STREAM_CLOSE: MP_THREAD_GIL_EXIT(); close(o->fd); MP_THREAD_GIL_ENTER(); #ifdef MICROPY_CPYTHON_COMPAT o->fd = -1; #endif return 0; case MP_STREAM_GET_FILENO: return o->fd; default: *errcode = EINVAL; return MP_STREAM_ERROR; } } STATIC const mp_rom_map_elem_t vfs_posix_rawfile_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_fileno), MP_ROM_PTR(&vfs_posix_file_fileno_obj) }, { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) }, { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) }, { MP_ROM_QSTR(MP_QSTR_flush), MP_ROM_PTR(&mp_stream_flush_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&vfs_posix_file___exit___obj) }, }; STATIC MP_DEFINE_CONST_DICT(vfs_posix_rawfile_locals_dict, vfs_posix_rawfile_locals_dict_table); #if MICROPY_PY_IO_FILEIO STATIC const mp_stream_p_t vfs_posix_fileio_stream_p = { .read = vfs_posix_file_read, .write = vfs_posix_file_write, .ioctl = vfs_posix_file_ioctl, }; const mp_obj_type_t mp_type_vfs_posix_fileio = { { &mp_type_type }, .name = MP_QSTR_FileIO, .print = vfs_posix_file_print, .make_new = vfs_posix_file_make_new, .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &vfs_posix_fileio_stream_p, .locals_dict = (mp_obj_dict_t *)&vfs_posix_rawfile_locals_dict, }; #endif STATIC const mp_stream_p_t vfs_posix_textio_stream_p = { .read = vfs_posix_file_read, .write = vfs_posix_file_write, .ioctl = vfs_posix_file_ioctl, .is_text = true, }; const mp_obj_type_t mp_type_vfs_posix_textio = { { &mp_type_type }, .name = MP_QSTR_TextIOWrapper, .print = vfs_posix_file_print, .make_new = vfs_posix_file_make_new, .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &vfs_posix_textio_stream_p, .locals_dict = (mp_obj_dict_t *)&vfs_posix_rawfile_locals_dict, }; /* const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO}; const mp_obj_vfs_posix_file_t mp_sys_stdout_obj = {{&mp_type_textio}, STDOUT_FILENO}; const mp_obj_vfs_posix_file_t mp_sys_stderr_obj = {{&mp_type_textio}, STDERR_FILENO}; */ #endif // MICROPY_VFS_POSIX || MICROPY_VFS_POSIX_FILE
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_posix_file.c
C
apache-2.0
9,679
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2013-2017 Damien P. George * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <stdio.h> #include <string.h> #include "py/runtime.h" #include "py/stream.h" #include "py/reader.h" #include "extmod/vfs.h" #if MICROPY_READER_VFS typedef struct _mp_reader_vfs_t { mp_obj_t file; uint16_t len; uint16_t pos; byte buf[24]; } mp_reader_vfs_t; STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) { mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data; if (reader->pos >= reader->len) { if (reader->len < sizeof(reader->buf)) { return MP_READER_EOF; } else { int errcode; reader->len = mp_stream_rw(reader->file, reader->buf, sizeof(reader->buf), &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); if (errcode != 0) { // TODO handle errors properly return MP_READER_EOF; } if (reader->len == 0) { return MP_READER_EOF; } reader->pos = 0; } } return reader->buf[reader->pos++]; } STATIC void mp_reader_vfs_close(void *data) { mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data; mp_stream_close(reader->file); m_del_obj(mp_reader_vfs_t, reader); } void mp_reader_new_file(mp_reader_t *reader, const char *filename) { mp_reader_vfs_t *rf = m_new_obj(mp_reader_vfs_t); mp_obj_t args[2] = { mp_obj_new_str(filename, strlen(filename)), MP_OBJ_NEW_QSTR(MP_QSTR_rb), }; rf->file = mp_vfs_open(MP_ARRAY_SIZE(args), &args[0], (mp_map_t *)&mp_const_empty_map); int errcode; rf->len = mp_stream_rw(rf->file, rf->buf, sizeof(rf->buf), &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); if (errcode != 0) { mp_raise_OSError(errcode); } rf->pos = 0; reader->data = rf; reader->readbyte = mp_reader_vfs_readbyte; reader->close = mp_reader_vfs_close; } #endif // MICROPY_READER_VFS
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/vfs_reader.c
C
apache-2.0
3,118
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "extmod/virtpin.h" int mp_virtual_pin_read(mp_obj_t pin) { mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin); mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol; return pin_p->ioctl(pin, MP_PIN_READ, 0, NULL); } void mp_virtual_pin_write(mp_obj_t pin, int value) { mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin); mp_pin_p_t *pin_p = (mp_pin_p_t *)s->type->protocol; pin_p->ioctl(pin, MP_PIN_WRITE, value, NULL); }
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/virtpin.c
C
apache-2.0
1,688
/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) * * Copyright (c) 2016 Paul Sokolovsky * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef MICROPY_INCLUDED_EXTMOD_VIRTPIN_H #define MICROPY_INCLUDED_EXTMOD_VIRTPIN_H #include "py/obj.h" #define MP_PIN_READ (1) #define MP_PIN_WRITE (2) #define MP_PIN_INPUT (3) #define MP_PIN_OUTPUT (4) // Pin protocol typedef struct _mp_pin_p_t { mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); } mp_pin_p_t; int mp_virtual_pin_read(mp_obj_t pin); void mp_virtual_pin_write(mp_obj_t pin, int value); // If a port exposes a Pin object, it's constructor should be like this mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args); #endif // MICROPY_INCLUDED_EXTMOD_VIRTPIN_H
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/virtpin.h
C
apache-2.0
1,893
freeze(".", ("webrepl.py", "webrepl_setup.py", "websocket_helper.py"))
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/webrepl/manifest.py
Python
apache-2.0
71
# This module should be imported from REPL, not run from command line. import socket import uos import network import uwebsocket import websocket_helper import _webrepl listen_s = None client_s = None def setup_conn(port, accept_handler): global listen_s listen_s = socket.socket() listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ai = socket.getaddrinfo("0.0.0.0", port) addr = ai[0][4] listen_s.bind(addr) listen_s.listen(1) if accept_handler: listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler) for i in (network.AP_IF, network.STA_IF): iface = network.WLAN(i) if iface.active(): print("WebREPL daemon started on ws://%s:%d" % (iface.ifconfig()[0], port)) return listen_s def accept_conn(listen_sock): global client_s cl, remote_addr = listen_sock.accept() prev = uos.dupterm(None) uos.dupterm(prev) if prev: print("\nConcurrent WebREPL connection from", remote_addr, "rejected") cl.close() return print("\nWebREPL connection from:", remote_addr) client_s = cl websocket_helper.server_handshake(cl) ws = uwebsocket.websocket(cl, True) ws = _webrepl._webrepl(ws) cl.setblocking(False) # notify REPL on socket incoming data (ESP32/ESP8266-only) if hasattr(uos, "dupterm_notify"): cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify) uos.dupterm(ws) def stop(): global listen_s, client_s uos.dupterm(None) if client_s: client_s.close() if listen_s: listen_s.close() def start(port=8266, password=None): stop() if password is None: try: import webrepl_cfg _webrepl.password(webrepl_cfg.PASS) setup_conn(port, accept_conn) print("Started webrepl in normal mode") except: print("WebREPL is not configured, run 'import webrepl_setup'") else: _webrepl.password(password) setup_conn(port, accept_conn) print("Started webrepl in manual override mode") def start_foreground(port=8266): stop() s = setup_conn(port, None) accept_conn(s)
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/webrepl/webrepl.py
Python
apache-2.0
2,186
import sys # import uos as os import os import machine RC = "./boot.py" CONFIG = "./webrepl_cfg.py" def input_choice(prompt, choices): while 1: resp = input(prompt) if resp in choices: return resp def getpass(prompt): return input(prompt) def input_pass(): while 1: passwd1 = getpass("New password (4-9 chars): ") if len(passwd1) < 4 or len(passwd1) > 9: print("Invalid password length") continue passwd2 = getpass("Confirm password: ") if passwd1 == passwd2: return passwd1 print("Passwords do not match") def exists(fname): try: with open(fname): pass return True except OSError: return False def get_daemon_status(): with open(RC) as f: for l in f: if "webrepl" in l: if l.startswith("#"): return False return True return None def change_daemon(action): LINES = ("import webrepl", "webrepl.start()") with open(RC) as old_f, open(RC + ".tmp", "w") as new_f: found = False for l in old_f: for patt in LINES: if patt in l: found = True if action and l.startswith("#"): l = l[1:] elif not action and not l.startswith("#"): l = "#" + l new_f.write(l) if not found: new_f.write("import webrepl\nwebrepl.start()\n") # FatFs rename() is not POSIX compliant, will raise OSError if # dest file exists. os.remove(RC) os.rename(RC + ".tmp", RC) def main(): status = get_daemon_status() print("WebREPL daemon auto-start status:", "enabled" if status else "disabled") print("\nWould you like to (E)nable or (D)isable it running on boot?") print("(Empty line to quit)") resp = input("> ").upper() if resp == "E": if exists(CONFIG): resp2 = input_choice( "Would you like to change WebREPL password? (y/n) ", ("y", "n", "") ) else: print("To enable WebREPL, you must set password for it") resp2 = "y" if resp2 == "y": passwd = input_pass() with open(CONFIG, "w") as f: f.write("PASS = %r\n" % passwd) if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status): print("No further action required") sys.exit() change_daemon(resp == "E") print("Changes will be activated after reboot") resp = input_choice("Would you like to reboot now? (y/n) ", ("y", "n", "")) if resp == "y": machine.reset() main()
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/webrepl/webrepl_setup.py
Python
apache-2.0
2,783
try: import usys as sys except ImportError: import sys try: import ubinascii as binascii except: import binascii try: import uhashlib as hashlib except: import hashlib DEBUG = 0 def server_handshake(sock): clr = sock.makefile("rwb", 0) l = clr.readline() # sys.stdout.write(repr(l)) webkey = None while 1: l = clr.readline() if not l: raise OSError("EOF in headers") if l == b"\r\n": break # sys.stdout.write(l) h, v = [x.strip() for x in l.split(b":", 1)] if DEBUG: print((h, v)) if h == b"Sec-WebSocket-Key": webkey = v if not webkey: raise OSError("Not a websocket request") if DEBUG: print("Sec-WebSocket-Key:", webkey, len(webkey)) d = hashlib.sha1(webkey) d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11") respkey = d.digest() respkey = binascii.b2a_base64(respkey)[:-1] if DEBUG: print("respkey:", respkey) sock.send( b"""\ HTTP/1.1 101 Switching Protocols\r Upgrade: websocket\r Connection: Upgrade\r Sec-WebSocket-Accept: """ ) sock.send(respkey) sock.send("\r\n\r\n") # Very simplified client handshake, works for MicroPython's # websocket server implementation, but probably not for other # servers. def client_handshake(sock): cl = sock.makefile("rwb", 0) cl.write( b"""\ GET / HTTP/1.1\r Host: echo.websocket.org\r Connection: Upgrade\r Upgrade: websocket\r Sec-WebSocket-Key: foo\r \r """ ) l = cl.readline() # print(l) while 1: l = cl.readline() if l == b"\r\n": break # sys.stdout.write(l)
YifuLiu/AliOS-Things
components/py_engine/engine/extmod/webrepl/websocket_helper.py
Python
apache-2.0
1,717
from __future__ import print_function import re import sys import platform if platform.python_version_tuple()[0] == '2': bytes_cons = lambda val, enc=None: bytearray(val) from htmlentitydefs import codepoint2name elif platform.python_version_tuple()[0] == '3': bytes_cons = bytes from html.entities import codepoint2name # end compatibility code # this must match the equivalent function in qstr.c def compute_hash(qstr, bytes_hash): hash = 5381 for b in qstr: hash = (hash * 33) ^ b # Make sure that valid hash is never zero, zero means "hash not computed" return (hash & ((1 << (8 * bytes_hash)) - 1)) or 1 def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): qbytes = bytes_cons(qstr, "utf8") qlen = len(qbytes) qhash = compute_hash(qbytes, cfg_bytes_hash) if all(32 <= ord(c) <= 126 and c != "\\" and c != '"' for c in qstr): # qstr is all printable ASCII so render it as-is (for easier debugging) qdata = qstr else: # qstr contains non-printable codes so render entire thing as hex pairs qdata = "".join(("\\x%02x" % b) for b in qbytes) if qlen >= (1 << (8 * cfg_bytes_len)): print("qstr is too long:", qstr) assert False qlen_str = ("\\x%02x" * cfg_bytes_len) % tuple( ((qlen >> (8 * i)) & 0xFF) for i in range(cfg_bytes_len) ) qhash_str = ("\\x%02x" * cfg_bytes_hash) % tuple( ((qhash >> (8 * i)) & 0xFF) for i in range(cfg_bytes_hash) ) return 'QDEF(MP_QSTR_%s, (const byte *)"%s%s" "%s")' % (qdata, qhash_str, qlen_str, qdata) if __name__ == "__main__": BYTES_IN_LEN = 1 #MICROPY_QSTR_BYTES_IN_LEN BYTES_IN_HASH = 2 #MICROPY_QSTR_BYTES_IN_HASH print ("Gen qstr for micropython with:") print ("BYTES_IN_LEN = %d" % BYTES_IN_LEN) print ("BYTES_IN_HASH = %d" % BYTES_IN_HASH) for arg in sys.argv: if arg == 'gen_qstr.py': continue qstr_computer = make_bytes(BYTES_IN_LEN, BYTES_IN_HASH, arg) print (qstr_computer)
YifuLiu/AliOS-Things
components/py_engine/engine/genhdr/gen_qstr.py
Python
apache-2.0
2,037
# @(#)Makefile.inc 8.2 (Berkeley) 2/21/94 # CFLAGS+=-D__DBINTERFACE_PRIVATE .include "${.CURDIR}/db/btree/Makefile.inc" .include "${.CURDIR}/db/db/Makefile.inc" .include "${.CURDIR}/db/hash/Makefile.inc" .include "${.CURDIR}/db/man/Makefile.inc" .include "${.CURDIR}/db/mpool/Makefile.inc" .include "${.CURDIR}/db/recno/Makefile.inc"
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/Makefile.inc
Makefile
apache-2.0
335
# @(#)Makefile 8.9 (Berkeley) 7/14/94 LIBDB= libdb.a OBJ1= hash.o hash_bigkey.o hash_buf.o hash_func.o hash_log2.o hash_page.o \ hsearch.o ndbm.o OBJ2= bt_close.o bt_conv.o bt_debug.o bt_delete.o bt_get.o bt_open.o \ bt_overflow.o bt_page.o bt_put.o bt_search.o bt_seq.o bt_split.o \ bt_utils.o OBJ3= db.o OBJ4= mpool.o OBJ5= rec_close.o rec_delete.o rec_get.o rec_open.o rec_put.o rec_search.o \ rec_seq.o rec_utils.o MISC= ${LIBDB}: ${OBJ1} ${OBJ2} ${OBJ3} ${OBJ4} ${OBJ5} ${MISC} rm -f $@ ar cq $@ \ `lorder ${OBJ1} ${OBJ2} ${OBJ3} ${OBJ4} ${OBJ5} ${MISC} | tsort` ranlib $@ clean: rm -f ${LIBDB} ${OBJ1} ${OBJ2} ${OBJ3} ${OBJ4} ${OBJ5} ${MISC} OORG= -O CL= ${CC} -c -D__DBINTERFACE_PRIVATE ${OORG} -I. -Iinclude hash.o: ../../hash/hash.c ${CL} -I../../hash ../../hash/hash.c hash_bigkey.o: ../../hash/hash_bigkey.c ${CL} -I../../hash ../../hash/hash_bigkey.c hash_buf.o: ../../hash/hash_buf.c ${CL} -I../../hash ../../hash/hash_buf.c hash_func.o: ../../hash/hash_func.c ${CL} -I../../hash ../../hash/hash_func.c hash_log2.o: ../../hash/hash_log2.c ${CL} -I../../hash ../../hash/hash_log2.c hash_page.o: ../../hash/hash_page.c ${CL} -I../../hash ../../hash/hash_page.c hsearch.o: ../../hash/hsearch.c ${CL} -I../../hash ../../hash/hsearch.c ndbm.o: ../../hash/ndbm.c ${CL} -I../../hash ../../hash/ndbm.c bt_close.o: ../../btree/bt_close.c ${CL} -I../../btree ../../btree/bt_close.c bt_conv.o: ../../btree/bt_conv.c ${CL} -I../../btree ../../btree/bt_conv.c bt_debug.o: ../../btree/bt_debug.c ${CL} -I../../btree ../../btree/bt_debug.c bt_delete.o: ../../btree/bt_delete.c ${CL} -I../../btree ../../btree/bt_delete.c bt_get.o: ../../btree/bt_get.c ${CL} -I../../btree ../../btree/bt_get.c bt_open.o: ../../btree/bt_open.c ${CL} -I../../btree ../../btree/bt_open.c bt_overflow.o: ../../btree/bt_overflow.c ${CL} -I../../btree ../../btree/bt_overflow.c bt_page.o: ../../btree/bt_page.c ${CL} -I../../btree ../../btree/bt_page.c bt_put.o: ../../btree/bt_put.c ${CL} -I../../btree ../../btree/bt_put.c bt_search.o: ../../btree/bt_search.c ${CL} -I../../btree ../../btree/bt_search.c bt_seq.o: ../../btree/bt_seq.c ${CL} -I../../btree ../../btree/bt_seq.c bt_split.o: ../../btree/bt_split.c ${CL} -I../../btree ../../btree/bt_split.c bt_stack.o: ../../btree/bt_stack.c ${CL} -I../../btree ../../btree/bt_stack.c bt_utils.o: ../../btree/bt_utils.c ${CL} -I../../btree ../../btree/bt_utils.c db.o: ../../db/db.c ${CL} ../../db/db.c mpool.o: ../../mpool/mpool.c ${CL} -I../../mpool ../../mpool/mpool.c rec_close.o: ../../recno/rec_close.c ${CL} -I../../recno ../../recno/rec_close.c rec_delete.o: ../../recno/rec_delete.c ${CL} -I../../recno ../../recno/rec_delete.c rec_get.o: ../../recno/rec_get.c ${CL} -I../../recno ../../recno/rec_get.c rec_open.o: ../../recno/rec_open.c ${CL} -I../../recno ../../recno/rec_open.c rec_put.o: ../../recno/rec_put.c ${CL} -I../../recno ../../recno/rec_put.c rec_search.o: ../../recno/rec_search.c ${CL} -I../../recno ../../recno/rec_search.c rec_seq.o: ../../recno/rec_seq.c ${CL} -I../../recno ../../recno/rec_seq.c rec_utils.o: ../../recno/rec_utils.c ${CL} -I../../recno ../../recno/rec_utils.c memmove.o: ${CC} -DMEMMOVE -c -O -I. -Iinclude clib/memmove.c mktemp.o: ${CC} -c -O -I. -Iinclude clib/mktemp.c snprintf.o: ${CC} -c -O -I. -Iinclude clib/snprintf.c
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/Makefile
Makefile
apache-2.0
3,354
# @(#)Makefile 8.9 (Berkeley) 7/14/94 LIBDB= libdb.a OBJ1= hash.o hash_bigkey.o hash_buf.o hash_func.o hash_log2.o hash_page.o \ hsearch.o ndbm.o OBJ2= bt_close.o bt_conv.o bt_debug.o bt_delete.o bt_get.o bt_open.o \ bt_overflow.o bt_page.o bt_put.o bt_search.o bt_seq.o bt_split.o \ bt_utils.o OBJ3= db.o OBJ4= mpool.o OBJ5= rec_close.o rec_delete.o rec_get.o rec_open.o rec_put.o rec_search.o \ rec_seq.o rec_utils.o MISC= snprintf.o ${LIBDB}: ${OBJ1} ${OBJ2} ${OBJ3} ${OBJ4} ${OBJ5} ${MISC} rm -f $@ ar cq $@ \ `lorder ${OBJ1} ${OBJ2} ${OBJ3} ${OBJ4} ${OBJ5} ${MISC} | tsort` ranlib $@ clean: rm -f ${LIBDB} ${OBJ1} ${OBJ2} ${OBJ3} ${OBJ4} ${OBJ5} ${MISC} OORG= -O CL= ${CC} -c -D__DBINTERFACE_PRIVATE ${OORG} -I. -Iinclude hash.o: ../../hash/hash.c ${CL} -I../../hash ../../hash/hash.c hash_bigkey.o: ../../hash/hash_bigkey.c ${CL} -I../../hash ../../hash/hash_bigkey.c hash_buf.o: ../../hash/hash_buf.c ${CL} -I../../hash ../../hash/hash_buf.c hash_func.o: ../../hash/hash_func.c ${CL} -I../../hash ../../hash/hash_func.c hash_log2.o: ../../hash/hash_log2.c ${CL} -I../../hash ../../hash/hash_log2.c hash_page.o: ../../hash/hash_page.c ${CL} -I../../hash ../../hash/hash_page.c hsearch.o: ../../hash/hsearch.c ${CL} -I../../hash ../../hash/hsearch.c ndbm.o: ../../hash/ndbm.c ${CL} -I../../hash ../../hash/ndbm.c bt_close.o: ../../btree/bt_close.c ${CL} -I../../btree ../../btree/bt_close.c bt_conv.o: ../../btree/bt_conv.c ${CL} -I../../btree ../../btree/bt_conv.c bt_debug.o: ../../btree/bt_debug.c ${CL} -I../../btree ../../btree/bt_debug.c bt_delete.o: ../../btree/bt_delete.c ${CL} -I../../btree ../../btree/bt_delete.c bt_get.o: ../../btree/bt_get.c ${CL} -I../../btree ../../btree/bt_get.c bt_open.o: ../../btree/bt_open.c ${CL} -I../../btree ../../btree/bt_open.c bt_overflow.o: ../../btree/bt_overflow.c ${CL} -I../../btree ../../btree/bt_overflow.c bt_page.o: ../../btree/bt_page.c ${CL} -I../../btree ../../btree/bt_page.c bt_put.o: ../../btree/bt_put.c ${CL} -I../../btree ../../btree/bt_put.c bt_search.o: ../../btree/bt_search.c ${CL} -I../../btree ../../btree/bt_search.c bt_seq.o: ../../btree/bt_seq.c ${CL} -I../../btree ../../btree/bt_seq.c bt_split.o: ../../btree/bt_split.c ${CL} -I../../btree ../../btree/bt_split.c bt_stack.o: ../../btree/bt_stack.c ${CL} -I../../btree ../../btree/bt_stack.c bt_utils.o: ../../btree/bt_utils.c ${CL} -I../../btree ../../btree/bt_utils.c db.o: ../../db/db.c ${CL} ../../db/db.c mpool.o: ../../mpool/mpool.c ${CL} -I../../mpool ../../mpool/mpool.c rec_close.o: ../../recno/rec_close.c ${CL} -I../../recno ../../recno/rec_close.c rec_delete.o: ../../recno/rec_delete.c ${CL} -I../../recno ../../recno/rec_delete.c rec_get.o: ../../recno/rec_get.c ${CL} -I../../recno ../../recno/rec_get.c rec_open.o: ../../recno/rec_open.c ${CL} -I../../recno ../../recno/rec_open.c rec_put.o: ../../recno/rec_put.c ${CL} -I../../recno ../../recno/rec_put.c rec_search.o: ../../recno/rec_search.c ${CL} -I../../recno ../../recno/rec_search.c rec_seq.o: ../../recno/rec_seq.c ${CL} -I../../recno ../../recno/rec_seq.c rec_utils.o: ../../recno/rec_utils.c ${CL} -I../../recno ../../recno/rec_utils.c memmove.o: ${CC} -DMEMMOVE -c -O -I. -Iinclude clib/memmove.c mktemp.o: ${CC} -c -O -I. -Iinclude clib/mktemp.c snprintf.o: ${CC} -c -O -I. -Iinclude clib/snprintf.c
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/Makefile
Makefile
apache-2.0
3,365
../../include/cdefs.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/include/cdefs.h
C
apache-2.0
21
/*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)compat.h 8.13 (Berkeley) 2/21/94 */ #ifndef _COMPAT_H_ #define _COMPAT_H_ #include <sys/types.h> /* * If your system doesn't typedef u_long, u_short, or u_char, change * the 0 to a 1. */ #if 0 typedef unsigned char u_char; /* 4.[34]BSD names. */ typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned short u_short; #endif /* If your system doesn't typedef size_t, change the 0 to a 1. */ #if 0 typedef unsigned int size_t; /* POSIX, 4.[34]BSD names. */ #endif /* If your system doesn't typedef ssize_t, change the 0 to a 1. */ #if 0 typedef int ssize_t; /* POSIX names. */ #endif /* * If your system doesn't have the POSIX type for a signal mask, * change the 0 to a 1. */ #if 0 /* POSIX 1003.1 signal mask type. */ typedef unsigned int sigset_t; #endif /* * If your system's vsprintf returns a char *, not an int, * change the 0 to a 1. */ #if 0 #define VSPRINTF_CHARSTAR #endif /* * If you don't have POSIX 1003.1 signals, the signal code surrounding the * temporary file creation is intended to block all of the possible signals * long enough to create the file and unlink it. All of this stuff is * intended to use old-style BSD calls to fake POSIX 1003.1 calls. */ #ifdef NO_POSIX_SIGNALS #define sigemptyset(set) (*(set) = 0) #define sigfillset(set) (*(set) = ~(sigset_t)0, 0) #define sigaddset(set,signo) (*(set) |= sigmask(signo), 0) #define sigdelset(set,signo) (*(set) &= ~sigmask(signo), 0) #define sigismember(set,signo) ((*(set) & sigmask(signo)) != 0) #define SIG_BLOCK 1 #define SIG_UNBLOCK 2 #define SIG_SETMASK 3 static int __sigtemp; /* For the use of sigprocmask */ /* Repeated test of oset != NULL is to avoid "*0". */ #define sigprocmask(how, set, oset) \ ((__sigtemp = \ (((how) == SIG_BLOCK) ? \ sigblock(0) | *(set) : \ (((how) == SIG_UNBLOCK) ? \ sigblock(0) & ~(*(set)) : \ ((how) == SIG_SETMASK ? \ *(set) : sigblock(0))))), \ ((oset) ? (*(oset ? oset : set) = sigsetmask(__sigtemp)) : \ sigsetmask(__sigtemp)), 0) #endif /* * If your system doesn't have an include file with the appropriate * byte order set, make sure you specify the correct one. */ #ifndef BYTE_ORDER #define LITTLE_ENDIAN 1234 /* LSB first: i386, vax */ #define BIG_ENDIAN 4321 /* MSB first: 68000, ibm, net */ #define BYTE_ORDER BIG_ENDIAN /* Set for your system. */ #endif #if defined(SYSV) || defined(SYSTEM5) #define index(a, b) strchr(a, b) #define rindex(a, b) strrchr(a, b) #define bzero(a, b) memset(a, 0, b) #define bcmp(a, b, n) memcmp(a, b, n) #define bcopy(a, b, n) memmove(b, a, n) #endif #if defined(BSD) || defined(BSD4_3) #define strchr(a, b) index(a, b) #define strrchr(a, b) rindex(a, b) #define memcmp(a, b, n) bcmp(a, b, n) #define memmove(a, b, n) bcopy(b, a, n) #endif /* * 32-bit machine. The db routines are theoretically independent of * the size of u_shorts and u_longs, but I don't know that anyone has * ever actually tried it. At a minimum, change the following #define's * if you are trying to compile on a different type of system. */ #ifndef USHRT_MAX #define USHRT_MAX 0xFFFF #define ULONG_MAX 0xFFFFFFFF #endif #ifndef O_ACCMODE /* POSIX 1003.1 access mode mask. */ #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR) #endif #ifndef _POSIX2_RE_DUP_MAX /* POSIX 1003.2 RE limit. */ #define _POSIX2_RE_DUP_MAX 255 #endif /* * If you can't provide lock values in the open(2) call. Note, this * allows races to happen. */ #ifndef O_EXLOCK /* 4.4BSD extension. */ #define O_EXLOCK 0 #endif #ifndef O_SHLOCK /* 4.4BSD extension. */ #define O_SHLOCK 0 #endif #ifndef EFTYPE #define EFTYPE EINVAL /* POSIX 1003.1 format errno. */ #endif #ifndef WCOREDUMP /* 4.4BSD extension */ #define WCOREDUMP(a) 0 #endif #ifndef STDERR_FILENO #define STDIN_FILENO 0 /* ANSI C #defines */ #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #ifndef SEEK_END #define SEEK_SET 0 /* POSIX 1003.1 seek values */ #define SEEK_CUR 1 #define SEEK_END 2 #endif #ifndef _POSIX_VDISABLE /* POSIX 1003.1 disabling char. */ #define _POSIX_VDISABLE 0 /* Some systems used 0. */ #endif #ifndef TCSASOFT /* 4.4BSD extension. */ #define TCSASOFT 0 #endif #ifndef _POSIX2_RE_DUP_MAX /* POSIX 1003.2 values. */ #define _POSIX2_RE_DUP_MAX 255 #endif #ifndef NULL /* ANSI C #defines NULL everywhere. */ #define NULL 0 #endif #ifndef MAX /* Usually found in <sys/param.h>. */ #define MAX(_a,_b) ((_a)<(_b)?(_b):(_a)) #endif #ifndef MIN /* Usually found in <sys/param.h>. */ #define MIN(_a,_b) ((_a)<(_b)?(_a):(_b)) #endif /* Default file permissions. */ #ifndef DEFFILEMODE /* 4.4BSD extension. */ #define DEFFILEMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) #endif #ifndef S_ISDIR /* POSIX 1003.1 file type tests. */ #define S_ISDIR(m) ((m & 0170000) == 0040000) /* directory */ #define S_ISCHR(m) ((m & 0170000) == 0020000) /* char special */ #define S_ISBLK(m) ((m & 0170000) == 0060000) /* block special */ #define S_ISREG(m) ((m & 0170000) == 0100000) /* regular file */ #define S_ISFIFO(m) ((m & 0170000) == 0010000) /* fifo */ #endif #ifndef S_ISLNK /* BSD POSIX 1003.1 extensions */ #define S_ISLNK(m) ((m & 0170000) == 0120000) /* symbolic link */ #define S_ISSOCK(m) ((m & 0170000) == 0140000) /* socket */ #endif /* The type of a va_list. */ #ifndef _BSD_VA_LIST_ /* 4.4BSD #define. */ #define _BSD_VA_LIST_ char * #endif #endif /* !_COMPAT_H_ */
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/include/compat.h
C
apache-2.0
7,281
../../include/db.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/include/db.h
C
apache-2.0
18
../../include/mpool.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/include/mpool.h
C
apache-2.0
21
../../include/ndbm.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/include/ndbm.h
C
apache-2.0
20
../../include/queue.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/aix.3.2/include/queue.h
C
apache-2.0
21
../Makefile
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/Makefile
Makefile
apache-2.0
11
../../include/cdefs.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/include/cdefs.h
C
apache-2.0
21
../../include/compat.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/include/compat.h
C
apache-2.0
22
/*- * Copyright (c) 1990, 1993, 1994 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)db.h 8.6 (Berkeley) 6/16/94 */ #ifndef _DB_H_ #define _DB_H_ #include <sys/types.h> #include <sys/cdefs.h> #include <limits.h> #ifdef __DBINTERFACE_PRIVATE #include <compat.h> #endif #define RET_ERROR -1 /* Return values. */ #define RET_SUCCESS 0 #define RET_SPECIAL 1 #define MAX_PAGE_NUMBER 0xffffffff /* >= # of pages in a file */ typedef u_int32_t pgno_t; #define MAX_PAGE_OFFSET 65535 /* >= # of bytes in a page */ typedef u_int16_t indx_t; #define MAX_REC_NUMBER 0xffffffff /* >= # of records in a tree */ typedef u_int32_t recno_t; /* Key/data structure -- a Data-Base Thang. */ typedef struct { void *data; /* data */ size_t size; /* data length */ } DBT; /* Routine flags. */ #define R_CURSOR 1 /* del, put, seq */ #define __R_UNUSED 2 /* UNUSED */ #define R_FIRST 3 /* seq */ #define R_IAFTER 4 /* put (RECNO) */ #define R_IBEFORE 5 /* put (RECNO) */ #define R_LAST 6 /* seq (BTREE, RECNO) */ #define R_NEXT 7 /* seq */ #define R_NOOVERWRITE 8 /* put */ #define R_PREV 9 /* seq (BTREE, RECNO) */ #define R_SETCURSOR 10 /* put (RECNO) */ #define R_RECNOSYNC 11 /* sync (RECNO) */ typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE; /* * !!! * The following flags are included in the dbopen(3) call as part of the * open(2) flags. In order to avoid conflicts with the open flags, start * at the top of the 16 or 32-bit number space and work our way down. If * the open flags were significantly expanded in the future, it could be * a problem. Wish I'd left another flags word in the dbopen call. * * !!! * None of this stuff is implemented yet. The only reason that it's here * is so that the access methods can skip copying the key/data pair when * the DB_LOCK flag isn't set. */ #if UINT_MAX > 65535 #define DB_LOCK 0x20000000 /* Do locking. */ #define DB_SHMEM 0x40000000 /* Use shared memory. */ #define DB_TXN 0x80000000 /* Do transactions. */ #else #define DB_LOCK 0x2000 /* Do locking. */ #define DB_SHMEM 0x4000 /* Use shared memory. */ #define DB_TXN 0x8000 /* Do transactions. */ #endif /* Access method description structure. */ typedef struct __db { DBTYPE type; /* Underlying db type. */ int (*close) __P((struct __db *)); int (*del) __P((const struct __db *, const DBT *, u_int)); int (*get) __P((const struct __db *, const DBT *, DBT *, u_int)); int (*put) __P((const struct __db *, DBT *, const DBT *, u_int)); int (*seq) __P((const struct __db *, DBT *, DBT *, u_int)); int (*sync) __P((const struct __db *, u_int)); void *internal; /* Access method private. */ int (*fd) __P((const struct __db *)); } DB; #define BTREEMAGIC 0x053162 #define BTREEVERSION 3 /* Structure used to pass parameters to the btree routines. */ typedef struct { #define R_DUP 0x01 /* duplicate keys */ u_long flags; u_int cachesize; /* bytes to cache */ int maxkeypage; /* maximum keys per page */ int minkeypage; /* minimum keys per page */ u_int psize; /* page size */ int (*compare) /* comparison function */ __P((const DBT *, const DBT *)); size_t (*prefix) /* prefix function */ __P((const DBT *, const DBT *)); int lorder; /* byte order */ } BTREEINFO; #define HASHMAGIC 0x061561 #define HASHVERSION 2 /* Structure used to pass parameters to the hashing routines. */ typedef struct { u_int bsize; /* bucket size */ u_int ffactor; /* fill factor */ u_int nelem; /* number of elements */ u_int cachesize; /* bytes to cache */ u_int32_t /* hash function */ (*hash) __P((const void *, size_t)); int lorder; /* byte order */ } HASHINFO; /* Structure used to pass parameters to the record routines. */ typedef struct { #define R_FIXEDLEN 0x01 /* fixed-length records */ #define R_NOKEY 0x02 /* key not required */ #define R_SNAPSHOT 0x04 /* snapshot the input */ u_long flags; u_int cachesize; /* bytes to cache */ u_int psize; /* page size */ int lorder; /* byte order */ size_t reclen; /* record length (fixed-length records) */ u_char bval; /* delimiting byte (variable-length records */ char *bfname; /* btree file name */ } RECNOINFO; #ifdef __DBINTERFACE_PRIVATE /* * Little endian <==> big endian 32-bit swap macros. * M_32_SWAP swap a memory location * P_32_SWAP swap a referenced memory location * P_32_COPY swap from one location to another */ #define M_32_SWAP(a) { \ u_int32_t _tmp = a; \ ((char *)&a)[0] = ((char *)&_tmp)[3]; \ ((char *)&a)[1] = ((char *)&_tmp)[2]; \ ((char *)&a)[2] = ((char *)&_tmp)[1]; \ ((char *)&a)[3] = ((char *)&_tmp)[0]; \ } #define P_32_SWAP(a) { \ u_int32_t _tmp = *(u_int32_t *)a; \ ((char *)a)[0] = ((char *)&_tmp)[3]; \ ((char *)a)[1] = ((char *)&_tmp)[2]; \ ((char *)a)[2] = ((char *)&_tmp)[1]; \ ((char *)a)[3] = ((char *)&_tmp)[0]; \ } #define P_32_COPY(a, b) { \ ((char *)&(b))[0] = ((char *)&(a))[3]; \ ((char *)&(b))[1] = ((char *)&(a))[2]; \ ((char *)&(b))[2] = ((char *)&(a))[1]; \ ((char *)&(b))[3] = ((char *)&(a))[0]; \ } /* * Little endian <==> big endian 16-bit swap macros. * M_16_SWAP swap a memory location * P_16_SWAP swap a referenced memory location * P_16_COPY swap from one location to another */ #define M_16_SWAP(a) { \ u_int16_t _tmp = a; \ ((char *)&a)[0] = ((char *)&_tmp)[1]; \ ((char *)&a)[1] = ((char *)&_tmp)[0]; \ } #define P_16_SWAP(a) { \ u_int16_t _tmp = *(u_int16_t *)a; \ ((char *)a)[0] = ((char *)&_tmp)[1]; \ ((char *)a)[1] = ((char *)&_tmp)[0]; \ } #define P_16_COPY(a, b) { \ ((char *)&(b))[0] = ((char *)&(a))[1]; \ ((char *)&(b))[1] = ((char *)&(a))[0]; \ } #endif __BEGIN_DECLS DB *dbopen __P((const char *, int, int, DBTYPE, const void *)); #ifdef __DBINTERFACE_PRIVATE DB *__bt_open __P((const char *, int, int, const BTREEINFO *, int)); DB *__hash_open __P((const char *, int, int, const HASHINFO *, int)); DB *__rec_open __P((const char *, int, int, const RECNOINFO *, int)); void __dbpanic __P((DB *dbp)); #endif __END_DECLS #endif /* !_DB_H_ */
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/include/db.h
C
apache-2.0
7,857
../../include/mpool.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/include/mpool.h
C
apache-2.0
21
../../include/ndbm.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/include/ndbm.h
C
apache-2.0
20
../../include/queue.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsd.4.4/include/queue.h
C
apache-2.0
21
../Makefile
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/Makefile
Makefile
apache-2.0
11
/*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)assert.h 4.4 (Berkeley) 4/3/91 */ #ifndef _ASSERT_H_ #define _ASSERT_H_ #ifdef NDEBUG #define assert(expression) #define _assert(expression) #else #define assert(expression) { \ if (!(expression)) { \ (void)fprintf(stderr, \ "assertion \"%s\" failed: file \"%s\", line %d\n", \ "expression", __FILE__, __LINE__); \ exit(2); \ } \ } #define _assert(expression) assert(expression) #endif #endif /* !_ASSERT_H_ */
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/assert.h
C
apache-2.0
2,264
../../include/cdefs.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/cdefs.h
C
apache-2.0
21
/*- * Copyright (c) 1991, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)compat.h 8.13 (Berkeley) 2/21/94 */ #ifndef _COMPAT_H_ #define _COMPAT_H_ #include <sys/types.h> /* * If your system doesn't typedef u_long, u_short, or u_char, change * the 0 to a 1. */ #if 0 typedef unsigned char u_char; /* 4.[34]BSD names. */ typedef unsigned int u_int; typedef unsigned long u_long; typedef unsigned short u_short; #endif /* If your system doesn't typedef size_t, change the 0 to a 1. */ #if 0 typedef unsigned int size_t; /* POSIX, 4.[34]BSD names. */ #endif /* If your system doesn't typedef ssize_t, change the 0 to a 1. */ #if 0 typedef int ssize_t; /* POSIX names. */ #endif /* * If your system doesn't have the POSIX type for a signal mask, * change the 0 to a 1. */ #if 0 /* POSIX 1003.1 signal mask type. */ typedef unsigned int sigset_t; #endif /* * If your system's vsprintf returns a char *, not an int, * change the 0 to a 1. */ #if 0 #define VSPRINTF_CHARSTAR #endif /* * If you don't have POSIX 1003.1 signals, the signal code surrounding the * temporary file creation is intended to block all of the possible signals * long enough to create the file and unlink it. All of this stuff is * intended to use old-style BSD calls to fake POSIX 1003.1 calls. */ #ifdef NO_POSIX_SIGNALS #define sigemptyset(set) (*(set) = 0) #define sigfillset(set) (*(set) = ~(sigset_t)0, 0) #define sigaddset(set,signo) (*(set) |= sigmask(signo), 0) #define sigdelset(set,signo) (*(set) &= ~sigmask(signo), 0) #define sigismember(set,signo) ((*(set) & sigmask(signo)) != 0) #define SIG_BLOCK 1 #define SIG_UNBLOCK 2 #define SIG_SETMASK 3 static int __sigtemp; /* For the use of sigprocmask */ /* Repeated test of oset != NULL is to avoid "*0". */ #define sigprocmask(how, set, oset) \ ((__sigtemp = \ (((how) == SIG_BLOCK) ? \ sigblock(0) | *(set) : \ (((how) == SIG_UNBLOCK) ? \ sigblock(0) & ~(*(set)) : \ ((how) == SIG_SETMASK ? \ *(set) : sigblock(0))))), \ ((oset) ? (*(oset ? oset : set) = sigsetmask(__sigtemp)) : \ sigsetmask(__sigtemp)), 0) #endif /* * If your system doesn't have an include file with the appropriate * byte order set, make sure you specify the correct one. */ #ifndef BYTE_ORDER #define LITTLE_ENDIAN 1234 /* LSB first: i386, vax */ #define BIG_ENDIAN 4321 /* MSB first: 68000, ibm, net */ #define BYTE_ORDER LITTLE_ENDIAN /* Set for your system. */ #endif #if defined(SYSV) || defined(SYSTEM5) #define index(a, b) strchr(a, b) #define rindex(a, b) strrchr(a, b) #define bzero(a, b) memset(a, 0, b) #define bcmp(a, b, n) memcmp(a, b, n) #define bcopy(a, b, n) memmove(b, a, n) #endif #if defined(BSD) || defined(BSD4_3) #define strchr(a, b) index(a, b) #define strrchr(a, b) rindex(a, b) #define memcmp(a, b, n) bcmp(a, b, n) #define memmove(a, b, n) bcopy(b, a, n) #endif /* * 32-bit machine. The db routines are theoretically independent of * the size of u_shorts and u_longs, but I don't know that anyone has * ever actually tried it. At a minimum, change the following #define's * if you are trying to compile on a different type of system. */ #ifndef USHRT_MAX #define USHRT_MAX 0xFFFF #define ULONG_MAX 0xFFFFFFFF #endif #ifndef O_ACCMODE /* POSIX 1003.1 access mode mask. */ #define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR) #endif #ifndef _POSIX2_RE_DUP_MAX /* POSIX 1003.2 RE limit. */ #define _POSIX2_RE_DUP_MAX 255 #endif /* * If you can't provide lock values in the open(2) call. Note, this * allows races to happen. */ #ifndef O_EXLOCK /* 4.4BSD extension. */ #define O_EXLOCK 0 #endif #ifndef O_SHLOCK /* 4.4BSD extension. */ #define O_SHLOCK 0 #endif #ifndef EFTYPE #define EFTYPE EINVAL /* POSIX 1003.1 format errno. */ #endif #ifndef WCOREDUMP /* 4.4BSD extension */ #define WCOREDUMP(a) 0 #endif #ifndef STDERR_FILENO #define STDIN_FILENO 0 /* ANSI C #defines */ #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #ifndef SEEK_END #define SEEK_SET 0 /* POSIX 1003.1 seek values */ #define SEEK_CUR 1 #define SEEK_END 2 #endif #ifndef _POSIX_VDISABLE /* POSIX 1003.1 disabling char. */ #define _POSIX_VDISABLE 0 /* Some systems used 0. */ #endif #ifndef TCSASOFT /* 4.4BSD extension. */ #define TCSASOFT 0 #endif #ifndef _POSIX2_RE_DUP_MAX /* POSIX 1003.2 values. */ #define _POSIX2_RE_DUP_MAX 255 #endif #ifndef NULL /* ANSI C #defines NULL everywhere. */ #define NULL 0 #endif #ifndef MAX /* Usually found in <sys/param.h>. */ #define MAX(_a,_b) ((_a)<(_b)?(_b):(_a)) #endif #ifndef MIN /* Usually found in <sys/param.h>. */ #define MIN(_a,_b) ((_a)<(_b)?(_a):(_b)) #endif /* Default file permissions. */ #ifndef DEFFILEMODE /* 4.4BSD extension. */ #define DEFFILEMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) #endif #ifndef S_ISDIR /* POSIX 1003.1 file type tests. */ #define S_ISDIR(m) ((m & 0170000) == 0040000) /* directory */ #define S_ISCHR(m) ((m & 0170000) == 0020000) /* char special */ #define S_ISBLK(m) ((m & 0170000) == 0060000) /* block special */ #define S_ISREG(m) ((m & 0170000) == 0100000) /* regular file */ #define S_ISFIFO(m) ((m & 0170000) == 0010000) /* fifo */ #endif #ifndef S_ISLNK /* BSD POSIX 1003.1 extensions */ #define S_ISLNK(m) ((m & 0170000) == 0120000) /* symbolic link */ #define S_ISSOCK(m) ((m & 0170000) == 0140000) /* socket */ #endif /* The type of a va_list. */ #ifndef _BSD_VA_LIST_ /* 4.4BSD #define. */ #define _BSD_VA_LIST_ char * #endif #endif /* !_COMPAT_H_ */
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/compat.h
C
apache-2.0
7,284
../../include/db.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/db.h
C
apache-2.0
18
../../include/mpool.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/mpool.h
C
apache-2.0
21
../../include/ndbm.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/ndbm.h
C
apache-2.0
20
../../include/queue.h
YifuLiu/AliOS-Things
components/py_engine/engine/lib/berkeley-db-1.xx/PORT/bsdi.1.0/include/queue.h
C
apache-2.0
21