micropython: add micropython component

This commit is contained in:
KY-zhang-X
2022-09-29 12:10:37 +08:00
parent 1514f1cb9b
commit dd76146324
2679 changed files with 354110 additions and 0 deletions

View File

@@ -0,0 +1,153 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_SPI
#include "py/mphal.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "extmod/machine_spi.h"
#include "modmachine.h"
#if !(MP_GEN_HDR)
#include "tos_k.h"
#include "mp_tos_hal_spi.h"
#endif
typedef struct _machine_hard_spi_obj_t {
mp_obj_base_t base;
hal_spi_port_t port;
hal_spi_t spi;
uint16_t timeout;
uint16_t timeout_char;
uint8_t init;
} machine_hard_spi_obj_t;
STATIC machine_hard_spi_obj_t machine_hard_spi_obj_all[MICROPY_HW_SPI_NUM];
STATIC machine_hard_spi_obj_t *machine_hard_spi_find(mp_obj_t user_obj) {
machine_hard_spi_obj_t *spi = NULL;
if (mp_obj_is_int(user_obj)) {
mp_uint_t spi_id = mp_obj_get_int(user_obj);
if (spi_id < MICROPY_HW_SPI_NUM)
spi = &machine_hard_spi_obj_all[spi_id];
if (spi->base.type == NULL) {
spi->base.type = &machine_hard_spi_type;
spi->port = (hal_spi_port_t)spi_id;
spi->init = 0;
}
}
return spi;
}
STATIC void machine_hard_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
machine_hard_spi_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "SPI(%u)", self->port);
}
STATIC mp_obj_t machine_hard_spi_init_helper(machine_hard_spi_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args);
mp_obj_t machine_hard_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// check arguments
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
machine_hard_spi_obj_t *spi = machine_hard_spi_find(args[0]);
if (spi == NULL) {
mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("invalid spi"));
}
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
machine_hard_spi_init_helper(spi, n_args - 1, args + 1, &kw_args);
return MP_OBJ_FROM_PTR(spi);
}
STATIC mp_obj_t machine_hard_spi_init_helper(machine_hard_spi_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
/*
enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit };
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 = SPI_FIRSTBIT_MSB} },
};
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 (self->init) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("SPI(%u) has been initialized"), self->port);
}
if (0 != tos_hal_spi_init(&self->spi, self->port)) {
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("SPI(%u) doesn't exist"), self->port);
}
// FIXME: should not be fixed
self->timeout = 100;
self->timeout_char = 1;
self->init = 1;
return mp_const_none;
}
STATIC void machine_hard_spi_init(mp_obj_base_t *self_in, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in;
machine_hard_spi_init_helper(self, n_args, pos_args, kw_args);
}
STATIC void machine_hard_spi_deinit(mp_obj_base_t *self_in) {
machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in;
if (self->init) {
tos_hal_spi_deinit(&self->spi);
self->init = 0;
}
}
STATIC void machine_hard_spi_transfer(mp_obj_base_t *self_in, size_t len, const uint8_t *src, uint8_t *dest) {
machine_hard_spi_obj_t *self = (machine_hard_spi_obj_t *)self_in;
tos_hal_spi_transfer(&self->spi, src, dest, len, self->timeout + len * self->timeout_char);
}
STATIC const mp_machine_spi_p_t machine_hard_spi_p = {
.init = machine_hard_spi_init,
.deinit = machine_hard_spi_deinit,
.transfer = machine_hard_spi_transfer,
};
const mp_obj_type_t machine_hard_spi_type = {
{ &mp_type_type },
.name = MP_QSTR_SPI,
.print = machine_hard_spi_print,
.make_new = machine_hard_spi_make_new,
.protocol = &machine_hard_spi_p,
.locals_dict = (mp_obj_dict_t *)&mp_machine_spi_locals_dict,
};
#endif /* MICROPY_PY_MACHINE_SPI */

View File

@@ -0,0 +1,34 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_MACHINE_HW_SPI_H
#define MICROPY_INCLUDED_MACHINE_HW_SPI_H
#include "py/obj.h"
extern const mp_obj_type_t machine_hard_spi_type;
#endif /* MICROPY_INCLUDED_MACHINE_HW_SPI_H */

View File

@@ -0,0 +1,281 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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 "py/mphal.h"
#include "py/runtime.h"
#include "extmod/virtpin.h"
#include "modmachine.h"
#if !(MP_GEN_HDR)
#include "mp_tos_hal_pin.h"
#endif
typedef struct _machine_pin_obj_t {
mp_obj_base_t base;
hal_pin_port_t port;
hal_pin_t pin;
qstr name;
mp_obj_t handler;
} machine_pin_obj_t;
void mp_hal_pin_write(machine_pin_obj_t *pin, int v) {
if (tos_hal_pin_write(&pin->pin, v) != 0) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Pin(%q) failed to be written"), pin->name);
}
}
int mp_hal_pin_read(machine_pin_obj_t * pin) {
int v = tos_hal_pin_read(&pin->pin);
if (v < 0) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Pin(%q) failed to be read"), pin->name);
}
return v;
}
void mp_hal_pin_config(machine_pin_obj_t * pin, uint32_t mode) {
if (tos_hal_pin_init(&pin->pin, pin->port, (hal_pin_mode_t)mode) != 0) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Pin(%q) failed to be configured"), pin->name);
}
}
qstr mp_hal_pin_name(machine_pin_obj_t *pin) {
return pin->name;
}
extern const mp_obj_dict_t machine_pins_locals_dict;
machine_pin_obj_t *mp_hal_get_pin_obj(mp_obj_t name) {
const mp_map_t *named_map = &machine_pins_locals_dict.map;
mp_map_elem_t *named_elem = mp_map_lookup((mp_map_t *)named_map, name, MP_MAP_LOOKUP);
machine_pin_obj_t *pin;
if (named_elem != NULL && named_elem->value != MP_OBJ_NULL) {
pin = m_new_obj(machine_pin_obj_t);
pin->port = mp_obj_get_int(named_elem->value);
pin->name = mp_obj_str_get_qstr(name);
pin->base.type = &machine_pin_type;
pin->handler = mp_const_none;
return pin;
}
return NULL;
}
void machine_pins_init(void) {
}
STATIC machine_pin_obj_t *machine_pin_find(mp_obj_t user_obj) {
machine_pin_obj_t *pin_obj = mp_hal_get_pin_obj(user_obj);
if (pin_obj) {
return pin_obj;
}
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("Pin(%s) doesn't exist"), mp_obj_str_get_str(user_obj));
}
STATIC void machine_pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
machine_pin_obj_t *self = self_in;
mp_printf(print, "Pin(%q)", self->name);
}
STATIC mp_obj_t machine_pin_obj_init_helper(machine_pin_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args);
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) {
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
// Run an argument through the mapper and return the result.
machine_pin_obj_t *pin = machine_pin_find(args[0]);
if (pin == NULL) {
mp_raise_ValueError(MP_ERROR_TEXT("invalid pin"));
}
if (n_args > 1 || n_kw > 0) {
// pin mode given, so configure this GPIO
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
machine_pin_obj_init_helper(pin, n_args - 1, args + 1, &kw_args);
}
return MP_OBJ_FROM_PTR(pin);
}
STATIC mp_obj_t machine_pin_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);
machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (n_args == 0) {
// get pin
return MP_OBJ_NEW_SMALL_INT(mp_hal_pin_read(self));
} else {
// set pin
mp_hal_pin_write(self, mp_obj_is_true(args[0]));
return mp_const_none;
}
}
// pin.init(mode=None, pull=-1, *, value, drive, hold)
STATIC mp_obj_t machine_pin_obj_init_helper(machine_pin_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_mode, ARG_value };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT },
{ MP_QSTR_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}},
};
// 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);
// get mode
uint mode = args[ARG_mode].u_int;
if (!MP_HAL_IS_PIN_MODE(mode)) {
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("invalid pin mode: %d"), mode);
}
// if given, set the pin value before initialising to prevent glitches
if (args[ARG_value].u_obj != MP_OBJ_NULL) {
mp_hal_pin_write(self, mp_obj_is_true(args[ARG_value].u_obj));
}
// configure the GPIO as requested
mp_hal_pin_config(self, mode);
return mp_const_none;
}
// pin.init(mode, pull)
STATIC mp_obj_t machine_pin_obj_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
return machine_pin_obj_init_helper(MP_OBJ_TO_PTR(args[0]), n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_pin_init_obj, 1, machine_pin_obj_init);
// pin.value([value])
STATIC mp_obj_t machine_pin_value(size_t n_args, const mp_obj_t *args) {
return machine_pin_call(args[0], n_args - 1, 0, args + 1);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_pin_value_obj, 1, 2, machine_pin_value);
// pin.off()
STATIC mp_obj_t machine_pin_off(mp_obj_t self_in) {
machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_hal_pin_low(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_off_obj, machine_pin_off);
// pin.on()
STATIC mp_obj_t machine_pin_on(mp_obj_t self_in) {
machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_hal_pin_high(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_pin_on_obj, machine_pin_on);
void machine_pin_isr_handler(void *arg) {
machine_pin_obj_t *self = (machine_pin_obj_t *)arg;
mp_sched_schedule(self->handler, MP_OBJ_FROM_PTR(self));
}
// pin.irq(handler=None, trigger=IRQ_FALLING|IRQ_RISING)
STATIC mp_obj_t machine_pin_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_handler, ARG_trigger };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_handler, MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_trigger, MP_ARG_INT, {.u_int = HAL_PIN_IRQ_RISING|HAL_PIN_IRQ_FALLING } },
};
machine_pin_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);
if (n_args > 1 || kw_args->used != 0) {
// set handler
mp_obj_t handler = args[ARG_handler].u_obj;
if (handler == mp_const_none || !mp_obj_is_callable(handler)) {
mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("invalid irq handler"));
}
self->handler = handler;
// configure irq
if ((tos_hal_pin_irq_callback(&self->pin, machine_pin_isr_handler, self) != 0)
|| (tos_hal_pin_irq(&self->pin, (hal_pin_irq_t)args[ARG_trigger].u_int) != 0)) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("Pin(%q) failed to configure irq"), self->name);
}
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_pin_irq_obj, 1, machine_pin_irq);
STATIC const mp_rom_map_elem_t machine_pin_locals_dict_table[] = {
// instance methods
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_pin_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&machine_pin_value_obj) },
{ MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&machine_pin_off_obj) },
{ MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&machine_pin_on_obj) },
{ MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&machine_pin_irq_obj) },
// class constants
{ MP_ROM_QSTR(MP_QSTR_IN), MP_ROM_INT(HAL_PIN_MODE_INPUT) },
{ MP_ROM_QSTR(MP_QSTR_OUT), MP_ROM_INT(HAL_PIN_MODE_OUTPUT) },
{ MP_ROM_QSTR(MP_QSTR_OPEN_DRAIN), MP_ROM_INT(HAL_PIN_MODE_OUTPUT_OD) },
{ MP_ROM_QSTR(MP_QSTR_IN_PULLUP), MP_ROM_INT(HAL_PIN_MODE_INPUT_PULLUP) },
{ MP_ROM_QSTR(MP_QSTR_IN_PULLDOWN), MP_ROM_INT(HAL_PIN_MODE_INPUT_PULLDOWN) },
{ MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(HAL_PIN_IRQ_RISING) },
{ MP_ROM_QSTR(MP_QSTR_IRQ_FALLING), MP_ROM_INT(HAL_PIN_IRQ_FALLING) },
};
STATIC MP_DEFINE_CONST_DICT(machine_pin_locals_dict, machine_pin_locals_dict_table);
STATIC mp_uint_t pin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
(void)errcode;
machine_pin_obj_t *self = MP_OBJ_TO_PTR(self_in);
switch (request) {
case MP_PIN_READ: {
return mp_hal_pin_read(self);
}
case MP_PIN_WRITE: {
mp_hal_pin_write(self, arg);
return 0;
}
}
return (mp_uint_t)-1;
}
STATIC const mp_pin_p_t pin_pin_p = {
.ioctl = pin_ioctl,
};
const mp_obj_type_t machine_pin_type = {
{ &mp_type_type },
.name = MP_QSTR_Pin,
.print = machine_pin_print,
.make_new = mp_pin_make_new,
.call = machine_pin_call,
.protocol = &pin_pin_p,
.locals_dict = (mp_obj_t)&machine_pin_locals_dict,
};
#endif /* MICROPY_PY_MACHINE */

View File

@@ -0,0 +1,36 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_MACHINE_PIN_H
#define MICROPY_INCLUDED_MACHINE_PIN_H
#include "py/obj.h"
extern const mp_obj_type_t machine_pin_type;
void machine_pins_init(void);
#endif /* MICROPY_INCLUDED_MACHINE_PIN_H */

View File

@@ -0,0 +1,232 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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 "py/obj.h"
#include "py/runtime.h"
#include "modmachine.h"
#if !(MP_GEN_HDR)
#include "tos_k.h"
#endif
typedef struct _machine_timer_obj_t {
mp_obj_base_t base;
k_timer_t timer;
mp_obj_t callback;
mp_int_t period;
uint8_t mode;
uint8_t init : 1;
uint8_t running : 1;
struct _machine_timer_obj_t *next;
} machine_timer_obj_t;
STATIC void machine_timer_disable(machine_timer_obj_t *self);
void machine_timer_deinit_all(void) {
machine_timer_obj_t *t = MP_STATE_PORT(machine_timer_obj_head);
for (; t != NULL; t = t->next) {
machine_timer_disable(t);
}
}
STATIC void machine_timer_handler(void *arg) {
machine_timer_obj_t *self = (machine_timer_obj_t *)arg;
mp_sched_schedule(self->callback, MP_OBJ_FROM_PTR(self));
if (self->mode == TOS_OPT_TIMER_ONESHOT)
self->running = 0;
}
STATIC void machine_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->init) {
qstr mode = self->mode == TOS_OPT_TIMER_ONESHOT ? MP_QSTR_ONE_SHOT : MP_QSTR_PERIODIC;
mp_printf(print, "Timer(%p, mode=%q, period=%u, running=%u)", self, mode, self->period, self->running);
} else {
mp_printf(print, "Timer(%p)", self);
}
}
STATIC mp_obj_t machine_timer_init_helper(machine_timer_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args);
mp_obj_t machine_timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// check arguments
// mp_arg_check_num(n_args, n_kw, 0, MP_OBJ_FUN_ARGS_MAX, true);
machine_timer_obj_t *self = mp_obj_malloc(machine_timer_obj_t, &machine_timer_type);
self->init = 0;
self->mode = TOS_OPT_TIMER_ONESHOT;
self->running = 0;
self->period = 1000;
self->callback = mp_const_none;
memset(&self->timer, 0x00, sizeof(k_timer_t));
self->next = MP_STATE_PORT(machine_timer_obj_head);
MP_STATE_PORT(machine_timer_obj_head) = self;
if (n_args > 0 || n_kw > 0) {
// start the timer
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
machine_timer_init_helper(self, n_args, args, &kw_args);
}
return MP_OBJ_FROM_PTR(self);
}
STATIC void machine_timer_enable(machine_timer_obj_t *self) {
k_tick_t period_ticks = tos_millisec2tick(self->period);
k_err_t err = tos_timer_create(&self->timer, period_ticks, period_ticks,
machine_timer_handler, self, self->mode);
if (err != K_ERR_NONE) {
mp_raise_msg(&mp_type_OSError, "can't create timer");
}
}
STATIC void machine_timer_disable(machine_timer_obj_t *self) {
if (self->init) {
tos_timer_destroy(&self->timer);
self->callback = mp_const_none;
self->init = 0;
}
}
STATIC mp_obj_t machine_timer_init_helper(machine_timer_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_mode, ARG_callback, ARG_tick_hz, ARG_period, ARG_freq };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = TOS_OPT_TIMER_PERIODIC} },
{ MP_QSTR_callback, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
{ MP_QSTR_tick_hz, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000} },
{ MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
#if MICROPY_PY_BUILTINS_FLOAT
{ MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} },
#else
{ MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0xffffffff} },
#endif
};
// 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);
uint64_t period = self->period;
#if MICROPY_PY_BUILTINS_FLOAT
if (args[ARG_freq].u_obj != mp_const_none) {
// frequency specified in Hz
period = (uint64_t)(MICROPY_FLOAT_CONST(1000.0) / mp_obj_get_float(args[ARG_freq].u_obj));
}
#else
if (args[ARG_freq].u_int != 0xffffffff) {
// frequency specified in Hz
period = 1000 / (args[ARG_freq].u_int);
}
#endif
else {
// period specified
period = ((uint64_t)args[ARG_period].u_int * 1000 / args[ARG_tick_hz].u_int);
}
if (period < 1) {
period = 1;
} else if (period >= 0x40000000) {
mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("period too large"));
}
self->period = period;
if (args[ARG_mode].u_int != TOS_OPT_TIMER_ONESHOT && args[ARG_mode].u_int != TOS_OPT_TIMER_PERIODIC) {
mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("invalid timer mode"));
}
self->mode = args[ARG_mode].u_int;
self->callback = args[ARG_callback].u_obj;
// create timer
machine_timer_enable(self);
self->init = 1;
if (self->callback == mp_const_none) {
// do nothing
} else if (mp_obj_is_callable(self->callback)) {
// start timer
self->running = 1;
tos_timer_start(&self->timer);
}
return mp_const_none;
}
// timer.init()
STATIC mp_obj_t machine_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
machine_timer_disable(args[0]);
return machine_timer_init_helper(args[0], n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_timer_init_obj, 1, machine_timer_init);
// timer.deinit()
STATIC mp_obj_t machine_timer_deinit(mp_obj_t self_in) {
machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
machine_timer_disable(self);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_timer_deinit_obj, machine_timer_deinit);
STATIC mp_obj_t machine_timer_callback(mp_obj_t self_in, mp_obj_t callback) {
machine_timer_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (callback == mp_const_none) {
tos_timer_stop(&self->timer);
self->running = 0;
self->callback = mp_const_none;
} else if (mp_obj_is_callable(callback)) {
self->callback = callback;
if (!self->running) {
// restart timer
tos_timer_start(&self->timer);
self->running = 1;
}
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(machine_timer_callback_obj, machine_timer_callback);
STATIC const mp_rom_map_elem_t machine_timer_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_timer_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_timer_deinit_obj) },
{ MP_ROM_QSTR(MP_QSTR_callback), MP_ROM_PTR(&machine_timer_callback_obj) },
{ MP_ROM_QSTR(MP_QSTR_ONE_SHOT), MP_ROM_INT(TOS_OPT_TIMER_ONESHOT) },
{ MP_ROM_QSTR(MP_QSTR_PERIODIC), MP_ROM_INT(TOS_OPT_TIMER_PERIODIC) },
};
STATIC MP_DEFINE_CONST_DICT(machine_timer_locals_dict, machine_timer_locals_dict_table);
const mp_obj_type_t machine_timer_type = {
{ &mp_type_type },
.name = MP_QSTR_Timer,
.print = machine_timer_print,
.make_new = machine_timer_make_new,
.locals_dict = (mp_obj_dict_t *)&machine_timer_locals_dict,
};
#endif /* MICROPY_PY_MACHINE */

View File

@@ -0,0 +1,36 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_MACHINE_TIMER_H
#define MICROPY_INCLUDED_MACHINE_TIMER_H
#include "py/obj.h"
extern const mp_obj_type_t machine_timer_type;
void machine_timer_deinit_all(void);
#endif /* MICROPY_INCLUDED_MACHINE_TIMER_H */

View File

@@ -0,0 +1,404 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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"
#include "py/mphal.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "shared/runtime/interrupt_char.h"
#include "modmachine.h"
#if !(MP_GEN_HDR)
#include "tos_k.h"
#include "tos_at.h"
#include "tos_hal_uart.h"
#include "mp_tos_hal_uart.h"
#endif
typedef struct _machine_uart_obj_t {
mp_obj_base_t base;
hal_uart_port_t port;
hal_uart_t uart;
// k_mutex_t tx_lock;
uint8_t rx_char_buf;
k_sem_t rx_sem;
k_chr_fifo_t rx_fifo;
uint8_t *rx_fifo_buf;
uint16_t rx_fifo_buf_len;
uint16_t timeout; // timeout waiting for first char
uint16_t timeout_char; // timeout waiting between chars
at_agent_t *at_agent;
uint8_t init;
uint8_t attached_to_repl;
} machine_uart_obj_t;
STATIC machine_uart_obj_t machine_uart_obj_all[MICROPY_HW_UART_NUM];
void machine_uart_rx_start(machine_uart_obj_t *self) {
if (self->rx_fifo_buf || self->at_agent) {
tos_hal_uart_recv_start(&self->uart, &self->rx_char_buf, 1);
}
}
void mp_hal_uart_rx_start(uint32_t uart_id) {
machine_uart_obj_t *self = &machine_uart_obj_all[uart_id];
if (self == NULL || !self->init) {
return;
}
machine_uart_rx_start(self);
}
int machine_uart_rx_chr(machine_uart_obj_t *self) {
k_err_t err;
uint8_t chr;
if (!self->init)
return -1;
machine_uart_rx_start(self);
if (tos_chr_fifo_is_empty(&self->rx_fifo)) {
if (tos_sem_pend(&self->rx_sem, self->timeout) != K_ERR_NONE) {
return -1;
}
}
err = tos_chr_fifo_pop(&self->rx_fifo, &chr);
return err == K_ERR_NONE ? chr : -1;
}
int machine_uart_tx_strn(machine_uart_obj_t *self, const char *str, mp_uint_t len) {
int ret = 0;
// tos_mutex_pend(&self->tx_lock);
ret = tos_hal_uart_write(&self->uart, (const uint8_t *)str, len, 0xFFFF);
// tos_mutex_post(&self->tx_lock);
return ret;
}
void machine_uart_attach_to_repl(machine_uart_obj_t *self, uint8_t attached) {
self->attached_to_repl = attached;
}
void mp_hal_uart_irq_handler(uint32_t uart_id) {
machine_uart_obj_t *self;
if (uart_id >= MICROPY_HW_UART_NUM) {
return;
}
self = &machine_uart_obj_all[uart_id];
if (self == NULL || !self->init) {
return;
}
machine_uart_rx_start(self);
#if MICROPY_PY_NETWORK
// if UART is used as AT agent
if (self->at_agent) {
tos_at_uart_input_byte(self->at_agent, self->rx_char_buf);
return;
}
#endif
if (self->attached_to_repl) {
if (mp_interrupt_char == self->rx_char_buf) {
mp_sched_keyboard_interrupt();
return;
}
}
if (self->rx_fifo_buf) {
tos_chr_fifo_push(&self->rx_fifo, self->rx_char_buf);
tos_sem_post(&self->rx_sem);
}
}
void machine_uart_set_at_agent(machine_uart_obj_t *self, at_agent_t *at_agent) {
self->at_agent = at_agent;
}
hal_uart_port_t machine_uart_get_port(machine_uart_obj_t *self) {
return self->port;
}
STATIC machine_uart_obj_t *machine_uart_find(mp_obj_t user_obj) {
machine_uart_obj_t *uart = NULL;
if (mp_obj_is_int(user_obj)) {
mp_uint_t uart_id = mp_obj_get_int(user_obj);
if (uart_id < MICROPY_HW_UART_NUM)
uart = &machine_uart_obj_all[uart_id];
if (uart->base.type == NULL) {
uart->base.type = &machine_uart_type;
uart->port = (hal_uart_port_t)uart_id;
uart->rx_fifo_buf = NULL;
uart->at_agent = NULL;
uart->init = 0;
}
}
return uart;
}
STATIC void machine_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->init) {
mp_printf(print, "UART(%u, rxbuf=%u, timeout=%u, timeout_char=%u)", self->port, self->rx_fifo_buf_len, self->timeout, self->timeout_char);
} else {
mp_printf(print, "UART(%u)", self->port);
}
}
STATIC mp_obj_t machine_uart_init_helper(machine_uart_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args);
mp_obj_t machine_uart_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// check arguments
mp_arg_check_num(n_args, n_kw, 1, MP_OBJ_FUN_ARGS_MAX, true);
machine_uart_obj_t *uart = machine_uart_find(args[0]);
if (uart == NULL) {
mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("invalid uart"));
}
mp_map_t kw_args;
mp_map_init_fixed_table(&kw_args, n_kw, args + n_args);
if (!uart->init) {
machine_uart_init_helper(uart, n_args - 1, args + 1, &kw_args);
}
return MP_OBJ_FROM_PTR(uart);
}
STATIC mp_obj_t machine_uart_init_helper(machine_uart_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { /*ARG_baudrate, ARG_bits, ARG_parity, ARG_stop, ARG_flow, ARG_txbuf, */ARG_rxbuf, ARG_timeout, ARG_timeout_char };
static const mp_arg_t allowed_args[] = {
// { MP_QSTR_baudrate, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 9600} },
// { MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} },
// { MP_QSTR_parity, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} },
// { MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} },
// { MP_QSTR_flow, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int}}
// { MP_QSTR_txbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} },
{ MP_QSTR_rxbuf, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 64} },
{ MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
{ MP_QSTR_timeout_char, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} },
};
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 (self->init) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("UART(%u) has been initialized"), self->port);
}
if (0 != tos_hal_uart_init(&self->uart, self->port)) {
mp_raise_msg_varg(&mp_type_ValueError, MP_ERROR_TEXT("UART(%u) doesn't exist"), self->port);
}
if (args[ARG_rxbuf].u_int >= 0) {
self->rx_fifo_buf_len = args[ARG_rxbuf].u_int;
}
self->timeout = args[ARG_timeout].u_int;
self->timeout_char = args[ARG_timeout_char].u_int;
// minimal char timeout is 2ms
if (self->timeout_char < 2) {
self->timeout_char = 2;
}
self->attached_to_repl = 0;
// reset rx fifo buffer before reallocation
if (self->rx_fifo_buf) {
tos_mmheap_free(self->rx_fifo_buf);
self->rx_fifo_buf = NULL;
}
// TODO: reset rx fifo and rx sem?
// tos_chr_fifo_destroy(&self->rx_fifo);
// tos_sem_destroy(&self->rx_sem);
// setup rx fifo
if (self->rx_fifo_buf_len > 0) {
self->rx_fifo_buf = tos_mmheap_alloc(self->rx_fifo_buf_len);
if (!self->rx_fifo_buf) {
goto err0;
}
tos_chr_fifo_create(&self->rx_fifo, self->rx_fifo_buf, self->rx_fifo_buf_len);
if (K_ERR_NONE != tos_sem_create(&self->rx_sem, 0)) {
goto err1;
}
machine_uart_rx_start(self);
}
self->init = 1;
return mp_const_none;
err1:
tos_mmheap_free(self->rx_fifo_buf);
self->rx_fifo_buf = NULL;
tos_chr_fifo_destroy(&self->rx_fifo);
err0:
tos_hal_uart_deinit(&self->uart);
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("can't create rxbuf"));
return mp_const_none;
}
// uart.init()
STATIC mp_obj_t machine_uart_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) {
return machine_uart_init_helper(MP_OBJ_TO_PTR(args[0]), n_args - 1, args + 1, kw_args);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(machine_uart_init_obj, 1, machine_uart_init);
// uart.deinit()
STATIC mp_obj_t machine_uart_deinit(mp_obj_t self_in) {
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->init) {
if (self->rx_fifo_buf) {
tos_mmheap_free(self->rx_fifo_buf);
self->rx_fifo_buf = NULL;
}
tos_chr_fifo_destroy(&self->rx_fifo);
tos_sem_destroy(&self->rx_sem);
tos_hal_uart_deinit(&self->uart);
self->init = 0;
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_deinit_obj, machine_uart_deinit);
// uart.any()
// Return `True` if any characters waiting, else `False`.
STATIC mp_obj_t machine_uart_any(mp_obj_t self_in) {
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->rx_fifo_buf) {
return MP_OBJ_NEW_SMALL_INT(!tos_chr_fifo_is_empty(&self->rx_fifo));
} else {
return MP_OBJ_NEW_SMALL_INT(0);
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(machine_uart_any_obj, machine_uart_any);
STATIC const mp_rom_map_elem_t machine_uart_locals_dict_table[] = {
// instance methods
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&machine_uart_init_obj) },
{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&machine_uart_deinit_obj) },
{ MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&machine_uart_any_obj) },
{ MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) },
{ MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_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) },
};
STATIC MP_DEFINE_CONST_DICT(machine_uart_locals_dict, machine_uart_locals_dict_table);
mp_uint_t machine_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) {
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
uint8_t *buf = buf_in;
if (size == 0) {
return 0;
}
if (!self->rx_fifo_buf) {
// no buffering
if (0 != tos_hal_uart_read(&self->uart, (const uint8_t *)buf, size, self->timeout + self->timeout_char * size)) {
return MP_STREAM_ERROR;
}
return size;
} else {
uint8_t *orig_buf = buf;
if (tos_chr_fifo_is_empty(&self->rx_fifo)) {
if (K_ERR_NONE != tos_sem_pend(&self->rx_sem, self->timeout)) {
*errcode = MP_EAGAIN;
return MP_STREAM_ERROR;
}
}
for (;;) {
int read_size = tos_chr_fifo_pop_stream(&self->rx_fifo, buf, size);
size -= read_size; buf += read_size;
if (size <= 0) {
return buf - orig_buf;
}
if (tos_chr_fifo_is_empty(&self->rx_fifo)) {
if (K_ERR_NONE != tos_sem_pend(&self->rx_sem, self->timeout_char)) {
return buf - orig_buf;
}
}
}
}
}
mp_uint_t machine_uart_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) {
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
int ret;
// tos_mutex_pend(&self->tx_lock);
ret = tos_hal_uart_write(&self->uart, (uint8_t *)buf, size, 0xFFFF);
// tos_mutex_post(&self->tx_lock);
if (ret != 0) {
return MP_STREAM_ERROR;
}
return size;
}
mp_uint_t machine_uart_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) {
machine_uart_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_uint_t ret;
if (request == MP_STREAM_POLL) {
uintptr_t flags = arg;
ret = 0;
if ((flags & MP_STREAM_POLL_RD) && !tos_chr_fifo_is_empty(&self->rx_fifo)) {
ret |= MP_STREAM_POLL_RD;
}
if ((flags & MP_STREAM_POLL_WR) && 1) {
ret |= MP_STREAM_POLL_WR;
}
} else {
*errcode = MP_EINVAL;
ret = MP_STREAM_ERROR;
}
return ret;
}
STATIC const mp_stream_p_t uart_stream_p = {
.read = machine_uart_read,
.write = machine_uart_write,
.ioctl = machine_uart_ioctl,
.is_text = false,
};
const mp_obj_type_t machine_uart_type = {
{ &mp_type_type },
.name = MP_QSTR_UART,
.print = machine_uart_print,
.make_new = machine_uart_make_new,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &uart_stream_p,
.locals_dict = (mp_obj_dict_t *)&machine_uart_locals_dict,
};

View File

@@ -0,0 +1,56 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_MACHINE_UART_H
#define MICROPY_INCLUDED_MACHINE_UART_H
#include "py/obj.h"
#ifndef MP_GEN_HDR
#include "tos_k.h"
#include "tos_hal.h"
#include "tos_at.h"
#endif
extern const mp_obj_type_t machine_uart_type;
typedef struct _machine_uart_obj_t machine_uart_obj_t;
/* board */
void mp_hal_uart_rx_start(uint32_t uart_id);
void mp_hal_uart_irq_handler(uint32_t uart_id);
/* repl */
int machine_uart_rx_chr(machine_uart_obj_t *self);
int machine_uart_tx_strn(machine_uart_obj_t *self, const char *str, mp_uint_t len);
void machine_uart_rx_start(machine_uart_obj_t *self);
void machine_uart_attach_to_repl(machine_uart_obj_t *self, uint8_t attached);
/* esp8266 */
void machine_uart_set_at_agent(machine_uart_obj_t *self, at_agent_t *at_agent);
hal_uart_port_t machine_uart_get_port(machine_uart_obj_t *self);
#endif /* MICROPY_INCLUDED_MACHINE_UART_H */

View File

@@ -0,0 +1,315 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_NETWORK && MICROPY_PY_NETWORK_ESP8266
#include "py/mphal.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "py/mperrno.h"
#include "extmod/modnetwork.h"
#include "machine_uart.h"
#if !(MP_GEN_HDR)
#include "tos_k.h"
#include "tos_at_socket.h"
#include "sal_module_wrapper.h"
#include "esp8266.h"
#endif
#define MAKE_SOCKADDR(addr, ip, port) \
struct sockaddr addr; \
addr.sa_family = AF_INET; \
addr.sa_data[0] = port >> 8; \
addr.sa_data[1] = port; \
addr.sa_data[2] = ip[0]; \
addr.sa_data[3] = ip[1]; \
addr.sa_data[4] = ip[2]; \
addr.sa_data[5] = ip[3];
#define UNPACK_SOCKADDR(addr, ip, port) \
port = (addr.sa_data[0] << 8) | addr.sa_data[1]; \
ip[0] = addr.sa_data[2]; \
ip[1] = addr.sa_data[3]; \
ip[2] = addr.sa_data[4]; \
ip[3] = addr.sa_data[5];
STATIC int esp8266_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_t *ip_out) {
char ip_str[16];
if (0 != tos_sal_module_parse_domain(name, ip_str, sizeof(ip_str))) {
return -2;
}
int ret = sscanf(ip_str, "%hhu.%hhu.%hhu.%hhu",
&ip_out[0], &ip_out[1], &ip_out[2], &ip_out[3]);
if (ret != 4) {
return -2;
}
return 0;
}
STATIC int socket_socket(struct _mod_network_socket_obj_t *skt, int *_errno) {
// only support IPv4
if (skt->domain != MOD_NETWORK_AF_INET) {
*_errno = MP_EAFNOSUPPORT;
return -1;
}
int domain = AF_INET;
int type;
switch (skt->type) {
case MOD_NETWORK_SOCK_STREAM:
type = SOCK_STREAM;
break;
case MOD_NETWORK_SOCK_DGRAM:
type = SOCK_DGRAM;
break;
case MOD_NETWORK_SOCK_RAW:
// SOCK_RAW is not supported yet
default:
*_errno = MP_EINVAL;
return -1;
}
// open socket
int fd = socket(domain, type, 0);
if (fd < 0) {
// FIXME: no more detailed errno
*_errno = MP_EMFILE;
return -1;
}
// store state of this socket
skt->fileno = fd;
return 0;
}
STATIC void socket_close(struct _mod_network_socket_obj_t *socket) {
close(socket->fileno);
}
STATIC int socket_bind(struct _mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno) {
// FIXME: not support
*_errno = MP_EINVAL;
return -1;
}
STATIC int socket_listen(struct _mod_network_socket_obj_t *socket, mp_int_t backlog, int *_errno) {
// FIXME: not support
*_errno = MP_EINVAL;
return -1;
}
STATIC int socket_accept(struct _mod_network_socket_obj_t *socket, struct _mod_network_socket_obj_t *socket2, byte *ip, mp_uint_t *port, int *_errno) {
// FIXME: not support
*_errno = MP_EINVAL;
return -1;
}
STATIC int socket_connect(struct _mod_network_socket_obj_t *socket, byte *ip, mp_uint_t port, int *_errno) {
MAKE_SOCKADDR(addr, ip, port);
int ret = connect(socket->fileno, &addr, sizeof(addr));
if (ret != 0) {
// FIXME: no more detailed errno
*_errno = MP_ETIMEDOUT;
return -1;
}
return 0;
}
STATIC mp_uint_t socket_send(struct _mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) {
int ret = send(socket->fileno, buf, len, 0);
if (ret < 0) {
// FIXME: no more detailed errno
*_errno = MP_EPERM;
return (mp_uint_t)-1;
}
return ret;
}
STATIC mp_uint_t socket_recv(struct _mod_network_socket_obj_t *socket, byte *buf, mp_uint_t len, int *_errno) {
int ret = recv(socket->fileno, buf, len, 0);
if (ret < 0) {
// FIXME: no more detailed errno
*_errno = MP_EPERM;
return (mp_uint_t)-1;
}
return ret;
}
STATIC mp_uint_t socket_sendto(struct _mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) {
MAKE_SOCKADDR(addr, ip, port);
int ret = sendto(socket->fileno, buf, len, 0, &addr, sizeof(addr));
if (ret < 0) {
// FIXME: no more detailed errno
*_errno = MP_EPERM;
return (mp_uint_t)-1;
}
return ret;
}
STATIC mp_uint_t socket_recvfrom(struct _mod_network_socket_obj_t *socket, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) {
struct sockaddr addr;
socklen_t addr_len = sizeof(addr);
int ret = recvfrom(socket->fileno, buf, len, 0, &addr, &addr_len);
if (ret < 0) {
// FIXME
*_errno = MP_EPERM;
return (mp_uint_t)-1;
}
UNPACK_SOCKADDR(addr, ip, *port);
return ret;
}
STATIC int socket_setsockopt(struct _mod_network_socket_obj_t *socket, mp_uint_t level, mp_uint_t opt, const void *optval, mp_uint_t optlen, int *_errno) {
// FIXME not support
*_errno = MP_EINVAL;
return -1;
}
STATIC int socket_settimeout(struct _mod_network_socket_obj_t *socket, mp_uint_t timeout_ms, int *_errno) {
// FIXME
*_errno = MP_EINVAL;
return -1;
}
STATIC int socket_ioctl(struct _mod_network_socket_obj_t *socket, mp_uint_t request, mp_uint_t arg, int *_errno) {
// FIXME
if (request == MP_STREAM_POLL) {
int ret = 0;
if ((arg & MP_STREAM_POLL_RD) && 1) {
ret |= MP_STREAM_POLL_RD;
}
if ((arg & MP_STREAM_POLL_WR) && 1) {
ret |= MP_STREAM_POLL_WR;
}
return ret;
} else {
*_errno = MP_EINVAL;
return (int)MP_STREAM_ERROR;
}
}
/********************************************/
typedef struct _esp8266_obj_t {
mp_obj_base_t base;
const machine_uart_obj_t *uart;
uint8_t init;
} esp8266_obj_t;
STATIC esp8266_obj_t esp8266_obj = {
{(mp_obj_type_t *)&mod_network_nic_type_esp8266},
.uart = NULL,
.init = 0,
};
extern at_agent_t esp8266_agent;
STATIC mp_obj_t esp8266_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// check arguments
mp_arg_check_num(n_args, n_kw, 1, 1, false);
if (!esp8266_obj.init) {
machine_uart_obj_t *uart = MP_OBJ_TO_PTR(args[0]);
machine_uart_set_at_agent(uart, &esp8266_agent);
machine_uart_rx_start(uart);
if (0 != esp8266_sal_init(machine_uart_get_port(uart))) {
esp8266_sal_deinit();
machine_uart_set_at_agent(uart, NULL);
mp_raise_msg(&mp_type_OSError, "can't setup esp8266");
}
esp8266_obj.uart = uart;
esp8266_obj.init = 1;
mod_network_register_nic(MP_OBJ_FROM_PTR(&esp8266_obj));
}
return MP_OBJ_FROM_PTR(&esp8266_obj);
}
STATIC mp_obj_t esp8266_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
enum { ARG_ssid, ARG_pwd };
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_ssid, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} },
{ MP_QSTR_pwd, MP_ARG_OBJ, {.u_obj = mp_const_none} },
};
// parse args
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);
// get ssid
size_t ssid_len;
const char *ssid = mp_obj_str_get_data(args[ARG_ssid].u_obj, &ssid_len);
// get pwd
size_t pwd_len = 0;
const char *pwd = "";
if (args[ARG_pwd].u_obj != mp_const_none) {
pwd = mp_obj_str_get_data(args[ARG_pwd].u_obj, &pwd_len);
}
// connect to AP
if (esp8266_join_ap(ssid, pwd) != 0) {
mp_raise_msg_varg(&mp_type_OSError, MP_ERROR_TEXT("could not connect to ssid=%s, pwd=%s\n"), ssid, pwd);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(esp8266_connect_obj, 1, esp8266_connect);
STATIC const mp_rom_map_elem_t esp8266_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&esp8266_connect_obj) },
};
STATIC MP_DEFINE_CONST_DICT(esp8266_locals_dict, esp8266_locals_dict_table);
const mod_network_nic_type_t mod_network_nic_type_esp8266 = {
.base = {
{ &mp_type_type },
.name = MP_QSTR_ESP8266,
.make_new = esp8266_make_new,
.locals_dict = (mp_obj_dict_t *)&esp8266_locals_dict,
},
.gethostbyname = esp8266_gethostbyname,
.socket = socket_socket,
.close = socket_close,
.bind = socket_bind,
.listen = socket_listen,
.accept = socket_accept,
.connect = socket_connect,
.send = socket_send,
.recv = socket_recv,
.sendto = socket_sendto,
.recvfrom = socket_recvfrom,
.setsockopt = socket_setsockopt,
.settimeout = socket_settimeout,
.ioctl = socket_ioctl,
};
#endif /* MICROPY_PY_NETWORK && MICROPY_PY_NETWORK_ESP8266*/

View File

@@ -0,0 +1,80 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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 "py/runtime.h"
#include "shared/runtime/pyexec.h"
#include "extmod/machine_mem.h"
#include "extmod/machine_signal.h"
#include "extmod/machine_spi.h"
#include "extmod/machine_i2c.h"
#include "modmachine.h"
STATIC mp_obj_t machine_soft_reset(void) {
pyexec_system_exit = PYEXEC_FORCED_EXIT;
mp_raise_type(&mp_type_SystemExit);
}
MP_DEFINE_CONST_FUN_OBJ_0(machine_soft_reset_obj, machine_soft_reset);
STATIC const mp_rom_map_elem_t machine_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_umachine) },
{ MP_ROM_QSTR(MP_QSTR_soft_reset), MP_ROM_PTR(&machine_soft_reset_obj) },
{ MP_ROM_QSTR(MP_QSTR_mem8), MP_ROM_PTR(&machine_mem8_obj) },
{ MP_ROM_QSTR(MP_QSTR_mem16), MP_ROM_PTR(&machine_mem16_obj) },
{ MP_ROM_QSTR(MP_QSTR_mem32), MP_ROM_PTR(&machine_mem32_obj) },
{ MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&machine_pin_type) },
{ MP_ROM_QSTR(MP_QSTR_Signal), MP_ROM_PTR(&machine_signal_type) },
#if MICROPY_PY_MACHINE_I2C
#if MICROPY_PY_MACHINE_SOFTI2C
{ MP_ROM_QSTR(MP_QSTR_SoftI2C), MP_ROM_PTR(&mp_machine_soft_i2c_type) },
#endif
#endif
#if MICROPY_PY_MACHINE_SPI
{ MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&machine_hard_spi_type) },
#if MICROPY_PY_MACHINE_SOFTSPI
{ MP_ROM_QSTR(MP_QSTR_SoftSPI), MP_ROM_PTR(&mp_machine_soft_spi_type) },
#endif
#endif
{ MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&machine_uart_type) },
{ MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&machine_timer_type) },
};
STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table);
const mp_obj_module_t mp_module_machine = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&machine_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_umachine, mp_module_machine);
#endif /* MICROPY_PY_MACHINE */

View File

@@ -0,0 +1,37 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_MODMACHINE_H
#define MICROPY_INCLUDED_MODMACHINE_H
#include "py/obj.h"
#include "machine_pin.h"
#include "machine_uart.h"
#include "machine_hw_spi.h"
#include "machine_timer.h"
#endif /* MICROPY_INCLUDED_MODMACHINE_H */

View File

@@ -0,0 +1,64 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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
#include "py/runtime.h"
#include "py/smallint.h"
#include "py/obj.h"
#include "shared/timeutils/timeutils.h"
#include "extmod/utime_mphal.h"
STATIC const mp_rom_map_elem_t time_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_utime) },
// { MP_ROM_QSTR(MP_QSTR_gmtime), MP_ROM_PTR(&time_localtime_obj) },
// { MP_ROM_QSTR(MP_QSTR_localtime), MP_ROM_PTR(&time_localtime_obj) },
// { MP_ROM_QSTR(MP_QSTR_mktime), MP_ROM_PTR(&time_mktime_obj) },
// { MP_ROM_QSTR(MP_QSTR_time), MP_ROM_PTR(&time_time_obj) },
{ MP_ROM_QSTR(MP_QSTR_sleep), MP_ROM_PTR(&mp_utime_sleep_obj) },
{ MP_ROM_QSTR(MP_QSTR_sleep_ms), MP_ROM_PTR(&mp_utime_sleep_ms_obj) },
// { MP_ROM_QSTR(MP_QSTR_sleep_us), MP_ROM_PTR(&mp_utime_sleep_us_obj) },
{ MP_ROM_QSTR(MP_QSTR_ticks_ms), MP_ROM_PTR(&mp_utime_ticks_ms_obj) },
// { MP_ROM_QSTR(MP_QSTR_ticks_us), MP_ROM_PTR(&mp_utime_ticks_us_obj) },
{ MP_ROM_QSTR(MP_QSTR_ticks_cpu), MP_ROM_PTR(&mp_utime_ticks_cpu_obj) },
{ MP_ROM_QSTR(MP_QSTR_ticks_add), MP_ROM_PTR(&mp_utime_ticks_add_obj) },
{ MP_ROM_QSTR(MP_QSTR_ticks_diff), MP_ROM_PTR(&mp_utime_ticks_diff_obj) },
// { MP_ROM_QSTR(MP_QSTR_time_ns), MP_ROM_PTR(&mp_utime_time_ns_obj) },
};
STATIC MP_DEFINE_CONST_DICT(time_module_globals, time_module_globals_table);
const mp_obj_module_t mp_module_utime = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&time_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_utime, mp_module_utime);
#endif /* MICROPY_PY_UTIME */

View File

@@ -0,0 +1,361 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_TOS
#include "py/runtime.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/mpthread.h"
#include "extmod/vfs.h"
#include "vfs_tos.h"
#if !(MP_GEN_HDR)
#include "tos_vfs.h"
#endif
#include <stdio.h>
#include <string.h>
typedef struct _mp_obj_vfs_tos_t {
mp_obj_base_t base;
vstr_t root;
size_t root_len;
bool readonly;
} mp_obj_vfs_tos_t;
// It's a nice trick for reducing memory reallocation to add `path` after `self->root` directly rather create a new vstr.
// But it's not so useful on repeated calling (e.g. rename).
STATIC const char *vfs_tos_get_path_str(mp_obj_vfs_tos_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_tos_get_path_obj(mp_obj_vfs_tos_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_import_stat_t mp_vfs_tos_import_stat(void *self_in, const char *path) {
mp_obj_vfs_tos_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);
}
vfs_fstat_t st;
int ret = tos_vfs_stat(path, &st);
if (ret == 0) {
if (st.type == VFS_TYPE_DIRECTORY) {
return MP_IMPORT_STAT_DIR;
} else if (st.type == VFS_TYPE_FILE) {
return MP_IMPORT_STAT_FILE;
}
}
return MP_IMPORT_STAT_NO_EXIST;
}
STATIC mp_obj_t vfs_tos_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_tos_t *vfs = mp_obj_malloc(mp_obj_vfs_tos_t, 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_tos_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) {
mp_obj_vfs_tos_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_tos_mount_obj, vfs_tos_mount);
STATIC mp_obj_t vfs_tos_umount(mp_obj_t self_in) {
(void)self_in;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(vfs_tos_umount_obj, vfs_tos_umount);
STATIC mp_obj_t vfs_tos_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in) {
mp_obj_vfs_tos_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_tos_get_path_obj(self, path_in);
}
return mp_vfs_tos_file_open(&mp_type_textio, path_in, mode_in);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_tos_open_obj, vfs_tos_open);
STATIC mp_obj_t vfs_tos_chdir(mp_obj_t self_in, mp_obj_t path_in) {
// FIXME chdir() is not supported by tos
mp_raise_OSError(MP_EPERM);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_chdir_obj, vfs_tos_chdir);
STATIC mp_obj_t vfs_tos_getcwd(mp_obj_t self_in) {
// FIXME getcwd() is not supported by tos
return mp_obj_new_str("/", 1);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(vfs_tos_getcwd_obj, vfs_tos_getcwd);
typedef struct _vfs_tos_ilistdir_it_t {
mp_obj_base_t base;
mp_fun_1_t iternext;
bool is_str;
VFS_DIR *dir;
} vfs_tos_ilistdir_it_t;
STATIC mp_obj_t vfs_tos_ilistdir_it_iternext(mp_obj_t self_in) {
vfs_tos_ilistdir_it_t *self = MP_OBJ_FROM_PTR(self_in);
if (self->dir == NULL) {
return MP_OBJ_STOP_ITERATION;
}
for (;;) {
vfs_dirent_t *dirent = tos_vfs_readdir(self->dir);
if (dirent == NULL) {
tos_vfs_closedir(self->dir);
self->dir = NULL;
return MP_OBJ_STOP_ITERATION;
}
const char *fn = dirent->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));
}
if (dirent->type == VFS_TYPE_DIRECTORY) {
t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR);
} else if (dirent->type == VFS_TYPE_FILE) {
t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG);
} else {
// unknown type should be 0
t->items[1] = MP_OBJ_NEW_SMALL_INT(0);
}
// ino is not supported by tos
t->items[2] = MP_OBJ_NEW_SMALL_INT(0);
return MP_OBJ_FROM_PTR(t);
}
}
STATIC mp_obj_t vfs_tos_ilistdir(mp_obj_t self_in, mp_obj_t path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
vfs_tos_ilistdir_it_t *iter = mp_obj_malloc(vfs_tos_ilistdir_it_t, &mp_type_polymorph_iter);
iter->iternext = vfs_tos_ilistdir_it_iternext;
iter->is_str = mp_obj_get_type(path_in) == &mp_type_str;
const char *path = vfs_tos_get_path_str(self, path_in);
if (path[0] == '\0') {
path = ".";
}
iter->dir = tos_vfs_opendir(path);
if (iter->dir == NULL) {
// mp_raise_OSError(errno)
return mp_const_none;
}
return MP_OBJ_FROM_PTR(iter);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_ilistdir_obj, vfs_tos_ilistdir);
STATIC mp_obj_t vfs_tos_mkdir(mp_obj_t self_in, mp_obj_t path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
const char *path = vfs_tos_get_path_str(self, path_in);
int ret = tos_vfs_mkdir(path);
if (ret != 0) {
mp_raise_OSError(vfs_err_to_errno_table[-ret]);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_mkdir_obj, vfs_tos_mkdir);
STATIC mp_obj_t vfs_tos_remove(mp_obj_t self_in, mp_obj_t path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
const char *path = vfs_tos_get_path_str(self, path_in);
int ret = tos_vfs_unlink(path);
if (ret != 0) {
mp_raise_OSError(vfs_err_to_errno_table[-ret]);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_remove_obj, vfs_tos_remove);
STATIC mp_obj_t vfs_tos_rename(mp_obj_t self_in, mp_obj_t old_path_in, mp_obj_t new_path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
const char *old_path = vfs_tos_get_path_str(self, old_path_in);
// const char *new_path = vfs_tos_get_path_str(self, new_path_in);
const char *new_path = mp_obj_str_get_str(new_path_in);
vstr_t *new_path_vstr = NULL;
if (self->root_len != 0) {
int new_path_len = strlen(new_path);
new_path_vstr = vstr_new(self->root_len + new_path_len);
vstr_add_strn(new_path_vstr, self->root.buf, self->root_len);
vstr_add_strn(new_path_vstr, new_path, new_path_len);
new_path = vstr_null_terminated_str(new_path_vstr);
}
int ret = tos_vfs_rename(old_path, new_path);
if (new_path_vstr) { vstr_free(new_path_vstr); }
if (ret != 0) {
mp_raise_OSError(vfs_err_to_errno_table[-ret]);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_3(vfs_tos_rename_obj, vfs_tos_rename);
STATIC mp_obj_t vfs_tos_rmdir(mp_obj_t self_in, mp_obj_t path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
const char *path = vfs_tos_get_path_str(self, path_in);
// FIXME: rmdir is not supported by fatfs
int ret = tos_vfs_rmdir(path);
if (ret != 0) {
mp_raise_OSError(vfs_err_to_errno_table[-ret]);
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_rmdir_obj, vfs_tos_rmdir);
STATIC mp_obj_t vfs_tos_stat(mp_obj_t self_in, mp_obj_t path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
vfs_fstat_t st;
const char *path = vfs_tos_get_path_str(self, path_in);
int ret = tos_vfs_stat(path, &st);
if (ret != 0) {
mp_raise_OSError(vfs_err_to_errno_table[-ret]);
}
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
t->items[0] = MP_OBJ_NEW_SMALL_INT(st.mode);
t->items[1] = mp_obj_new_int_from_uint(0); // st_ino
t->items[2] = mp_obj_new_int_from_uint(0); // st_dev
t->items[3] = mp_obj_new_int_from_uint(0); // st_nlink
t->items[4] = mp_obj_new_int_from_uint(0); // st_uid
t->items[5] = mp_obj_new_int_from_uint(0); // st_gid
t->items[6] = mp_obj_new_int_from_uint(st.size); // st_size
t->items[7] = mp_obj_new_int_from_uint(st.atime); // st_atime
t->items[8] = mp_obj_new_int_from_uint(st.mtime); // st_mtime
t->items[9] = mp_obj_new_int_from_uint(st.ctime); // st_ctime
return MP_OBJ_FROM_PTR(t);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_stat_obj, vfs_tos_stat);
#if MICROPY_PY_UOS_STATVFS
STATIC mp_obj_t vfs_tos_statvfs(mp_obj_t self_in, mp_obj_t path_in) {
mp_obj_vfs_tos_t *self = MP_OBJ_TO_PTR(self_in);
vfs_fsstat_t st;
const char *path = vfs_tos_get_path_str(self, path_in);
int ret = tos_vfs_statfs(path, &st);
if (ret != 0) {
mp_raise_OSError(vfs_err_to_errno_table[-ret]);
}
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
t->items[0] = MP_OBJ_NEW_SMALL_INT(st.blk_size); // f_bsize
t->items[1] = MP_OBJ_NEW_SMALL_INT(st.blk_size); // f_frsize
t->items[2] = MP_OBJ_NEW_SMALL_INT(st.blk_num); // f_blocks
t->items[3] = MP_OBJ_NEW_SMALL_INT(st.blk_free); // f_bfree
t->items[4] = MP_OBJ_NEW_SMALL_INT(st.blk_avail); // f_bavail
t->items[5] = MP_OBJ_NEW_SMALL_INT(st.file_num); // f_files
t->items[6] = MP_OBJ_NEW_SMALL_INT(st.file_free); // f_ffree
t->items[7] = MP_OBJ_NEW_SMALL_INT(st.file_free); // f_favail
t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags
t->items[9] = MP_OBJ_NEW_SMALL_INT(st.name_len); // f_namemax
return MP_OBJ_FROM_PTR(t);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(vfs_tos_statvfs_obj, vfs_tos_statvfs);
#endif /* MICROPY_PY_UOS_STATVFS */
STATIC const mp_rom_map_elem_t vfs_tos_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_tos_mount_obj) },
{ MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&vfs_tos_umount_obj) },
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&vfs_tos_open_obj) },
{ MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&vfs_tos_chdir_obj) },
{ MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&vfs_tos_getcwd_obj) },
{ MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&vfs_tos_ilistdir_obj) },
{ MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&vfs_tos_mkdir_obj) },
{ MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&vfs_tos_remove_obj) },
{ MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&vfs_tos_rename_obj) },
{ MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&vfs_tos_rmdir_obj) },
{ MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&vfs_tos_stat_obj) },
#if MICROPY_PY_UOS_STATVFS
{ MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&vfs_tos_statvfs_obj) },
#endif
};
STATIC MP_DEFINE_CONST_DICT(vfs_tos_locals_dict, vfs_tos_locals_dict_table);
STATIC const mp_vfs_proto_t vfs_tos_proto = {
.import_stat = mp_vfs_tos_import_stat,
};
const mp_obj_type_t mp_type_vfs_tos = {
{ &mp_type_type },
.name = MP_QSTR_VfsTos,
.make_new = vfs_tos_make_new,
.protocol = &vfs_tos_proto,
.locals_dict = (mp_obj_dict_t *)&vfs_tos_locals_dict,
};
#endif /* MICROPY_VFS_TOS */

View File

@@ -0,0 +1,39 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_VFS_TOS_H
#define MICROPY_INCLUDED_VFS_TOS_H
#include "py/obj.h"
extern const byte vfs_err_to_errno_table[22];
extern const mp_obj_type_t mp_type_vfs_tos;
extern const mp_obj_type_t mp_type_vfs_tos_fileio;
extern const mp_obj_type_t mp_type_vfs_tos_textio;
mp_obj_t mp_vfs_tos_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_obj_t mode_in);
#endif /* MICROPY_INCLUDED_VFS_TOS_H */

View File

@@ -0,0 +1,321 @@
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2022 KY-zhang-X
*
* 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_TOS
#include "py/mphal.h"
#include "py/mpthread.h"
#include "py/runtime.h"
#include "py/stream.h"
#include "vfs_tos.h"
#include "unistd.h"
#if !(MP_GEN_HDR)
#include "tos_vfs.h"
#endif
const byte vfs_err_to_errno_table[] = {
[VFS_ERR_NONE] = 0,
[VFS_ERR_BUFFER_NULL] = MP_EINVAL,
[VFS_ERR_DEVICE_NOT_REGISTERED] = MP_ENODEV,
[VFS_ERR_DEVICE_ALREADY_REGISTERED] = 0, // should never be here
[VFS_ERR_FILE_NO_AVAILABLE] = MP_EACCES,
[VFS_ERR_FILE_NOT_OPEN] = MP_EBADF,
[VFS_ERR_FS_ALREADY_MOUNTED] = 0, // should never be here
[VFS_ERR_FS_ALREADY_REGISTERED] = 0, // should never be here
[VFS_ERR_FS_NOT_REGISTERED] = MP_ENODEV,
[VFS_ERR_FS_NOT_MOUNT] = MP_ENODEV,
[VFS_ERR_OPS_NULL] = MP_ENODEV,
[VFS_ERR_OPS_FAILED] = MP_ENODEV,
[VFS_ERR_INODE_NAME_TOO_LONG] = MP_EINVAL,
[VFS_ERR_INODE_CREATE_FAILED] = MP_ENOMEM,
[VFS_ERR_INODE_NOT_FOUND] = MP_ENOENT,
[VFS_ERR_INODE_INVALID] = MP_ENOENT,
[VFS_ERR_INODE_BUSY] = MP_EBUSY,
[VFS_ERR_INODE_INAVALIABLE] = MP_ENOENT,
[VFS_ERR_OPEN_DIR] = MP_EISDIR, // not used
[VFS_ERR_OUT_OF_MEMORY] = MP_ENOMEM,
[VFS_ERR_PARA_INVALID] = MP_EINVAL,
[VFS_ERR_PATH_TOO_LONG] = MP_EINVAL,
};
typedef struct _mp_obj_vfs_tos_file_t {
mp_obj_base_t base;
int fd;
} mp_obj_vfs_tos_file_t;
#if MICROPY_CPYTHON_COMPAT
STATIC void check_fd_is_open(const mp_obj_vfs_tos_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_tos_file_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
mp_obj_vfs_tos_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_tos_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_obj_t mode_in) {
// [REF] vfs_posix_file.c > mp_vfs_posix_file_open
// [REF] vfs_fat_file.c > mp_vfs_fat_file_open
mp_obj_vfs_tos_file_t *o = m_new_obj(mp_obj_vfs_tos_file_t);
const char *mode_s = mp_obj_str_get_str(mode_in);
int mode = 0;
while (*mode_s) {
switch (*mode_s++) {
case 'r':
mode |= VFS_OFLAG_READ;
break;
case 'w':
mode |= VFS_OFLAG_WRITE | VFS_OFLAG_CREATE_ALWAYS;
break;
case 'x':
mode |= VFS_OFLAG_WRITE | VFS_OFLAG_CREATE_NEW;
break;
case 'a':
mode |= VFS_OFLAG_WRITE | VFS_OFLAG_OPEN_ALWAYS; // FIXME: VFS_OFLAG_OPEN_APPEND ?
break;
case '+':
mode |= VFS_OFLAG_READ | VFS_OFLAG_WRITE;
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_tos_fileio;
break;
case 't':
type = &mp_type_vfs_tos_textio;
break;
#endif /* MICROPY_PY_IO_FILEIO */
}
}
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 r = tos_vfs_open(fname, mode);
if (r < 0) {
mp_raise_OSError(vfs_err_to_errno_table[-r]);
}
o->fd = r;
return MP_OBJ_FROM_PTR(o);
}
STATIC mp_obj_t vfs_tos_file_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
// [REF] vfs_posix_file.c > vfs_posix_file_make_new
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_tos_file_open(type, arg_vals[0].u_obj, arg_vals[1].u_obj);
}
STATIC mp_obj_t vfs_tos_file_fileno(mp_obj_t self_in) {
mp_obj_vfs_tos_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_tos_file_fileno_obj, vfs_tos_file_fileno);
STATIC mp_obj_t vfs_tos_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_tos_file___exit___obj, 4, 4, vfs_tos_file___exit__);
STATIC mp_uint_t vfs_tos_file_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) {
// [REF] vfs_posix_file.c > vfs_posix_file_read
mp_obj_vfs_tos_file_t *o = MP_OBJ_TO_PTR(o_in);
check_fd_is_open(o);
int r = tos_vfs_read(o->fd, buf, size);
if (r < 0) {
*errcode = vfs_err_to_errno_table[-r];
return MP_STREAM_ERROR;
}
return (mp_uint_t)r;
}
STATIC mp_uint_t vfs_tos_file_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) {
// [REF] vfs_posix_file.c > vfs_posix_file_write
mp_obj_vfs_tos_file_t *o = MP_OBJ_TO_PTR(o_in);
check_fd_is_open(o);
#if MICROPY_PY_OS_DUPTERM
// FIXME: not supported
if (o->fd <= STDERR_FILENO) {
mp_hal_stdout_tx_strn(buf, size);
return size;
}
#endif /* MICROPY_PY_OS_DUPTERM */
int r = tos_vfs_write(o->fd, buf, size);
if (r < 0) {
*errcode = vfs_err_to_errno_table[-r];
return MP_STREAM_ERROR;
}
return (mp_uint_t)r;
}
STATIC mp_uint_t vfs_tos_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) {
// [REF] vfs_posix_file.c > vfs_posix_file_ioctl
mp_obj_vfs_tos_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 r = tos_vfs_sync(o->fd);
if (r < 0) {
*errcode = vfs_err_to_errno_table[-r];
return MP_STREAM_ERROR;
}
return 0;
}
case MP_STREAM_SEEK: {
struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg;
int r = tos_vfs_lseek(o->fd, s->offset, s->whence);
if (r < 0) {
*errcode = vfs_err_to_errno_table[-r];
return MP_STREAM_ERROR;
}
s->offset = r;
return 0;
}
case MP_STREAM_CLOSE: {
int r = tos_vfs_close(o->fd);
if (r < 0) {
*errcode = vfs_err_to_errno_table[-r];
return MP_STREAM_ERROR;
}
#if MICROPY_CPYTHON_COMPAT
o->fd = -1;
#endif
return 0;
}
case MP_STREAM_GET_FILENO:
return o->fd;
#if MICROPY_PY_USELECT
case MP_STREAM_POLL: {
mp_raise_NotImplementedError(MP_ERROR_TEXT("poll on file not available on TencentOS-tiny"));
}
#endif
default:
*errcode = MP_EINVAL;
return MP_STREAM_ERROR;
}
}
STATIC const mp_rom_map_elem_t vfs_tos_rawfile_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_fileno), MP_ROM_PTR(&vfs_tos_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_tos_file___exit___obj) },
};
STATIC MP_DEFINE_CONST_DICT(vfs_tos_rawfile_locals_dict, vfs_tos_rawfile_locals_dict_table);
#if MICROPY_PY_IO_FILEIO
STATIC const mp_stream_p_t vfs_tos_fileio_stream_p = {
.read = vfs_tos_file_read,
.write = vfs_tos_file_write,
.ioctl = vfs_tos_file_ioctl,
};
const mp_obj_type_t mp_type_vfs_tos_fileio = {
{ &mp_type_type },
.name = MP_QSTR_FileIO,
.print = vfs_tos_file_print,
.make_new = vfs_tos_file_make_new,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &vfs_tos_fileio_stream_p,
.locals_dict = (mp_obj_dict_t *)&vfs_tos_rawfile_locals_dict,
};
#endif /* MICROPY_PY_IO_FILEIO */
STATIC const mp_stream_p_t vfs_tos_textio_stream_p = {
.read = vfs_tos_file_read,
.write = vfs_tos_file_write,
.ioctl = vfs_tos_file_ioctl,
.is_text = true,
};
const mp_obj_type_t mp_type_vfs_tos_textio = {
{&mp_type_type},
.name = MP_QSTR_TextIOWrapper,
.print = vfs_tos_file_print,
.make_new = vfs_tos_file_make_new,
.getiter = mp_identity_getiter,
.iternext = mp_stream_unbuffered_iter,
.protocol = &vfs_tos_textio_stream_p,
.locals_dict = (mp_obj_dict_t *)&vfs_tos_rawfile_locals_dict,
};
// Note: buffering and encoding args are currently ignored
mp_obj_t mp_builtin_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 the file is an integer then delegate straight to the POSIX handler
return mp_vfs_tos_file_open(&mp_type_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj);
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
#endif /* MICROPY_VFS_TOS */