diff options
| author | Damien George <damien.p.george@gmail.com> | 2017-09-06 13:40:51 +1000 |
|---|---|---|
| committer | Damien George <damien.p.george@gmail.com> | 2017-09-06 13:40:51 +1000 |
| commit | 01dd7804b87d60b2deab16712eccb3b97351a9b7 (patch) | |
| tree | 1aa21f38a872b8e62a3d4e4f74f68033c6f827e4 /cc3200/mods | |
| parent | a9862b30068fc9df1022f08019fb35aaa5085f64 (diff) | |
ports: Make new ports/ sub-directory and move all ports there.
This is to keep the top-level directory clean, to make it clear what is
core and what is a port, and to allow the repository to grow with new ports
in a sustainable way.
Diffstat (limited to 'cc3200/mods')
37 files changed, 0 insertions, 9419 deletions
diff --git a/cc3200/mods/modmachine.c b/cc3200/mods/modmachine.c deleted file mode 100644 index fb0fe7f2c..000000000 --- a/cc3200/mods/modmachine.c +++ /dev/null @@ -1,213 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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 "py/mpstate.h" -#include "py/runtime.h" -#include "py/mphal.h" -#include "irq.h" -#include "inc/hw_types.h" -#include "inc/hw_gpio.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "inc/hw_uart.h" -#include "rom_map.h" -#include "prcm.h" -#include "pybuart.h" -#include "pybpin.h" -#include "pybrtc.h" -#include "simplelink.h" -#include "modnetwork.h" -#include "modwlan.h" -#include "moduos.h" -#include "FreeRTOS.h" -#include "portable.h" -#include "task.h" -#include "mpexception.h" -#include "random.h" -#include "pybadc.h" -#include "pybi2c.h" -#include "pybsd.h" -#include "pybwdt.h" -#include "pybsleep.h" -#include "pybspi.h" -#include "pybtimer.h" -#include "utils.h" -#include "gccollect.h" - - -#ifdef DEBUG -extern OsiTaskHandle mpTaskHandle; -extern OsiTaskHandle svTaskHandle; -extern OsiTaskHandle xSimpleLinkSpawnTaskHndl; -#endif - - -/// \module machine - functions related to the SoC -/// - -/******************************************************************************/ -// MicroPython bindings; - -STATIC mp_obj_t machine_reset(void) { - // disable wlan - wlan_stop(SL_STOP_TIMEOUT_LONG); - // reset the cpu and it's peripherals - MAP_PRCMMCUReset(true); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_reset_obj, machine_reset); - -#ifdef DEBUG -STATIC mp_obj_t machine_info(uint n_args, const mp_obj_t *args) { - // FreeRTOS info - { - printf("---------------------------------------------\n"); - printf("FreeRTOS\n"); - printf("---------------------------------------------\n"); - printf("Total heap: %u\n", configTOTAL_HEAP_SIZE); - printf("Free heap: %u\n", xPortGetFreeHeapSize()); - printf("MpTask min free stack: %u\n", (unsigned int)uxTaskGetStackHighWaterMark((TaskHandle_t)mpTaskHandle)); - printf("ServersTask min free stack: %u\n", (unsigned int)uxTaskGetStackHighWaterMark((TaskHandle_t)svTaskHandle)); - printf("SlTask min free stack: %u\n", (unsigned int)uxTaskGetStackHighWaterMark(xSimpleLinkSpawnTaskHndl)); - printf("IdleTask min free stack: %u\n", (unsigned int)uxTaskGetStackHighWaterMark(xTaskGetIdleTaskHandle())); - - uint32_t *pstack = (uint32_t *)&_stack; - while (*pstack == 0x55555555) { - pstack++; - } - printf("MAIN min free stack: %u\n", pstack - ((uint32_t *)&_stack)); - printf("---------------------------------------------\n"); - } - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(machine_info_obj, 0, 1, machine_info); -#endif - -STATIC mp_obj_t machine_freq(void) { - return mp_obj_new_int(HAL_FCPU_HZ); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_freq_obj, machine_freq); - -STATIC mp_obj_t machine_unique_id(void) { - uint8_t mac[SL_BSSID_LENGTH]; - wlan_get_mac (mac); - return mp_obj_new_bytes(mac, SL_BSSID_LENGTH); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_unique_id_obj, machine_unique_id); - -STATIC mp_obj_t machine_main(mp_obj_t main) { - if (MP_OBJ_IS_STR(main)) { - MP_STATE_PORT(machine_config_main) = main; - } else { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(machine_main_obj, machine_main); - -STATIC mp_obj_t machine_idle(void) { - __WFI(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_idle_obj, machine_idle); - -STATIC mp_obj_t machine_sleep (void) { - pyb_sleep_sleep(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_sleep_obj, machine_sleep); - -STATIC mp_obj_t machine_deepsleep (void) { - pyb_sleep_deepsleep(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_deepsleep_obj, machine_deepsleep); - -STATIC mp_obj_t machine_reset_cause (void) { - return mp_obj_new_int(pyb_sleep_get_reset_cause()); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_reset_cause_obj, machine_reset_cause); - -STATIC mp_obj_t machine_wake_reason (void) { - return mp_obj_new_int(pyb_sleep_get_wake_reason()); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(machine_wake_reason_obj, machine_wake_reason); - -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_reset), MP_ROM_PTR(&machine_reset_obj) }, -#ifdef DEBUG - { MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&machine_info_obj) }, -#endif - { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&machine_freq_obj) }, - { MP_ROM_QSTR(MP_QSTR_unique_id), MP_ROM_PTR(&machine_unique_id_obj) }, - { MP_ROM_QSTR(MP_QSTR_main), MP_ROM_PTR(&machine_main_obj) }, - { MP_ROM_QSTR(MP_QSTR_rng), MP_ROM_PTR(&machine_rng_get_obj) }, - { MP_ROM_QSTR(MP_QSTR_idle), MP_ROM_PTR(&machine_idle_obj) }, - { MP_ROM_QSTR(MP_QSTR_sleep), MP_ROM_PTR(&machine_sleep_obj) }, - { MP_ROM_QSTR(MP_QSTR_deepsleep), MP_ROM_PTR(&machine_deepsleep_obj) }, - { MP_ROM_QSTR(MP_QSTR_reset_cause), MP_ROM_PTR(&machine_reset_cause_obj) }, - { MP_ROM_QSTR(MP_QSTR_wake_reason), MP_ROM_PTR(&machine_wake_reason_obj) }, - - { MP_ROM_QSTR(MP_QSTR_disable_irq), MP_ROM_PTR(&pyb_disable_irq_obj) }, - { MP_ROM_QSTR(MP_QSTR_enable_irq), MP_ROM_PTR(&pyb_enable_irq_obj) }, - - { MP_ROM_QSTR(MP_QSTR_RTC), MP_ROM_PTR(&pyb_rtc_type) }, - { MP_ROM_QSTR(MP_QSTR_Pin), MP_ROM_PTR(&pin_type) }, - { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pyb_adc_type) }, - { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&pyb_i2c_type) }, - { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&pyb_spi_type) }, - { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&pyb_uart_type) }, - { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&pyb_timer_type) }, - { MP_ROM_QSTR(MP_QSTR_WDT), MP_ROM_PTR(&pyb_wdt_type) }, - { MP_ROM_QSTR(MP_QSTR_SD), MP_ROM_PTR(&pyb_sd_type) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_IDLE), MP_ROM_INT(PYB_PWR_MODE_ACTIVE) }, - { MP_ROM_QSTR(MP_QSTR_SLEEP), MP_ROM_INT(PYB_PWR_MODE_LPDS) }, - { MP_ROM_QSTR(MP_QSTR_DEEPSLEEP), MP_ROM_INT(PYB_PWR_MODE_HIBERNATE) }, - { MP_ROM_QSTR(MP_QSTR_POWER_ON), MP_ROM_INT(PYB_SLP_PWRON_RESET) }, // legacy constant - { MP_ROM_QSTR(MP_QSTR_PWRON_RESET), MP_ROM_INT(PYB_SLP_PWRON_RESET) }, - { MP_ROM_QSTR(MP_QSTR_HARD_RESET), MP_ROM_INT(PYB_SLP_HARD_RESET) }, - { MP_ROM_QSTR(MP_QSTR_WDT_RESET), MP_ROM_INT(PYB_SLP_WDT_RESET) }, - { MP_ROM_QSTR(MP_QSTR_DEEPSLEEP_RESET), MP_ROM_INT(PYB_SLP_HIB_RESET) }, - { MP_ROM_QSTR(MP_QSTR_SOFT_RESET), MP_ROM_INT(PYB_SLP_SOFT_RESET) }, - { MP_ROM_QSTR(MP_QSTR_WLAN_WAKE), MP_ROM_INT(PYB_SLP_WAKED_BY_WLAN) }, - { MP_ROM_QSTR(MP_QSTR_PIN_WAKE), MP_ROM_INT(PYB_SLP_WAKED_BY_GPIO) }, - { MP_ROM_QSTR(MP_QSTR_RTC_WAKE), MP_ROM_INT(PYB_SLP_WAKED_BY_RTC) }, -}; - -STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table); - -const mp_obj_module_t machine_module = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, -}; diff --git a/cc3200/mods/modnetwork.c b/cc3200/mods/modnetwork.c deleted file mode 100644 index 0234a0ccb..000000000 --- a/cc3200/mods/modnetwork.c +++ /dev/null @@ -1,182 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpstate.h" -#include "py/obj.h" -#include "py/nlr.h" -#include "py/runtime.h" -#include "py/mperrno.h" -#include "py/mphal.h" -#include "modnetwork.h" -#include "mpexception.h" -#include "serverstask.h" -#include "simplelink.h" - - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef struct { - mp_obj_base_t base; -} network_server_obj_t; - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC network_server_obj_t network_server_obj; -STATIC const mp_obj_type_t network_server_type; - -/// \module network - network configuration -/// -/// This module provides network drivers and server configuration. - -void mod_network_init0(void) { -} - -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) -STATIC mp_obj_t network_server_init_helper(mp_obj_t self, const mp_arg_val_t *args) { - const char *user = SERVERS_DEF_USER; - const char *pass = SERVERS_DEF_PASS; - if (args[0].u_obj != MP_OBJ_NULL) { - mp_obj_t *login; - mp_obj_get_array_fixed_n(args[0].u_obj, 2, &login); - user = mp_obj_str_get_str(login[0]); - pass = mp_obj_str_get_str(login[1]); - } - - uint32_t timeout = SERVERS_DEF_TIMEOUT_MS / 1000; - if (args[1].u_obj != MP_OBJ_NULL) { - timeout = mp_obj_get_int(args[1].u_obj); - } - - // configure the new login - servers_set_login ((char *)user, (char *)pass); - - // configure the timeout - servers_set_timeout(timeout * 1000); - - // start the servers - servers_start(); - - return mp_const_none; -} - -STATIC const mp_arg_t network_server_args[] = { - { MP_QSTR_id, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_login, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -}; -STATIC mp_obj_t network_server_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(network_server_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), network_server_args, args); - - // check the server id - if (args[0].u_obj != MP_OBJ_NULL) { - if (mp_obj_get_int(args[0].u_obj) != 0) { - mp_raise_OSError(MP_ENODEV); - } - } - - // setup the object and initialize it - network_server_obj_t *self = &network_server_obj; - self->base.type = &network_server_type; - network_server_init_helper(self, &args[1]); - - return (mp_obj_t)self; -} - -STATIC mp_obj_t network_server_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(network_server_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &network_server_args[1], args); - return network_server_init_helper(pos_args[0], args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(network_server_init_obj, 1, network_server_init); - -// timeout value given in seconds -STATIC mp_obj_t network_server_timeout(size_t n_args, const mp_obj_t *args) { - if (n_args > 1) { - uint32_t timeout = mp_obj_get_int(args[1]); - servers_set_timeout(timeout * 1000); - return mp_const_none; - } else { - // get - return mp_obj_new_int(servers_get_timeout() / 1000); - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(network_server_timeout_obj, 1, 2, network_server_timeout); - -STATIC mp_obj_t network_server_running(mp_obj_t self_in) { - // get - return mp_obj_new_bool(servers_are_enabled()); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_server_running_obj, network_server_running); - -STATIC mp_obj_t network_server_deinit(mp_obj_t self_in) { - // simply stop the servers - servers_stop(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(network_server_deinit_obj, network_server_deinit); -#endif - -STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_network) }, - { MP_ROM_QSTR(MP_QSTR_WLAN), MP_ROM_PTR(&mod_network_nic_type_wlan) }, - -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - { MP_ROM_QSTR(MP_QSTR_Server), MP_ROM_PTR(&network_server_type) }, -#endif -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table); - -const mp_obj_module_t mp_module_network = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_network_globals, -}; - -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) -STATIC const mp_rom_map_elem_t network_server_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&network_server_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&network_server_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_timeout), MP_ROM_PTR(&network_server_timeout_obj) }, - { MP_ROM_QSTR(MP_QSTR_isrunning), MP_ROM_PTR(&network_server_running_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(network_server_locals_dict, network_server_locals_dict_table); - -STATIC const mp_obj_type_t network_server_type = { - { &mp_type_type }, - .name = MP_QSTR_Server, - .make_new = network_server_make_new, - .locals_dict = (mp_obj_t)&network_server_locals_dict, -}; -#endif diff --git a/cc3200/mods/modnetwork.h b/cc3200/mods/modnetwork.h deleted file mode 100644 index 6ec90a2ba..000000000 --- a/cc3200/mods/modnetwork.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_MODNETWORK_H -#define MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define MOD_NETWORK_IPV4ADDR_BUF_SIZE (4) - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef struct _mod_network_nic_type_t { - mp_obj_type_t base; -} mod_network_nic_type_t; - -typedef struct _mod_network_socket_base_t { - union { - struct { - // this order is important so that fileno gets > 0 once - // the socket descriptor is assigned after being created. - uint8_t domain; - int8_t fileno; - uint8_t type; - uint8_t proto; - } u_param; - int16_t sd; - }; - uint32_t timeout_ms; // 0 for no timeout - bool cert_req; -} mod_network_socket_base_t; - -typedef struct _mod_network_socket_obj_t { - mp_obj_base_t base; - mod_network_socket_base_t sock_base; -} mod_network_socket_obj_t; - -/****************************************************************************** - EXPORTED DATA - ******************************************************************************/ -extern const mod_network_nic_type_t mod_network_nic_type_wlan; - -/****************************************************************************** - DECLARE FUNCTIONS - ******************************************************************************/ -void mod_network_init0(void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_MODNETWORK_H diff --git a/cc3200/mods/modubinascii.c b/cc3200/mods/modubinascii.c deleted file mode 100644 index 7f51a8f3d..000000000 --- a/cc3200/mods/modubinascii.c +++ /dev/null @@ -1,62 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2014 Paul Sokolovsky - * Copyright (c) 2015 Daniel Campora - * - * 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/nlr.h" -#include "py/runtime.h" -#include "py/binary.h" -#include "extmod/modubinascii.h" -#include "modubinascii.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_nvic.h" -#include "inc/hw_dthe.h" -#include "hw_memmap.h" -#include "rom_map.h" -#include "prcm.h" -#include "crc.h" -#include "cryptohash.h" -#include "mpexception.h" - - -/******************************************************************************/ -// MicroPython bindings - -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) }, -}; - -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, -}; diff --git a/cc3200/mods/modubinascii.h b/cc3200/mods/modubinascii.h deleted file mode 100644 index eb9fc4f21..000000000 --- a/cc3200/mods/modubinascii.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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. - */ -#ifndef MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H -#define MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H - - -#endif // MICROPY_INCLUDED_CC3200_MODS_MODUBINASCII_H diff --git a/cc3200/mods/moduhashlib.c b/cc3200/mods/moduhashlib.c deleted file mode 100644 index bec88d7ca..000000000 --- a/cc3200/mods/moduhashlib.c +++ /dev/null @@ -1,209 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2014 Paul Sokolovsky - * Copyright (c) 2015 Daniel Campora - * - * 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/mpconfig.h" -#include MICROPY_HAL_H -#include "py/nlr.h" -#include "py/runtime.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_nvic.h" -#include "inc/hw_shamd5.h" -#include "inc/hw_dthe.h" -#include "hw_memmap.h" -#include "rom_map.h" -#include "prcm.h" -#include "shamd5.h" -#include "cryptohash.h" -#include "mpexception.h" - - -/****************************************************************************** - DEFINE PRIVATE TYPES - ******************************************************************************/ -typedef struct _mp_obj_hash_t { - mp_obj_base_t base; - uint8_t *buffer; - uint32_t b_size; - uint32_t c_size; - uint8_t algo; - uint8_t h_size; - bool fixedlen; - bool digested; - uint8_t hash[32]; -} mp_obj_hash_t; - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void hash_update_internal(mp_obj_t self_in, mp_obj_t data, bool digest); -STATIC mp_obj_t hash_read (mp_obj_t self_in); - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void hash_update_internal(mp_obj_t self_in, mp_obj_t data, bool digest) { - mp_obj_hash_t *self = self_in; - mp_buffer_info_t bufinfo; - - if (data) { - mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); - } - - if (digest) { - CRYPTOHASH_SHAMD5Start (self->algo, self->b_size); - } - - if (self->c_size < self->b_size || !data || !self->fixedlen) { - if (digest || self->fixedlen) { - // no data means we want to process our internal buffer - CRYPTOHASH_SHAMD5Update (data ? bufinfo.buf : self->buffer, data ? bufinfo.len : self->b_size); - self->c_size += data ? bufinfo.len : 0; - } else { - self->buffer = m_renew(byte, self->buffer, self->b_size, self->b_size + bufinfo.len); - mp_seq_copy((byte*)self->buffer + self->b_size, bufinfo.buf, bufinfo.len, byte); - self->b_size += bufinfo.len; - self->digested = false; - } - } else { - mp_raise_OSError(MP_EPERM); - } -} - -STATIC mp_obj_t hash_read (mp_obj_t self_in) { - mp_obj_hash_t *self = self_in; - - if (!self->fixedlen) { - if (!self->digested) { - hash_update_internal(self, MP_OBJ_NULL, true); - } - } else if (self->c_size < self->b_size) { - // it's a fixed len block which is still incomplete - mp_raise_OSError(MP_EPERM); - } - - if (!self->digested) { - CRYPTOHASH_SHAMD5Read ((uint8_t *)self->hash); - self->digested = true; - } - return mp_obj_new_bytes(self->hash, self->h_size); -} - -/******************************************************************************/ -// MicroPython bindings - -/// \classmethod \constructor([data[, block_size]]) -/// initial data must be given if block_size wants to be passed -STATIC mp_obj_t hash_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, 0, 2, false); - mp_obj_hash_t *self = m_new0(mp_obj_hash_t, 1); - self->base.type = type_in; - if (self->base.type->name == MP_QSTR_sha1) { - self->algo = SHAMD5_ALGO_SHA1; - self->h_size = 20; - } else /* if (self->base.type->name == MP_QSTR_sha256) */ { - self->algo = SHAMD5_ALGO_SHA256; - self->h_size = 32; - } /* else { - self->algo = SHAMD5_ALGO_MD5; - self->h_size = 32; - } */ - - if (n_args) { - // CPython extension to avoid buffering the data before digesting it - // Note: care must be taken to provide all intermediate blocks as multiple - // of four bytes, otherwise the resulting hash will be incorrect. - // the final block can be of any length - if (n_args > 1) { - // block size given, we will feed the data directly into the hash engine - self->fixedlen = true; - self->b_size = mp_obj_get_int(args[1]); - hash_update_internal(self, args[0], true); - } else { - hash_update_internal(self, args[0], false); - } - } - return self; -} - -STATIC mp_obj_t hash_update(mp_obj_t self_in, mp_obj_t arg) { - mp_obj_hash_t *self = self_in; - hash_update_internal(self, arg, false); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_2(hash_update_obj, hash_update); - -STATIC mp_obj_t hash_digest(mp_obj_t self_in) { - return hash_read(self_in); -} -MP_DEFINE_CONST_FUN_OBJ_1(hash_digest_obj, hash_digest); - -STATIC const mp_rom_map_elem_t hash_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&hash_update_obj) }, - { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&hash_digest_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(hash_locals_dict, hash_locals_dict_table); - -//STATIC const mp_obj_type_t md5_type = { -// { &mp_type_type }, -// .name = MP_QSTR_md5, -// .make_new = hash_make_new, -// .locals_dict = (mp_obj_t)&hash_locals_dict, -//}; - -STATIC const mp_obj_type_t sha1_type = { - { &mp_type_type }, - .name = MP_QSTR_sha1, - .make_new = hash_make_new, - .locals_dict = (mp_obj_t)&hash_locals_dict, -}; - -STATIC const mp_obj_type_t sha256_type = { - { &mp_type_type }, - .name = MP_QSTR_sha256, - .make_new = hash_make_new, - .locals_dict = (mp_obj_t)&hash_locals_dict, -}; - -STATIC const mp_rom_map_elem_t mp_module_hashlib_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uhashlib) }, - //{ MP_ROM_QSTR(MP_QSTR_md5), MP_ROM_PTR(&md5_type) }, - { MP_ROM_QSTR(MP_QSTR_sha1), MP_ROM_PTR(&sha1_type) }, - { MP_ROM_QSTR(MP_QSTR_sha256), MP_ROM_PTR(&sha256_type) }, -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_hashlib_globals, mp_module_hashlib_globals_table); - -const mp_obj_module_t mp_module_uhashlib = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_hashlib_globals, -}; - diff --git a/cc3200/mods/moduos.c b/cc3200/mods/moduos.c deleted file mode 100644 index ba8fd86a6..000000000 --- a/cc3200/mods/moduos.c +++ /dev/null @@ -1,184 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpstate.h" -#include "py/nlr.h" -#include "py/objtuple.h" -#include "py/objstr.h" -#include "py/runtime.h" -#include "lib/timeutils/timeutils.h" -#include "lib/oofatfs/ff.h" -#include "lib/oofatfs/diskio.h" -#include "genhdr/mpversion.h" -#include "moduos.h" -#include "sflash_diskio.h" -#include "extmod/vfs.h" -#include "extmod/vfs_fat.h" -#include "random.h" -#include "mpexception.h" -#include "version.h" -#include "pybsd.h" -#include "pybuart.h" - -/// \module os - basic "operating system" services -/// -/// The `os` module contains functions for filesystem access and `urandom`. -/// -/// The filesystem has `/` as the root directory, and the available physical -/// drives are accessible from here. They are currently: -/// -/// /flash -- the serial flash filesystem -/// -/// On boot up, the current directory is `/flash`. - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC os_term_dup_obj_t os_term_dup_obj; - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ - -void osmount_unmount_all (void) { - //TODO - /* - for (mp_uint_t i = 0; i < MP_STATE_PORT(mount_obj_list).len; i++) { - os_fs_mount_t *mount_obj = ((os_fs_mount_t *)(MP_STATE_PORT(mount_obj_list).items[i])); - unmount(mount_obj); - } - */ -} - -/******************************************************************************/ -// MicroPython bindings -// - -STATIC const qstr os_uname_info_fields[] = { - MP_QSTR_sysname, MP_QSTR_nodename, - MP_QSTR_release, MP_QSTR_version, MP_QSTR_machine -}; -STATIC const MP_DEFINE_STR_OBJ(os_uname_info_sysname_obj, MICROPY_PY_SYS_PLATFORM); -STATIC const MP_DEFINE_STR_OBJ(os_uname_info_nodename_obj, MICROPY_PY_SYS_PLATFORM); -STATIC const MP_DEFINE_STR_OBJ(os_uname_info_release_obj, WIPY_SW_VERSION_NUMBER); -STATIC const MP_DEFINE_STR_OBJ(os_uname_info_version_obj, MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE); -STATIC const MP_DEFINE_STR_OBJ(os_uname_info_machine_obj, MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME); -STATIC MP_DEFINE_ATTRTUPLE( - os_uname_info_obj, - os_uname_info_fields, - 5, - (mp_obj_t)&os_uname_info_sysname_obj, - (mp_obj_t)&os_uname_info_nodename_obj, - (mp_obj_t)&os_uname_info_release_obj, - (mp_obj_t)&os_uname_info_version_obj, - (mp_obj_t)&os_uname_info_machine_obj -); - -STATIC mp_obj_t os_uname(void) { - return (mp_obj_t)&os_uname_info_obj; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(os_uname_obj, os_uname); - -STATIC mp_obj_t os_sync(void) { - sflash_disk_flush(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(os_sync_obj, os_sync); - -STATIC mp_obj_t os_urandom(mp_obj_t num) { - mp_int_t n = mp_obj_get_int(num); - vstr_t vstr; - vstr_init_len(&vstr, n); - for (int i = 0; i < n; i++) { - vstr.buf[i] = rng_get(); - } - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(os_urandom_obj, os_urandom); - -STATIC mp_obj_t os_dupterm(uint n_args, const mp_obj_t *args) { - if (n_args == 0) { - if (MP_STATE_PORT(os_term_dup_obj) == MP_OBJ_NULL) { - return mp_const_none; - } else { - return MP_STATE_PORT(os_term_dup_obj)->stream_o; - } - } else { - mp_obj_t stream_o = args[0]; - if (stream_o == mp_const_none) { - MP_STATE_PORT(os_term_dup_obj) = MP_OBJ_NULL; - } else { - if (!MP_OBJ_IS_TYPE(stream_o, &pyb_uart_type)) { - // must be a stream-like object providing at least read and write methods - mp_load_method(stream_o, MP_QSTR_read, os_term_dup_obj.read); - mp_load_method(stream_o, MP_QSTR_write, os_term_dup_obj.write); - } - os_term_dup_obj.stream_o = stream_o; - MP_STATE_PORT(os_term_dup_obj) = &os_term_dup_obj; - } - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(os_dupterm_obj, 0, 1, os_dupterm); - -STATIC const mp_rom_map_elem_t os_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uos) }, - - { MP_ROM_QSTR(MP_QSTR_uname), MP_ROM_PTR(&os_uname_obj) }, - - { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&mp_vfs_chdir_obj) }, - { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&mp_vfs_getcwd_obj) }, - { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&mp_vfs_ilistdir_obj) }, - { MP_ROM_QSTR(MP_QSTR_listdir), MP_ROM_PTR(&mp_vfs_listdir_obj) }, - { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&mp_vfs_mkdir_obj) }, - { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&mp_vfs_rename_obj) }, - { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&mp_vfs_remove_obj) }, - { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&mp_vfs_rmdir_obj) }, - { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&mp_vfs_stat_obj) }, - { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mp_vfs_remove_obj) }, // unlink aliases to remove - - { MP_ROM_QSTR(MP_QSTR_sync), MP_ROM_PTR(&os_sync_obj) }, - { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&os_urandom_obj) }, - - // MicroPython additions - // removed: mkfs - // renamed: unmount -> umount - { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&mp_vfs_mount_obj) }, - { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&mp_vfs_umount_obj) }, - { MP_ROM_QSTR(MP_QSTR_VfsFat), MP_ROM_PTR(&mp_fat_vfs_type) }, - { MP_ROM_QSTR(MP_QSTR_dupterm), MP_ROM_PTR(&os_dupterm_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(os_module_globals, os_module_globals_table); - -const mp_obj_module_t mp_module_uos = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&os_module_globals, -}; diff --git a/cc3200/mods/moduos.h b/cc3200/mods/moduos.h deleted file mode 100644 index f183715c9..000000000 --- a/cc3200/mods/moduos.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_MODUOS_H -#define MICROPY_INCLUDED_CC3200_MODS_MODUOS_H - -#include "py/obj.h" - -/****************************************************************************** - DEFINE PUBLIC TYPES - ******************************************************************************/ - -typedef struct _os_term_dup_obj_t { - mp_obj_t stream_o; - mp_obj_t read[3]; - mp_obj_t write[3]; -} os_term_dup_obj_t; - -/****************************************************************************** - DECLARE PUBLIC FUNCTIONS - ******************************************************************************/ -void osmount_unmount_all (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_MODUOS_H diff --git a/cc3200/mods/modusocket.c b/cc3200/mods/modusocket.c deleted file mode 100644 index f587e765a..000000000 --- a/cc3200/mods/modusocket.c +++ /dev/null @@ -1,824 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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 "simplelink.h" -#include "py/mpconfig.h" -#include "py/obj.h" -#include "py/objstr.h" -#include "py/runtime.h" -#include "py/stream.h" -#include "py/mphal.h" -#include "lib/netutils/netutils.h" -#include "modnetwork.h" -#include "modusocket.h" -#include "mpexception.h" - -/******************************************************************************/ -// The following set of macros and functions provide a glue between the CC3100 -// simplelink layer and the functions/methods provided by the usocket module. -// They were historically in a separate file because usocket was designed to -// work with multiple NICs, and the wlan_XXX functions just provided one -// particular NIC implementation (that of the CC3100). But the CC3200 port only -// supports a single NIC (being the CC3100) so it's unnecessary and inefficient -// to provide an intermediate wrapper layer. Hence the wlan_XXX functions -// are provided below as static functions so they can be inlined directly by -// the corresponding usocket calls. - -#define WLAN_MAX_RX_SIZE 16000 -#define WLAN_MAX_TX_SIZE 1476 - -#define MAKE_SOCKADDR(addr, ip, port) SlSockAddr_t addr; \ - addr.sa_family = SL_AF_INET; \ - addr.sa_data[0] = port >> 8; \ - addr.sa_data[1] = port; \ - addr.sa_data[2] = ip[3]; \ - addr.sa_data[3] = ip[2]; \ - addr.sa_data[4] = ip[1]; \ - addr.sa_data[5] = ip[0]; - -#define UNPACK_SOCKADDR(addr, ip, port) port = (addr.sa_data[0] << 8) | addr.sa_data[1]; \ - ip[0] = addr.sa_data[5]; \ - ip[1] = addr.sa_data[4]; \ - ip[2] = addr.sa_data[3]; \ - ip[3] = addr.sa_data[2]; - -#define SOCKET_TIMEOUT_QUANTA_MS (20) - -STATIC int convert_sl_errno(int sl_errno) { - return -sl_errno; -} - -// This function is left as non-static so it's not inlined. -int check_timedout(mod_network_socket_obj_t *s, int ret, uint32_t *timeout_ms, int *_errno) { - if (*timeout_ms == 0 || ret != SL_EAGAIN) { - if (s->sock_base.timeout_ms > 0 && ret == SL_EAGAIN) { - *_errno = MP_ETIMEDOUT; - } else { - *_errno = convert_sl_errno(ret); - } - return -1; - } - mp_hal_delay_ms(SOCKET_TIMEOUT_QUANTA_MS); - if (*timeout_ms < SOCKET_TIMEOUT_QUANTA_MS) { - *timeout_ms = 0; - } else { - *timeout_ms -= SOCKET_TIMEOUT_QUANTA_MS; - } - return 0; -} - -STATIC int wlan_gethostbyname(const char *name, mp_uint_t len, uint8_t *out_ip, uint8_t family) { - uint32_t ip; - int result = sl_NetAppDnsGetHostByName((_i8 *)name, (_u16)len, (_u32*)&ip, (_u8)family); - out_ip[0] = ip; - out_ip[1] = ip >> 8; - out_ip[2] = ip >> 16; - out_ip[3] = ip >> 24; - return result; -} - -STATIC int wlan_socket_socket(mod_network_socket_obj_t *s, int *_errno) { - int16_t sd = sl_Socket(s->sock_base.u_param.domain, s->sock_base.u_param.type, s->sock_base.u_param.proto); - if (sd < 0) { - *_errno = sd; - return -1; - } - s->sock_base.sd = sd; - return 0; -} - -STATIC void wlan_socket_close(mod_network_socket_obj_t *s) { - // this is to prevent the finalizer to close a socket that failed when being created - if (s->sock_base.sd >= 0) { - modusocket_socket_delete(s->sock_base.sd); - sl_Close(s->sock_base.sd); - s->sock_base.sd = -1; - } -} - -STATIC int wlan_socket_bind(mod_network_socket_obj_t *s, byte *ip, mp_uint_t port, int *_errno) { - MAKE_SOCKADDR(addr, ip, port) - int ret = sl_Bind(s->sock_base.sd, &addr, sizeof(addr)); - if (ret != 0) { - *_errno = ret; - return -1; - } - return 0; -} - -STATIC int wlan_socket_listen(mod_network_socket_obj_t *s, mp_int_t backlog, int *_errno) { - int ret = sl_Listen(s->sock_base.sd, backlog); - if (ret != 0) { - *_errno = ret; - return -1; - } - return 0; -} - -STATIC int wlan_socket_accept(mod_network_socket_obj_t *s, mod_network_socket_obj_t *s2, byte *ip, mp_uint_t *port, int *_errno) { - // accept incoming connection - int16_t sd; - SlSockAddr_t addr; - SlSocklen_t addr_len = sizeof(addr); - - uint32_t timeout_ms = s->sock_base.timeout_ms; - for (;;) { - sd = sl_Accept(s->sock_base.sd, &addr, &addr_len); - if (sd >= 0) { - // save the socket descriptor - s2->sock_base.sd = sd; - // return ip and port - UNPACK_SOCKADDR(addr, ip, *port); - return 0; - } - if (check_timedout(s, sd, &timeout_ms, _errno)) { - return -1; - } - } -} - -STATIC int wlan_socket_connect(mod_network_socket_obj_t *s, byte *ip, mp_uint_t port, int *_errno) { - MAKE_SOCKADDR(addr, ip, port) - uint32_t timeout_ms = s->sock_base.timeout_ms; - - // For a non-blocking connect the CC3100 will return SL_EALREADY while the - // connection is in progress. - - for (;;) { - int ret = sl_Connect(s->sock_base.sd, &addr, sizeof(addr)); - if (ret == 0) { - return 0; - } - - // Check if we are in non-blocking mode and the connection is in progress - if (s->sock_base.timeout_ms == 0 && ret == SL_EALREADY) { - // To match BSD we return EINPROGRESS here - *_errno = MP_EINPROGRESS; - return -1; - } - - // We are in blocking mode, so if the connection isn't in progress then error out - if (ret != SL_EALREADY) { - *_errno = convert_sl_errno(ret); - return -1; - } - - if (check_timedout(s, SL_EAGAIN, &timeout_ms, _errno)) { - return -1; - } - } -} - -STATIC int wlan_socket_send(mod_network_socket_obj_t *s, const byte *buf, mp_uint_t len, int *_errno) { - if (len == 0) { - return 0; - } - uint32_t timeout_ms = s->sock_base.timeout_ms; - for (;;) { - int ret = sl_Send(s->sock_base.sd, (const void *)buf, len, 0); - if (ret > 0) { - return ret; - } - if (check_timedout(s, ret, &timeout_ms, _errno)) { - return -1; - } - } -} - -STATIC int wlan_socket_recv(mod_network_socket_obj_t *s, byte *buf, mp_uint_t len, int *_errno) { - uint32_t timeout_ms = s->sock_base.timeout_ms; - for (;;) { - int ret = sl_Recv(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0); - if (ret >= 0) { - return ret; - } - if (check_timedout(s, ret, &timeout_ms, _errno)) { - return -1; - } - } -} - -STATIC int wlan_socket_sendto( mod_network_socket_obj_t *s, const byte *buf, mp_uint_t len, byte *ip, mp_uint_t port, int *_errno) { - MAKE_SOCKADDR(addr, ip, port) - uint32_t timeout_ms = s->sock_base.timeout_ms; - for (;;) { - int ret = sl_SendTo(s->sock_base.sd, (byte*)buf, len, 0, (SlSockAddr_t*)&addr, sizeof(addr)); - if (ret >= 0) { - return ret; - } - if (check_timedout(s, ret, &timeout_ms, _errno)) { - return -1; - } - } -} - -STATIC int wlan_socket_recvfrom(mod_network_socket_obj_t *s, byte *buf, mp_uint_t len, byte *ip, mp_uint_t *port, int *_errno) { - SlSockAddr_t addr; - SlSocklen_t addr_len = sizeof(addr); - uint32_t timeout_ms = s->sock_base.timeout_ms; - for (;;) { - int ret = sl_RecvFrom(s->sock_base.sd, buf, MIN(len, WLAN_MAX_RX_SIZE), 0, &addr, &addr_len); - if (ret >= 0) { - UNPACK_SOCKADDR(addr, ip, *port); - return ret; - } - if (check_timedout(s, ret, &timeout_ms, _errno)) { - return -1; - } - } -} - -STATIC int wlan_socket_setsockopt(mod_network_socket_obj_t *s, mp_uint_t level, mp_uint_t opt, const void *optval, mp_uint_t optlen, int *_errno) { - int ret = sl_SetSockOpt(s->sock_base.sd, level, opt, optval, optlen); - if (ret < 0) { - *_errno = ret; - return -1; - } - return 0; -} - -STATIC int wlan_socket_settimeout(mod_network_socket_obj_t *s, mp_uint_t timeout_s, int *_errno) { - SlSockNonblocking_t option; - if (timeout_s == 0 || timeout_s == -1) { - if (timeout_s == 0) { - // set non-blocking mode - option.NonblockingEnabled = 1; - } else { - // set blocking mode - option.NonblockingEnabled = 0; - } - timeout_s = 0; - } else { - // synthesize timeout via non-blocking behaviour with a loop - option.NonblockingEnabled = 1; - } - - int ret = sl_SetSockOpt(s->sock_base.sd, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &option, sizeof(option)); - if (ret != 0) { - *_errno = convert_sl_errno(ret); - return -1; - } - - s->sock_base.timeout_ms = timeout_s * 1000; - return 0; -} - -STATIC int wlan_socket_ioctl (mod_network_socket_obj_t *s, mp_uint_t request, mp_uint_t arg, int *_errno) { - mp_int_t ret; - if (request == MP_STREAM_POLL) { - mp_uint_t flags = arg; - ret = 0; - int32_t sd = s->sock_base.sd; - - // init fds - SlFdSet_t rfds, wfds, xfds; - SL_FD_ZERO(&rfds); - SL_FD_ZERO(&wfds); - SL_FD_ZERO(&xfds); - - // set fds if needed - if (flags & MP_STREAM_POLL_RD) { - SL_FD_SET(sd, &rfds); - } - if (flags & MP_STREAM_POLL_WR) { - SL_FD_SET(sd, &wfds); - } - if (flags & MP_STREAM_POLL_HUP) { - SL_FD_SET(sd, &xfds); - } - - // call simplelink's select with minimum timeout - SlTimeval_t tv; - tv.tv_sec = 0; - tv.tv_usec = 1; - int32_t nfds = sl_Select(sd + 1, &rfds, &wfds, &xfds, &tv); - - // check for errors - if (nfds == -1) { - *_errno = nfds; - return -1; - } - - // check return of select - if (SL_FD_ISSET(sd, &rfds)) { - ret |= MP_STREAM_POLL_RD; - } - if (SL_FD_ISSET(sd, &wfds)) { - ret |= MP_STREAM_POLL_WR; - } - if (SL_FD_ISSET(sd, &xfds)) { - ret |= MP_STREAM_POLL_HUP; - } - } else { - *_errno = MP_EINVAL; - ret = MP_STREAM_ERROR; - } - return ret; -} - -/****************************************************************************** - DEFINE PRIVATE CONSTANTS - ******************************************************************************/ -#define MOD_NETWORK_MAX_SOCKETS 10 - -/****************************************************************************** - DEFINE PRIVATE TYPES - ******************************************************************************/ -typedef struct { - int16_t sd; - bool user; -} modusocket_sock_t; - -/****************************************************************************** - DEFINE PRIVATE DATA - ******************************************************************************/ -STATIC const mp_obj_type_t socket_type; -STATIC OsiLockObj_t modusocket_LockObj; -STATIC modusocket_sock_t modusocket_sockets[MOD_NETWORK_MAX_SOCKETS] = {{.sd = -1}, {.sd = -1}, {.sd = -1}, {.sd = -1}, {.sd = -1}, - {.sd = -1}, {.sd = -1}, {.sd = -1}, {.sd = -1}, {.sd = -1}}; - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -__attribute__ ((section (".boot"))) -void modusocket_pre_init (void) { - // create the wlan lock - ASSERT(OSI_OK == sl_LockObjCreate(&modusocket_LockObj, "SockLock")); - sl_LockObjUnlock (&modusocket_LockObj); -} - -void modusocket_socket_add (int16_t sd, bool user) { - sl_LockObjLock (&modusocket_LockObj, SL_OS_WAIT_FOREVER); - for (int i = 0; i < MOD_NETWORK_MAX_SOCKETS; i++) { - if (modusocket_sockets[i].sd < 0) { - modusocket_sockets[i].sd = sd; - modusocket_sockets[i].user = user; - break; - } - } - sl_LockObjUnlock (&modusocket_LockObj); -} - -void modusocket_socket_delete (int16_t sd) { - sl_LockObjLock (&modusocket_LockObj, SL_OS_WAIT_FOREVER); - for (int i = 0; i < MOD_NETWORK_MAX_SOCKETS; i++) { - if (modusocket_sockets[i].sd == sd) { - modusocket_sockets[i].sd = -1; - break; - } - } - sl_LockObjUnlock (&modusocket_LockObj); -} - -void modusocket_enter_sleep (void) { - SlFdSet_t socketset; - int16_t maxfd = 0; - - for (int i = 0; i < MOD_NETWORK_MAX_SOCKETS; i++) { - int16_t sd; - if ((sd = modusocket_sockets[i].sd) >= 0) { - SL_FD_SET(sd, &socketset); - maxfd = (maxfd > sd) ? maxfd : sd; - } - } - - if (maxfd > 0) { - // wait for any of the sockets to become ready... - sl_Select(maxfd + 1, &socketset, NULL, NULL, NULL); - } -} - -void modusocket_close_all_user_sockets (void) { - sl_LockObjLock (&modusocket_LockObj, SL_OS_WAIT_FOREVER); - for (int i = 0; i < MOD_NETWORK_MAX_SOCKETS; i++) { - if (modusocket_sockets[i].sd >= 0 && modusocket_sockets[i].user) { - sl_Close(modusocket_sockets[i].sd); - modusocket_sockets[i].sd = -1; - } - } - sl_LockObjUnlock (&modusocket_LockObj); -} - -/******************************************************************************/ -// socket class - -// constructor socket(family=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP, fileno=None) -STATIC mp_obj_t 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); - - // create socket object - mod_network_socket_obj_t *s = m_new_obj_with_finaliser(mod_network_socket_obj_t); - s->base.type = (mp_obj_t)&socket_type; - s->sock_base.u_param.domain = SL_AF_INET; - s->sock_base.u_param.type = SL_SOCK_STREAM; - s->sock_base.u_param.proto = SL_IPPROTO_TCP; - s->sock_base.u_param.fileno = -1; - s->sock_base.timeout_ms = 0; - s->sock_base.cert_req = false; - - if (n_args > 0) { - s->sock_base.u_param.domain = mp_obj_get_int(args[0]); - if (n_args > 1) { - s->sock_base.u_param.type = mp_obj_get_int(args[1]); - if (n_args > 2) { - s->sock_base.u_param.proto = mp_obj_get_int(args[2]); - if (n_args > 3) { - s->sock_base.u_param.fileno = mp_obj_get_int(args[3]); - } - } - } - } - - // create the socket - int _errno; - if (wlan_socket_socket(s, &_errno) != 0) { - mp_raise_OSError(-_errno); - } - // add the socket to the list - modusocket_socket_add(s->sock_base.sd, true); - return s; -} - -// method socket.close() -STATIC mp_obj_t socket_close(mp_obj_t self_in) { - mod_network_socket_obj_t *self = self_in; - wlan_socket_close(self); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close); - -// method socket.bind(address) -STATIC mp_obj_t socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { - mod_network_socket_obj_t *self = self_in; - - // get address - uint8_t ip[MOD_NETWORK_IPV4ADDR_BUF_SIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_LITTLE); - - // call the NIC to bind the socket - int _errno = 0; - if (wlan_socket_bind(self, ip, port, &_errno) != 0) { - mp_raise_OSError(-_errno); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_bind_obj, socket_bind); - -// method socket.listen([backlog]) -STATIC mp_obj_t socket_listen(size_t n_args, const mp_obj_t *args) { - mod_network_socket_obj_t *self = args[0]; - - int32_t backlog = 0; - if (n_args > 1) { - backlog = mp_obj_get_int(args[1]); - backlog = (backlog < 0) ? 0 : backlog; - } - - int _errno; - if (wlan_socket_listen(self, backlog, &_errno) != 0) { - mp_raise_OSError(-_errno); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_listen_obj, 1, 2, socket_listen); - -// method socket.accept() -STATIC mp_obj_t socket_accept(mp_obj_t self_in) { - mod_network_socket_obj_t *self = self_in; - - // create new socket object - mod_network_socket_obj_t *socket2 = m_new_obj_with_finaliser(mod_network_socket_obj_t); - // the new socket inherits all properties from its parent - memcpy (socket2, self, sizeof(mod_network_socket_obj_t)); - - // accept the incoming connection - uint8_t ip[MOD_NETWORK_IPV4ADDR_BUF_SIZE]; - mp_uint_t port = 0; - int _errno = 0; - if (wlan_socket_accept(self, socket2, ip, &port, &_errno) != 0) { - mp_raise_OSError(_errno); - } - - // add the socket to the list - modusocket_socket_add(socket2->sock_base.sd, true); - - // make the return value - mp_obj_tuple_t *client = mp_obj_new_tuple(2, NULL); - client->items[0] = socket2; - client->items[1] = netutils_format_inet_addr(ip, port, NETUTILS_LITTLE); - return client; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_accept_obj, socket_accept); - -// method socket.connect(address) -STATIC mp_obj_t socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { - mod_network_socket_obj_t *self = self_in; - - // get address - uint8_t ip[MOD_NETWORK_IPV4ADDR_BUF_SIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_LITTLE); - - // connect the socket - int _errno; - if (wlan_socket_connect(self, ip, port, &_errno) != 0) { - if (!self->sock_base.cert_req && _errno == SL_ESECSNOVERIFY) { - return mp_const_none; - } - mp_raise_OSError(_errno); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_connect_obj, socket_connect); - -// method socket.send(bytes) -STATIC mp_obj_t socket_send(mp_obj_t self_in, mp_obj_t buf_in) { - mod_network_socket_obj_t *self = self_in; - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - int _errno; - mp_int_t ret = wlan_socket_send(self, bufinfo.buf, bufinfo.len, &_errno); - if (ret < 0) { - mp_raise_OSError(_errno); - } - return mp_obj_new_int_from_uint(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_send_obj, socket_send); - -// method socket.recv(bufsize) -STATIC mp_obj_t socket_recv(mp_obj_t self_in, mp_obj_t len_in) { - mod_network_socket_obj_t *self = self_in; - mp_int_t len = mp_obj_get_int(len_in); - vstr_t vstr; - vstr_init_len(&vstr, len); - int _errno; - mp_int_t ret = wlan_socket_recv(self, (byte*)vstr.buf, len, &_errno); - if (ret < 0) { - mp_raise_OSError(_errno); - } - if (ret == 0) { - return mp_const_empty_bytes; - } - vstr.len = ret; - vstr.buf[vstr.len] = '\0'; - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_recv_obj, socket_recv); - -// method socket.sendto(bytes, address) -STATIC mp_obj_t socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_obj_t addr_in) { - mod_network_socket_obj_t *self = self_in; - - // get the data - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_READ); - - // get address - uint8_t ip[MOD_NETWORK_IPV4ADDR_BUF_SIZE]; - mp_uint_t port = netutils_parse_inet_addr(addr_in, ip, NETUTILS_LITTLE); - - // call the nic to sendto - int _errno = 0; - mp_int_t ret = wlan_socket_sendto(self, bufinfo.buf, bufinfo.len, ip, port, &_errno); - if (ret < 0) { - mp_raise_OSError(_errno); - } - return mp_obj_new_int(ret); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(socket_sendto_obj, socket_sendto); - -// method socket.recvfrom(bufsize) -STATIC mp_obj_t socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { - mod_network_socket_obj_t *self = self_in; - vstr_t vstr; - vstr_init_len(&vstr, mp_obj_get_int(len_in)); - byte ip[4]; - mp_uint_t port = 0; - int _errno = 0; - mp_int_t ret = wlan_socket_recvfrom(self, (byte*)vstr.buf, vstr.len, ip, &port, &_errno); - if (ret < 0) { - mp_raise_OSError(_errno); - } - mp_obj_t tuple[2]; - if (ret == 0) { - tuple[0] = mp_const_empty_bytes; - } else { - vstr.len = ret; - vstr.buf[vstr.len] = '\0'; - tuple[0] = mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); - } - tuple[1] = netutils_format_inet_addr(ip, port, NETUTILS_LITTLE); - return mp_obj_new_tuple(2, tuple); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_recvfrom_obj, socket_recvfrom); - -// method socket.setsockopt(level, optname, value) -STATIC mp_obj_t socket_setsockopt(size_t n_args, const mp_obj_t *args) { - mod_network_socket_obj_t *self = args[0]; - - mp_int_t level = mp_obj_get_int(args[1]); - mp_int_t opt = mp_obj_get_int(args[2]); - - const void *optval; - mp_uint_t optlen; - mp_int_t val; - if (mp_obj_is_integer(args[3])) { - val = mp_obj_get_int_truncated(args[3]); - optval = &val; - optlen = sizeof(val); - } else { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); - optval = bufinfo.buf; - optlen = bufinfo.len; - } - - int _errno; - if (wlan_socket_setsockopt(self, level, opt, optval, optlen, &_errno) != 0) { - mp_raise_OSError(-_errno); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_setsockopt_obj, 4, 4, socket_setsockopt); - -// method socket.settimeout(value) -// timeout=0 means non-blocking -// timeout=None means blocking -// otherwise, timeout is in seconds -STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) { - mod_network_socket_obj_t *self = self_in; - mp_uint_t timeout; - if (timeout_in == mp_const_none) { - timeout = -1; - } else { - timeout = mp_obj_get_int(timeout_in); - } - int _errno = 0; - if (wlan_socket_settimeout(self, timeout, &_errno) != 0) { - mp_raise_OSError(_errno); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_settimeout_obj, socket_settimeout); - -// method socket.setblocking(flag) -STATIC mp_obj_t socket_setblocking(mp_obj_t self_in, mp_obj_t blocking) { - if (mp_obj_is_true(blocking)) { - return socket_settimeout(self_in, mp_const_none); - } else { - return socket_settimeout(self_in, MP_OBJ_NEW_SMALL_INT(0)); - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking); - -STATIC mp_obj_t 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(socket_makefile_obj, 1, 6, socket_makefile); - -STATIC const mp_rom_map_elem_t socket_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&socket_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&socket_close_obj) }, - { MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&socket_bind_obj) }, - { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&socket_listen_obj) }, - { MP_ROM_QSTR(MP_QSTR_accept), MP_ROM_PTR(&socket_accept_obj) }, - { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&socket_connect_obj) }, - { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&socket_send_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendall), MP_ROM_PTR(&socket_send_obj) }, - { MP_ROM_QSTR(MP_QSTR_recv), MP_ROM_PTR(&socket_recv_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&socket_sendto_obj) }, - { MP_ROM_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&socket_recvfrom_obj) }, - { MP_ROM_QSTR(MP_QSTR_setsockopt), MP_ROM_PTR(&socket_setsockopt_obj) }, - { MP_ROM_QSTR(MP_QSTR_settimeout), MP_ROM_PTR(&socket_settimeout_obj) }, - { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, - { MP_ROM_QSTR(MP_QSTR_makefile), MP_ROM_PTR(&socket_makefile_obj) }, - - // stream methods - { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read1_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_DEFINE_CONST_DICT(socket_locals_dict, socket_locals_dict_table); - -STATIC mp_uint_t socket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - mod_network_socket_obj_t *self = self_in; - mp_int_t ret = wlan_socket_recv(self, buf, size, errcode); - if (ret < 0) { - // we need to ignore the socket closed error here because a read() without params - // only returns when the socket is closed by the other end - if (*errcode != -SL_ESECCLOSED) { - ret = MP_STREAM_ERROR; - } else { - ret = 0; - } - } - return ret; -} - -STATIC mp_uint_t socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - mod_network_socket_obj_t *self = self_in; - mp_int_t ret = wlan_socket_send(self, buf, size, errcode); - if (ret < 0) { - ret = MP_STREAM_ERROR; - } - return ret; -} - -STATIC mp_uint_t socket_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { - mod_network_socket_obj_t *self = self_in; - return wlan_socket_ioctl(self, request, arg, errcode); -} - -const mp_stream_p_t socket_stream_p = { - .read = socket_read, - .write = socket_write, - .ioctl = socket_ioctl, - .is_text = false, -}; - -STATIC const mp_obj_type_t socket_type = { - { &mp_type_type }, - .name = MP_QSTR_socket, - .make_new = socket_make_new, - .protocol = &socket_stream_p, - .locals_dict = (mp_obj_t)&socket_locals_dict, -}; - -/******************************************************************************/ -// usocket module - -// function usocket.getaddrinfo(host, port) -/// \function getaddrinfo(host, port) -STATIC mp_obj_t mod_usocket_getaddrinfo(mp_obj_t host_in, mp_obj_t port_in) { - size_t hlen; - const char *host = mp_obj_str_get_data(host_in, &hlen); - mp_int_t port = mp_obj_get_int(port_in); - - // ipv4 only - uint8_t out_ip[MOD_NETWORK_IPV4ADDR_BUF_SIZE]; - int32_t result = wlan_gethostbyname(host, hlen, out_ip, SL_AF_INET); - if (result < 0) { - mp_raise_OSError(-result); - } - mp_obj_tuple_t *tuple = mp_obj_new_tuple(5, NULL); - tuple->items[0] = MP_OBJ_NEW_SMALL_INT(SL_AF_INET); - tuple->items[1] = MP_OBJ_NEW_SMALL_INT(SL_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(out_ip, port, NETUTILS_LITTLE); - return mp_obj_new_list(1, (mp_obj_t*)&tuple); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_usocket_getaddrinfo_obj, mod_usocket_getaddrinfo); - -STATIC const mp_rom_map_elem_t mp_module_usocket_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usocket) }, - - { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&socket_type) }, - { MP_ROM_QSTR(MP_QSTR_getaddrinfo), MP_ROM_PTR(&mod_usocket_getaddrinfo_obj) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(SL_AF_INET) }, - - { MP_ROM_QSTR(MP_QSTR_SOCK_STREAM), MP_ROM_INT(SL_SOCK_STREAM) }, - { MP_ROM_QSTR(MP_QSTR_SOCK_DGRAM), MP_ROM_INT(SL_SOCK_DGRAM) }, - - { MP_ROM_QSTR(MP_QSTR_IPPROTO_SEC), MP_ROM_INT(SL_SEC_SOCKET) }, - { MP_ROM_QSTR(MP_QSTR_IPPROTO_TCP), MP_ROM_INT(SL_IPPROTO_TCP) }, - { MP_ROM_QSTR(MP_QSTR_IPPROTO_UDP), MP_ROM_INT(SL_IPPROTO_UDP) }, -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_usocket_globals, mp_module_usocket_globals_table); - -const mp_obj_module_t mp_module_usocket = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_usocket_globals, -}; diff --git a/cc3200/mods/modusocket.h b/cc3200/mods/modusocket.h deleted file mode 100644 index 6e7758662..000000000 --- a/cc3200/mods/modusocket.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_MODUSOCKET_H -#define MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H - -extern const mp_obj_dict_t socket_locals_dict; -extern const mp_stream_p_t socket_stream_p; - -extern void modusocket_pre_init (void); -extern void modusocket_socket_add (int16_t sd, bool user); -extern void modusocket_socket_delete (int16_t sd); -extern void modusocket_enter_sleep (void); -extern void modusocket_close_all_user_sockets (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_MODUSOCKET_H diff --git a/cc3200/mods/modussl.c b/cc3200/mods/modussl.c deleted file mode 100644 index 321157049..000000000 --- a/cc3200/mods/modussl.c +++ /dev/null @@ -1,164 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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 "simplelink.h" -#include "py/mpconfig.h" -#include "py/obj.h" -#include "py/objstr.h" -#include "py/runtime.h" -#include "modnetwork.h" -#include "modusocket.h" -#include "mpexception.h" - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define SSL_CERT_NONE (0) -#define SSL_CERT_OPTIONAL (1) -#define SSL_CERT_REQUIRED (2) - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef struct _mp_obj_ssl_socket_t { - mp_obj_base_t base; - mod_network_socket_base_t sock_base; - mp_obj_t o_sock; -} mp_obj_ssl_socket_t; - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC const mp_obj_type_t ssl_socket_type; - -/******************************************************************************/ -// MicroPython bindings; SSL class - -// ssl sockets inherit from normal socket, so we take its -// locals and stream methods -STATIC const mp_obj_type_t ssl_socket_type = { - { &mp_type_type }, - .name = MP_QSTR_ussl, - .getiter = NULL, - .iternext = NULL, - .protocol = &socket_stream_p, - .locals_dict = (mp_obj_t)&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) { - STATIC const mp_arg_t allowed_args[] = { - { MP_QSTR_sock, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_keyfile, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_certfile, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_server_side, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_cert_reqs, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SSL_CERT_NONE} }, - { MP_QSTR_ssl_version, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SL_SO_SEC_METHOD_TLSV1} }, - { MP_QSTR_ca_certs, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - }; - - // parse arguments - 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); - - // chech if ca validation is required - if (args[4].u_int != SSL_CERT_NONE && args[5].u_obj == mp_const_none) { - goto arg_error; - } - - // retrieve the file paths (with an 6 byte offset in order to strip it from the '/flash' prefix) - const char *keyfile = (args[1].u_obj == mp_const_none) ? NULL : &(mp_obj_str_get_str(args[1].u_obj)[6]); - const char *certfile = (args[2].u_obj == mp_const_none) ? NULL : &(mp_obj_str_get_str(args[2].u_obj)[6]); - const char *cafile = (args[6].u_obj == mp_const_none || args[4].u_int != SSL_CERT_REQUIRED) ? - NULL : &(mp_obj_str_get_str(args[6].u_obj)[6]); - - // server side requires both certfile and keyfile - if (args[3].u_bool && (!keyfile || !certfile)) { - goto arg_error; - } - - _i16 _errno; - _i16 sd = ((mod_network_socket_obj_t *)args[0].u_obj)->sock_base.sd; - - // set the requested SSL method - _u8 method = args[5].u_int; - if ((_errno = sl_SetSockOpt(sd, SL_SOL_SOCKET, SL_SO_SECMETHOD, &method, sizeof(method))) < 0) { - goto socket_error; - } - if (keyfile && (_errno = sl_SetSockOpt(sd, SL_SOL_SOCKET, SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, keyfile, strlen(keyfile))) < 0) { - goto socket_error; - } - if (certfile && (_errno = sl_SetSockOpt(sd, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, certfile, strlen(certfile))) < 0) { - goto socket_error; - } - if (cafile && (_errno = sl_SetSockOpt(sd, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME, cafile, strlen(cafile))) < 0) { - goto socket_error; - } - - // create the ssl socket - mp_obj_ssl_socket_t *ssl_sock = m_new_obj(mp_obj_ssl_socket_t); - // ssl sockets inherit all properties from the original socket - memcpy (&ssl_sock->sock_base, &((mod_network_socket_obj_t *)args[0].u_obj)->sock_base, sizeof(mod_network_socket_base_t)); - ssl_sock->base.type = &ssl_socket_type; - ssl_sock->sock_base.cert_req = (args[4].u_int == SSL_CERT_REQUIRED) ? true : false; - ssl_sock->o_sock = args[0].u_obj; - - return ssl_sock; - -socket_error: - mp_raise_OSError(_errno); - -arg_error: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 0, mod_ssl_wrap_socket); - -STATIC const mp_rom_map_elem_t mp_module_ussl_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) }, - - // class exceptions - { MP_ROM_QSTR(MP_QSTR_SSLError), MP_ROM_PTR(&mp_type_OSError) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_CERT_NONE), MP_ROM_INT(SSL_CERT_NONE) }, - { MP_ROM_QSTR(MP_QSTR_CERT_OPTIONAL), MP_ROM_INT(SSL_CERT_OPTIONAL) }, - { MP_ROM_QSTR(MP_QSTR_CERT_REQUIRED), MP_ROM_INT(SSL_CERT_REQUIRED) }, - - { MP_ROM_QSTR(MP_QSTR_PROTOCOL_SSLv3), MP_ROM_INT(SL_SO_SEC_METHOD_SSLV3) }, - { MP_ROM_QSTR(MP_QSTR_PROTOCOL_TLSv1), MP_ROM_INT(SL_SO_SEC_METHOD_TLSV1) }, - { MP_ROM_QSTR(MP_QSTR_PROTOCOL_TLSv1_1), MP_ROM_INT(SL_SO_SEC_METHOD_TLSV1_1) }, - { MP_ROM_QSTR(MP_QSTR_PROTOCOL_TLSv1_2), MP_ROM_INT(SL_SO_SEC_METHOD_TLSV1_2) }, -}; - -STATIC MP_DEFINE_CONST_DICT(mp_module_ussl_globals, mp_module_ussl_globals_table); - -const mp_obj_module_t mp_module_ussl = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ussl_globals, -}; - diff --git a/cc3200/mods/modutime.c b/cc3200/mods/modutime.c deleted file mode 100644 index 13750f96b..000000000 --- a/cc3200/mods/modutime.c +++ /dev/null @@ -1,157 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpconfig.h" -#include "py/runtime.h" -#include "py/obj.h" -#include "py/smallint.h" -#include "py/mphal.h" -#include "lib/timeutils/timeutils.h" -#include "extmod/utime_mphal.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "prcm.h" -#include "systick.h" -#include "pybrtc.h" -#include "mpexception.h" -#include "utils.h" - -/// \module time - time related functions -/// -/// The `time` module provides functions for getting the current time and date, -/// and for sleeping. - -/******************************************************************************/ -// MicroPython bindings - -/// \function localtime([secs]) -/// Convert a time expressed in seconds since Jan 1, 2000 into an 8-tuple which -/// contains: (year, month, mday, hour, minute, second, weekday, yearday) -/// If secs is not provided or None, then the current time from the RTC is used. -/// year includes the century (for example 2015) -/// month is 1-12 -/// mday is 1-31 -/// hour is 0-23 -/// minute is 0-59 -/// second is 0-59 -/// weekday is 0-6 for Mon-Sun. -/// yearday is 1-366 -STATIC mp_obj_t time_localtime(size_t n_args, const mp_obj_t *args) { - if (n_args == 0 || args[0] == mp_const_none) { - timeutils_struct_time_t tm; - - // get the seconds from the RTC - timeutils_seconds_since_2000_to_struct_time(pyb_rtc_get_seconds(), &tm); - mp_obj_t tuple[8] = { - mp_obj_new_int(tm.tm_year), - mp_obj_new_int(tm.tm_mon), - mp_obj_new_int(tm.tm_mday), - mp_obj_new_int(tm.tm_hour), - mp_obj_new_int(tm.tm_min), - mp_obj_new_int(tm.tm_sec), - mp_obj_new_int(tm.tm_wday), - mp_obj_new_int(tm.tm_yday) - }; - return mp_obj_new_tuple(8, tuple); - } else { - mp_int_t seconds = mp_obj_get_int(args[0]); - timeutils_struct_time_t tm; - timeutils_seconds_since_2000_to_struct_time(seconds, &tm); - mp_obj_t tuple[8] = { - tuple[0] = mp_obj_new_int(tm.tm_year), - tuple[1] = mp_obj_new_int(tm.tm_mon), - tuple[2] = mp_obj_new_int(tm.tm_mday), - tuple[3] = mp_obj_new_int(tm.tm_hour), - tuple[4] = mp_obj_new_int(tm.tm_min), - tuple[5] = mp_obj_new_int(tm.tm_sec), - tuple[6] = mp_obj_new_int(tm.tm_wday), - tuple[7] = mp_obj_new_int(tm.tm_yday), - }; - return mp_obj_new_tuple(8, tuple); - } -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(time_localtime_obj, 0, 1, time_localtime); - -STATIC mp_obj_t time_mktime(mp_obj_t tuple) { - size_t len; - mp_obj_t *elem; - - mp_obj_get_array(tuple, &len, &elem); - - // localtime generates a tuple of len 8. CPython uses 9, so we accept both. - if (len < 8 || len > 9) { - mp_raise_TypeError(mpexception_num_type_invalid_arguments); - } - - return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]), mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), - mp_obj_get_int(elem[3]), mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5]))); -} -MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime); - -STATIC mp_obj_t time_time(void) { - return mp_obj_new_int(pyb_rtc_get_seconds()); -} -MP_DEFINE_CONST_FUN_OBJ_0(time_time_obj, time_time); - -STATIC mp_obj_t time_sleep(mp_obj_t seconds_o) { - int32_t sleep_s = mp_obj_get_int(seconds_o); - if (sleep_s > 0) { - mp_hal_delay_ms(sleep_s * 1000); - } - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(time_sleep_obj, time_sleep); - -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_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(&time_sleep_obj) }, - - // MicroPython additions - { 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) }, -}; - -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, -}; diff --git a/cc3200/mods/modwipy.c b/cc3200/mods/modwipy.c deleted file mode 100644 index 0f16e7301..000000000 --- a/cc3200/mods/modwipy.c +++ /dev/null @@ -1,30 +0,0 @@ -#include "py/mpconfig.h" -#include "py/obj.h" -#include "py/runtime.h" -#include "mperror.h" - - -/******************************************************************************/ -// MicroPython bindings - -STATIC mp_obj_t mod_wipy_heartbeat(size_t n_args, const mp_obj_t *args) { - if (n_args) { - mperror_enable_heartbeat (mp_obj_is_true(args[0])); - return mp_const_none; - } else { - return mp_obj_new_bool(mperror_is_heartbeat_enabled()); - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_wipy_heartbeat_obj, 0, 1, mod_wipy_heartbeat); - -STATIC const mp_rom_map_elem_t wipy_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_wipy) }, - { MP_ROM_QSTR(MP_QSTR_heartbeat), MP_ROM_PTR(&mod_wipy_heartbeat_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(wipy_module_globals, wipy_module_globals_table); - -const mp_obj_module_t wipy_module = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&wipy_module_globals, -}; diff --git a/cc3200/mods/modwlan.c b/cc3200/mods/modwlan.c deleted file mode 100644 index f9c7111b3..000000000 --- a/cc3200/mods/modwlan.c +++ /dev/null @@ -1,1303 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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 <stdbool.h> -#include <stdio.h> - -#include "simplelink.h" -#include "py/mpconfig.h" -#include "py/obj.h" -#include "py/objstr.h" -#include "py/runtime.h" -#include "py/stream.h" -#include "py/mphal.h" -#include "lib/timeutils/timeutils.h" -#include "lib/netutils/netutils.h" -#include "modnetwork.h" -#include "modusocket.h" -#include "modwlan.h" -#include "pybrtc.h" -#include "debug.h" -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) -#include "serverstask.h" -#endif -#include "mpexception.h" -#include "mpirq.h" -#include "pybsleep.h" -#include "antenna.h" - - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -// Status bits - These are used to set/reset the corresponding bits in a given variable -typedef enum{ - STATUS_BIT_NWP_INIT = 0, // If this bit is set: Network Processor is - // powered up - - STATUS_BIT_CONNECTION, // If this bit is set: the device is connected to - // the AP or client is connected to device (AP) - - STATUS_BIT_IP_LEASED, // If this bit is set: the device has leased IP to - // any connected client - - STATUS_BIT_IP_ACQUIRED, // If this bit is set: the device has acquired an IP - - STATUS_BIT_SMARTCONFIG_START, // If this bit is set: the SmartConfiguration - // process is started from SmartConfig app - - STATUS_BIT_P2P_DEV_FOUND, // If this bit is set: the device (P2P mode) - // found any p2p-device in scan - - STATUS_BIT_P2P_REQ_RECEIVED, // If this bit is set: the device (P2P mode) - // found any p2p-negotiation request - - STATUS_BIT_CONNECTION_FAILED, // If this bit is set: the device(P2P mode) - // connection to client(or reverse way) is failed - - STATUS_BIT_PING_DONE // If this bit is set: the device has completed - // the ping operation -} e_StatusBits; - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define CLR_STATUS_BIT_ALL(status) (status = 0) -#define SET_STATUS_BIT(status, bit) (status |= ( 1 << (bit))) -#define CLR_STATUS_BIT(status, bit) (status &= ~(1 << (bit))) -#define GET_STATUS_BIT(status, bit) (0 != (status & (1 << (bit)))) - -#define IS_NW_PROCSR_ON(status) GET_STATUS_BIT(status, STATUS_BIT_NWP_INIT) -#define IS_CONNECTED(status) GET_STATUS_BIT(status, STATUS_BIT_CONNECTION) -#define IS_IP_LEASED(status) GET_STATUS_BIT(status, STATUS_BIT_IP_LEASED) -#define IS_IP_ACQUIRED(status) GET_STATUS_BIT(status, STATUS_BIT_IP_ACQUIRED) -#define IS_SMART_CFG_START(status) GET_STATUS_BIT(status, STATUS_BIT_SMARTCONFIG_START) -#define IS_P2P_DEV_FOUND(status) GET_STATUS_BIT(status, STATUS_BIT_P2P_DEV_FOUND) -#define IS_P2P_REQ_RCVD(status) GET_STATUS_BIT(status, STATUS_BIT_P2P_REQ_RECEIVED) -#define IS_CONNECT_FAILED(status) GET_STATUS_BIT(status, STATUS_BIT_CONNECTION_FAILED) -#define IS_PING_DONE(status) GET_STATUS_BIT(status, STATUS_BIT_PING_DONE) - -#define MODWLAN_SL_SCAN_ENABLE 1 -#define MODWLAN_SL_SCAN_DISABLE 0 -#define MODWLAN_SL_MAX_NETWORKS 20 - -#define MODWLAN_MAX_NETWORKS 20 -#define MODWLAN_SCAN_PERIOD_S 3600 // 1 hour -#define MODWLAN_WAIT_FOR_SCAN_MS 1050 -#define MODWLAN_CONNECTION_WAIT_MS 2 - -#define ASSERT_ON_ERROR(x) ASSERT((x) >= 0) - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC wlan_obj_t wlan_obj = { - .mode = -1, - .status = 0, - .ip = 0, - .auth = MICROPY_PORT_WLAN_AP_SECURITY, - .channel = MICROPY_PORT_WLAN_AP_CHANNEL, - .ssid = MICROPY_PORT_WLAN_AP_SSID, - .key = MICROPY_PORT_WLAN_AP_KEY, - .mac = {0}, - //.ssid_o = {0}, - //.bssid = {0}, - #if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - .servers_enabled = false, - #endif -}; - -STATIC const mp_irq_methods_t wlan_irq_methods; - -/****************************************************************************** - DECLARE PUBLIC DATA - ******************************************************************************/ -#ifdef SL_PLATFORM_MULTI_THREADED -OsiLockObj_t wlan_LockObj; -#endif - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void wlan_clear_data (void); -STATIC void wlan_reenable (SlWlanMode_t mode); -STATIC void wlan_servers_start (void); -STATIC void wlan_servers_stop (void); -STATIC void wlan_reset (void); -STATIC void wlan_validate_mode (uint mode); -STATIC void wlan_set_mode (uint mode); -STATIC void wlan_validate_ssid_len (uint32_t len); -STATIC void wlan_set_ssid (const char *ssid, uint8_t len, bool add_mac); -STATIC void wlan_validate_security (uint8_t auth, const char *key, uint8_t len); -STATIC void wlan_set_security (uint8_t auth, const char *key, uint8_t len); -STATIC void wlan_validate_channel (uint8_t channel); -STATIC void wlan_set_channel (uint8_t channel); -#if MICROPY_HW_ANTENNA_DIVERSITY -STATIC void wlan_validate_antenna (uint8_t antenna); -STATIC void wlan_set_antenna (uint8_t antenna); -#endif -STATIC void wlan_sl_disconnect (void); -STATIC modwlan_Status_t wlan_do_connect (const char* ssid, uint32_t ssid_len, const char* bssid, uint8_t sec, - const char* key, uint32_t key_len, int32_t timeout); -STATIC void wlan_get_sl_mac (void); -STATIC void wlan_wep_key_unhexlify (const char *key, char *key_out); -STATIC void wlan_lpds_irq_enable (mp_obj_t self_in); -STATIC void wlan_lpds_irq_disable (mp_obj_t self_in); -STATIC bool wlan_scan_result_is_unique (const mp_obj_list_t *nets, _u8 *bssid); - -//***************************************************************************** -// -//! \brief The Function Handles WLAN Events -//! -//! \param[in] pWlanEvent - Pointer to WLAN Event Info -//! -//! \return None -//! -//***************************************************************************** -void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent) { - if (!pWlanEvent) { - return; - } - - switch(pWlanEvent->Event) - { - case SL_WLAN_CONNECT_EVENT: - { - //slWlanConnectAsyncResponse_t *pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected; - // copy the new connection data - //memcpy(wlan_obj.bssid, pEventData->bssid, SL_BSSID_LENGTH); - //memcpy(wlan_obj.ssid_o, pEventData->ssid_name, pEventData->ssid_len); - //wlan_obj.ssid_o[pEventData->ssid_len] = '\0'; - SET_STATUS_BIT(wlan_obj.status, STATUS_BIT_CONNECTION); - #if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - // we must reset the servers in case that the last connection - // was lost without any notification being received - servers_reset(); - #endif - } - break; - case SL_WLAN_DISCONNECT_EVENT: - CLR_STATUS_BIT(wlan_obj.status, STATUS_BIT_CONNECTION); - CLR_STATUS_BIT(wlan_obj.status, STATUS_BIT_IP_ACQUIRED); - #if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - servers_reset(); - servers_wlan_cycle_power(); - #endif - break; - case SL_WLAN_STA_CONNECTED_EVENT: - { - //slPeerInfoAsyncResponse_t *pEventData = &pWlanEvent->EventData.APModeStaConnected; - // get the mac address and name of the connected device - //memcpy(wlan_obj.bssid, pEventData->mac, SL_BSSID_LENGTH); - //memcpy(wlan_obj.ssid_o, pEventData->go_peer_device_name, pEventData->go_peer_device_name_len); - //wlan_obj.ssid_o[pEventData->go_peer_device_name_len] = '\0'; - SET_STATUS_BIT(wlan_obj.status, STATUS_BIT_CONNECTION); - #if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - // we must reset the servers in case that the last connection - // was lost without any notification being received - servers_reset(); - #endif - } - break; - case SL_WLAN_STA_DISCONNECTED_EVENT: - CLR_STATUS_BIT(wlan_obj.status, STATUS_BIT_CONNECTION); - #if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - servers_reset(); - servers_wlan_cycle_power(); - #endif - break; - case SL_WLAN_P2P_DEV_FOUND_EVENT: - // TODO - break; - case SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT: - // TODO - break; - case SL_WLAN_CONNECTION_FAILED_EVENT: - // TODO - break; - default: - break; - } -} - -//***************************************************************************** -// -//! \brief This function handles network events such as IP acquisition, IP -//! leased, IP released etc. -//! -//! \param[in] pNetAppEvent - Pointer to NetApp Event Info -//! -//! \return None -//! -//***************************************************************************** -void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent) { - if(!pNetAppEvent) { - return; - } - - switch(pNetAppEvent->Event) - { - case SL_NETAPP_IPV4_IPACQUIRED_EVENT: - { - SlIpV4AcquiredAsync_t *pEventData = NULL; - - SET_STATUS_BIT(wlan_obj.status, STATUS_BIT_IP_ACQUIRED); - - // Ip Acquired Event Data - pEventData = &pNetAppEvent->EventData.ipAcquiredV4; - - // Get the ip - wlan_obj.ip = pEventData->ip; - } - break; - case SL_NETAPP_IPV6_IPACQUIRED_EVENT: - break; - case SL_NETAPP_IP_LEASED_EVENT: - break; - case SL_NETAPP_IP_RELEASED_EVENT: - break; - default: - break; - } -} - -//***************************************************************************** -// -//! \brief This function handles HTTP server events -//! -//! \param[in] pServerEvent - Contains the relevant event information -//! \param[in] pServerResponse - Should be filled by the user with the -//! relevant response information -//! -//! \return None -//! -//**************************************************************************** -void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent, SlHttpServerResponse_t *pHttpResponse) { - if (!pHttpEvent) { - return; - } - - switch (pHttpEvent->Event) { - case SL_NETAPP_HTTPGETTOKENVALUE_EVENT: - break; - case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT: - break; - default: - break; - } -} - -//***************************************************************************** -// -//! \brief This function handles General Events -//! -//! \param[in] pDevEvent - Pointer to General Event Info -//! -//! \return None -//! -//***************************************************************************** -void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent) { - if (!pDevEvent) { - return; - } -} - -//***************************************************************************** -// -//! This function handles socket events indication -//! -//! \param[in] pSock - Pointer to Socket Event Info -//! -//! \return None -//! -//***************************************************************************** -void SimpleLinkSockEventHandler(SlSockEvent_t *pSock) { - if (!pSock) { - return; - } - - switch( pSock->Event ) { - case SL_SOCKET_TX_FAILED_EVENT: - switch( pSock->socketAsyncEvent.SockTxFailData.status) { - case SL_ECLOSE: - break; - default: - break; - } - break; - case SL_SOCKET_ASYNC_EVENT: - switch(pSock->socketAsyncEvent.SockAsyncData.type) { - case SSL_ACCEPT: - break; - case RX_FRAGMENTATION_TOO_BIG: - break; - case OTHER_SIDE_CLOSE_SSL_DATA_NOT_ENCRYPTED: - break; - default: - break; - } - break; - default: - break; - } -} - -//***************************************************************************** -// SimpleLink Asynchronous Event Handlers -- End -//***************************************************************************** - -__attribute__ ((section (".boot"))) -void wlan_pre_init (void) { - // create the wlan lock - #ifdef SL_PLATFORM_MULTI_THREADED - ASSERT(OSI_OK == sl_LockObjCreate(&wlan_LockObj, "WlanLock")); - #endif -} - -void wlan_first_start (void) { - if (wlan_obj.mode < 0) { - CLR_STATUS_BIT_ALL(wlan_obj.status); - wlan_obj.mode = sl_Start(0, 0, 0); - #ifdef SL_PLATFORM_MULTI_THREADED - sl_LockObjUnlock (&wlan_LockObj); - #endif - } - - // get the mac address - wlan_get_sl_mac(); -} - -void wlan_sl_init (int8_t mode, const char *ssid, uint8_t ssid_len, uint8_t auth, const char *key, uint8_t key_len, - uint8_t channel, uint8_t antenna, bool add_mac) { - - // stop the servers - wlan_servers_stop(); - - // do a basic start - wlan_first_start(); - - // close any active connections - wlan_sl_disconnect(); - - // Remove all profiles - ASSERT_ON_ERROR(sl_WlanProfileDel(0xFF)); - - // Enable the DHCP client - uint8_t value = 1; - ASSERT_ON_ERROR(sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE, 1, 1, &value)); - - // Set PM policy to normal - ASSERT_ON_ERROR(sl_WlanPolicySet(SL_POLICY_PM, SL_NORMAL_POLICY, NULL, 0)); - - // Unregister mDNS services - ASSERT_ON_ERROR(sl_NetAppMDNSUnRegisterService(0, 0)); - - // Stop the internal HTTP server - sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID); - - // Remove all 64 filters (8 * 8) - _WlanRxFilterOperationCommandBuff_t RxFilterIdMask; - memset ((void *)&RxFilterIdMask, 0 ,sizeof(RxFilterIdMask)); - memset(RxFilterIdMask.FilterIdMask, 0xFF, 8); - ASSERT_ON_ERROR(sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask, sizeof(_WlanRxFilterOperationCommandBuff_t))); - -#if MICROPY_HW_ANTENNA_DIVERSITY - // set the antenna type - wlan_set_antenna (antenna); -#endif - - // switch to the requested mode - wlan_set_mode(mode); - - // stop and start again (we need to in the propper mode from now on) - wlan_reenable(mode); - - // Set Tx power level for station or AP mode - // Number between 0-15, as dB offset from max power - 0 will set max power - uint8_t ucPower = 0; - if (mode == ROLE_AP) { - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_AP_TX_POWER, sizeof(ucPower), - (unsigned char *)&ucPower)); - - // configure all parameters - wlan_set_ssid (ssid, ssid_len, add_mac); - wlan_set_security (auth, key, key_len); - wlan_set_channel (channel); - - // set the country - _u8* country = (_u8*)"EU"; - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE, 2, country)); - - SlNetCfgIpV4Args_t ipV4; - ipV4.ipV4 = (_u32)SL_IPV4_VAL(192,168,1,1); // _u32 IP address - ipV4.ipV4Mask = (_u32)SL_IPV4_VAL(255,255,255,0); // _u32 Subnet mask for this AP - ipV4.ipV4Gateway = (_u32)SL_IPV4_VAL(192,168,1,1); // _u32 Default gateway address - ipV4.ipV4DnsServer = (_u32)SL_IPV4_VAL(192,168,1,1); // _u32 DNS server address - ASSERT_ON_ERROR(sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, IPCONFIG_MODE_ENABLE_IPV4, - sizeof(SlNetCfgIpV4Args_t), (_u8 *)&ipV4)); - - SlNetAppDhcpServerBasicOpt_t dhcpParams; - dhcpParams.lease_time = 4096; // lease time (in seconds) of the IP Address - dhcpParams.ipv4_addr_start = SL_IPV4_VAL(192,168,1,2); // first IP Address for allocation. - dhcpParams.ipv4_addr_last = SL_IPV4_VAL(192,168,1,254); // last IP Address for allocation. - ASSERT_ON_ERROR(sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID)); // Stop DHCP server before settings - ASSERT_ON_ERROR(sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, - sizeof(SlNetAppDhcpServerBasicOpt_t), (_u8* )&dhcpParams)); // set parameters - ASSERT_ON_ERROR(sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID)); // Start DHCP server with new settings - - // stop and start again - wlan_reenable(mode); - } else { // STA and P2P modes - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, - sizeof(ucPower), (unsigned char *)&ucPower)); - // set connection policy to Auto + Fast (tries to connect to the last connected AP) - ASSERT_ON_ERROR(sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 1, 0, 0, 0), NULL, 0)); - } - - // set current time and date (needed to validate certificates) - wlan_set_current_time (pyb_rtc_get_seconds()); - - // start the servers before returning - wlan_servers_start(); -} - -void wlan_update(void) { -#ifndef SL_PLATFORM_MULTI_THREADED - _SlTaskEntry(); -#endif -} - -void wlan_stop (uint32_t timeout) { - wlan_servers_stop(); - #ifdef SL_PLATFORM_MULTI_THREADED - sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER); - #endif - sl_Stop(timeout); - wlan_clear_data(); - wlan_obj.mode = -1; -} - -void wlan_get_mac (uint8_t *macAddress) { - if (macAddress) { - memcpy (macAddress, wlan_obj.mac, SL_MAC_ADDR_LEN); - } -} - -void wlan_get_ip (uint32_t *ip) { - if (ip) { - *ip = IS_IP_ACQUIRED(wlan_obj.status) ? wlan_obj.ip : 0; - } -} - -bool wlan_is_connected (void) { - return (GET_STATUS_BIT(wlan_obj.status, STATUS_BIT_CONNECTION) && - (GET_STATUS_BIT(wlan_obj.status, STATUS_BIT_IP_ACQUIRED) || wlan_obj.mode != ROLE_STA)); -} - -void wlan_set_current_time (uint32_t seconds_since_2000) { - timeutils_struct_time_t tm; - timeutils_seconds_since_2000_to_struct_time(seconds_since_2000, &tm); - - SlDateTime_t sl_datetime = {0}; - sl_datetime.sl_tm_day = tm.tm_mday; - sl_datetime.sl_tm_mon = tm.tm_mon; - sl_datetime.sl_tm_year = tm.tm_year; - sl_datetime.sl_tm_hour = tm.tm_hour; - sl_datetime.sl_tm_min = tm.tm_min; - sl_datetime.sl_tm_sec = tm.tm_sec; - sl_DevSet(SL_DEVICE_GENERAL_CONFIGURATION, SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME, sizeof(SlDateTime_t), (_u8 *)(&sl_datetime)); -} - -void wlan_off_on (void) { - // no need to lock the WLAN object on every API call since the servers and the MicroPtyhon - // task have the same priority - wlan_reenable(wlan_obj.mode); -} - -//***************************************************************************** -// DEFINE STATIC FUNCTIONS -//***************************************************************************** - -STATIC void wlan_clear_data (void) { - CLR_STATUS_BIT_ALL(wlan_obj.status); - wlan_obj.ip = 0; - //memset(wlan_obj.ssid_o, 0, sizeof(wlan_obj.ssid)); - //memset(wlan_obj.bssid, 0, sizeof(wlan_obj.bssid)); -} - -STATIC void wlan_reenable (SlWlanMode_t mode) { - // stop and start again - #ifdef SL_PLATFORM_MULTI_THREADED - sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER); - #endif - sl_Stop(SL_STOP_TIMEOUT); - wlan_clear_data(); - wlan_obj.mode = sl_Start(0, 0, 0); - #ifdef SL_PLATFORM_MULTI_THREADED - sl_LockObjUnlock (&wlan_LockObj); - #endif - ASSERT (wlan_obj.mode == mode); -} - -STATIC void wlan_servers_start (void) { -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - // start the servers if they were enabled before - if (wlan_obj.servers_enabled) { - servers_start(); - } -#endif -} - -STATIC void wlan_servers_stop (void) { -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - // Stop all other processes using the wlan engine - if ((wlan_obj.servers_enabled = servers_are_enabled())) { - servers_stop(); - } -#endif -} - -STATIC void wlan_reset (void) { - wlan_servers_stop(); - wlan_reenable (wlan_obj.mode); - wlan_servers_start(); -} - -STATIC void wlan_validate_mode (uint mode) { - if (mode != ROLE_STA && mode != ROLE_AP) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} - -STATIC void wlan_set_mode (uint mode) { - wlan_obj.mode = mode; - ASSERT_ON_ERROR(sl_WlanSetMode(mode)); -} - -STATIC void wlan_validate_ssid_len (uint32_t len) { - if (len > MODWLAN_SSID_LEN_MAX) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} - -STATIC void wlan_set_ssid (const char *ssid, uint8_t len, bool add_mac) { - if (ssid != NULL) { - // save the ssid - memcpy(&wlan_obj.ssid, ssid, len); - // append the last 2 bytes of the MAC address, since the use of this functionality is under our control - // we can assume that the lenght of the ssid is less than (32 - 5) - if (add_mac) { - snprintf((char *)&wlan_obj.ssid[len], sizeof(wlan_obj.ssid) - len, "-%02x%02x", wlan_obj.mac[4], wlan_obj.mac[5]); - len += 5; - } - wlan_obj.ssid[len] = '\0'; - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SSID, len, (unsigned char *)wlan_obj.ssid)); - } -} - -STATIC void wlan_validate_security (uint8_t auth, const char *key, uint8_t len) { - if (auth != SL_SEC_TYPE_WEP && auth != SL_SEC_TYPE_WPA_WPA2) { - goto invalid_args; - } - if (auth == SL_SEC_TYPE_WEP) { - for (mp_uint_t i = strlen(key); i > 0; i--) { - if (!unichar_isxdigit(*key++)) { - goto invalid_args; - } - } - } - return; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -STATIC void wlan_set_security (uint8_t auth, const char *key, uint8_t len) { - wlan_obj.auth = auth; - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SECURITY_TYPE, sizeof(uint8_t), &auth)); - if (key != NULL) { - memcpy(&wlan_obj.key, key, len); - wlan_obj.key[len] = '\0'; - if (auth == SL_SEC_TYPE_WEP) { - _u8 wep_key[32]; - wlan_wep_key_unhexlify(key, (char *)&wep_key); - key = (const char *)&wep_key; - len /= 2; - } - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_PASSWORD, len, (unsigned char *)key)); - } else { - wlan_obj.key[0] = '\0'; - } -} - -STATIC void wlan_validate_channel (uint8_t channel) { - if (channel < 1 || channel > 11) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} - -STATIC void wlan_set_channel (uint8_t channel) { - wlan_obj.channel = channel; - ASSERT_ON_ERROR(sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_CHANNEL, 1, &channel)); -} - -#if MICROPY_HW_ANTENNA_DIVERSITY -STATIC void wlan_validate_antenna (uint8_t antenna) { - if (antenna != ANTENNA_TYPE_INTERNAL && antenna != ANTENNA_TYPE_EXTERNAL) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} - -STATIC void wlan_set_antenna (uint8_t antenna) { - wlan_obj.antenna = antenna; - antenna_select(antenna); -} -#endif - -STATIC void wlan_sl_disconnect (void) { - // Device in station-mode. Disconnect previous connection if any - // The function returns 0 if 'Disconnected done', negative number if already - // disconnected Wait for 'disconnection' event if 0 is returned, Ignore - // other return-codes - if (0 == sl_WlanDisconnect()) { - while (IS_CONNECTED(wlan_obj.status)) { - mp_hal_delay_ms(MODWLAN_CONNECTION_WAIT_MS); - wlan_update(); - } - } -} - -STATIC modwlan_Status_t wlan_do_connect (const char* ssid, uint32_t ssid_len, const char* bssid, uint8_t sec, - const char* key, uint32_t key_len, int32_t timeout) { - SlSecParams_t secParams; - secParams.Key = (_i8*)key; - secParams.KeyLen = ((key != NULL) ? key_len : 0); - secParams.Type = sec; - - // first close any active connections - wlan_sl_disconnect(); - - if (!sl_WlanConnect((_i8*)ssid, ssid_len, (_u8*)bssid, &secParams, NULL)) { - // wait for the WLAN Event - uint32_t waitForConnectionMs = 0; - while (timeout && !IS_CONNECTED(wlan_obj.status)) { - mp_hal_delay_ms(MODWLAN_CONNECTION_WAIT_MS); - waitForConnectionMs += MODWLAN_CONNECTION_WAIT_MS; - if (timeout > 0 && waitForConnectionMs > timeout) { - return MODWLAN_ERROR_TIMEOUT; - } - wlan_update(); - } - return MODWLAN_OK; - } - return MODWLAN_ERROR_INVALID_PARAMS; -} - -STATIC void wlan_get_sl_mac (void) { - // Get the MAC address - uint8_t macAddrLen = SL_MAC_ADDR_LEN; - sl_NetCfgGet(SL_MAC_ADDRESS_GET, NULL, &macAddrLen, wlan_obj.mac); -} - -STATIC void wlan_wep_key_unhexlify (const char *key, char *key_out) { - byte hex_byte = 0; - for (mp_uint_t i = strlen(key); i > 0 ; i--) { - hex_byte += unichar_xdigit_value(*key++); - if (i & 1) { - hex_byte <<= 4; - } else { - *key_out++ = hex_byte; - hex_byte = 0; - } - } -} - -STATIC void wlan_lpds_irq_enable (mp_obj_t self_in) { - wlan_obj_t *self = self_in; - self->irq_enabled = true; -} - -STATIC void wlan_lpds_irq_disable (mp_obj_t self_in) { - wlan_obj_t *self = self_in; - self->irq_enabled = false; -} - -STATIC int wlan_irq_flags (mp_obj_t self_in) { - wlan_obj_t *self = self_in; - return self->irq_flags; -} - -STATIC bool wlan_scan_result_is_unique (const mp_obj_list_t *nets, _u8 *bssid) { - for (int i = 0; i < nets->len; i++) { - // index 1 in the list is the bssid - mp_obj_str_t *_bssid = (mp_obj_str_t *)((mp_obj_tuple_t *)nets->items[i])->items[1]; - if (!memcmp (_bssid->data, bssid, SL_BSSID_LENGTH)) { - return false; - } - } - return true; -} - -/******************************************************************************/ -// MicroPython bindings; WLAN class - -/// \class WLAN - WiFi driver - -STATIC mp_obj_t wlan_init_helper(wlan_obj_t *self, const mp_arg_val_t *args) { - // get the mode - int8_t mode = args[0].u_int; - wlan_validate_mode(mode); - - // get the ssid - size_t ssid_len = 0; - const char *ssid = NULL; - if (args[1].u_obj != NULL) { - ssid = mp_obj_str_get_data(args[1].u_obj, &ssid_len); - wlan_validate_ssid_len(ssid_len); - } - - // get the auth config - uint8_t auth = SL_SEC_TYPE_OPEN; - size_t key_len = 0; - const char *key = NULL; - if (args[2].u_obj != mp_const_none) { - mp_obj_t *sec; - mp_obj_get_array_fixed_n(args[2].u_obj, 2, &sec); - auth = mp_obj_get_int(sec[0]); - key = mp_obj_str_get_data(sec[1], &key_len); - wlan_validate_security(auth, key, key_len); - } - - // get the channel - uint8_t channel = args[3].u_int; - wlan_validate_channel(channel); - - // get the antenna type - uint8_t antenna = 0; -#if MICROPY_HW_ANTENNA_DIVERSITY - antenna = args[4].u_int; - wlan_validate_antenna(antenna); -#endif - - // initialize the wlan subsystem - wlan_sl_init(mode, (const char *)ssid, ssid_len, auth, (const char *)key, key_len, channel, antenna, false); - - return mp_const_none; -} - -STATIC const mp_arg_t wlan_init_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_mode, MP_ARG_INT, {.u_int = ROLE_STA} }, - { MP_QSTR_ssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_auth, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, - #if MICROPY_HW_ANTENNA_DIVERSITY - { MP_QSTR_antenna, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = ANTENNA_TYPE_INTERNAL} }, - #endif -}; -STATIC mp_obj_t wlan_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(wlan_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), wlan_init_args, args); - - // setup the object - wlan_obj_t *self = &wlan_obj; - self->base.type = (mp_obj_t)&mod_network_nic_type_wlan; - - // give it to the sleep module - pyb_sleep_set_wlan_obj(self); - - if (n_args > 1 || n_kw > 0) { - // check the peripheral id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_ENODEV); - } - // start the peripheral - wlan_init_helper(self, &args[1]); - } - - return (mp_obj_t)self; -} - -STATIC mp_obj_t wlan_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(wlan_init_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &wlan_init_args[1], args); - return wlan_init_helper(pos_args[0], args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wlan_init_obj, 1, wlan_init); - -STATIC mp_obj_t wlan_scan(mp_obj_t self_in) { - STATIC const qstr wlan_scan_info_fields[] = { - MP_QSTR_ssid, MP_QSTR_bssid, MP_QSTR_sec, MP_QSTR_channel, MP_QSTR_rssi - }; - - // check for correct wlan mode - if (wlan_obj.mode == ROLE_AP) { - mp_raise_OSError(MP_EPERM); - } - - Sl_WlanNetworkEntry_t wlanEntry; - mp_obj_t nets = mp_obj_new_list(0, NULL); - uint8_t _index = 0; - - // trigger a new network scan - uint32_t scanSeconds = MODWLAN_SCAN_PERIOD_S; - ASSERT_ON_ERROR(sl_WlanPolicySet(SL_POLICY_SCAN , MODWLAN_SL_SCAN_ENABLE, (_u8 *)&scanSeconds, sizeof(scanSeconds))); - - // wait for the scan to complete - mp_hal_delay_ms(MODWLAN_WAIT_FOR_SCAN_MS); - - do { - if (sl_WlanGetNetworkList(_index++, 1, &wlanEntry) <= 0) { - break; - } - - // we must skip any duplicated results - if (!wlan_scan_result_is_unique(nets, wlanEntry.bssid)) { - continue; - } - - mp_obj_t tuple[5]; - tuple[0] = mp_obj_new_str((const char *)wlanEntry.ssid, wlanEntry.ssid_len, false); - tuple[1] = mp_obj_new_bytes((const byte *)wlanEntry.bssid, SL_BSSID_LENGTH); - // 'normalize' the security type - if (wlanEntry.sec_type > 2) { - wlanEntry.sec_type = 2; - } - tuple[2] = mp_obj_new_int(wlanEntry.sec_type); - tuple[3] = mp_const_none; - tuple[4] = mp_obj_new_int(wlanEntry.rssi); - - // add the network to the list - mp_obj_list_append(nets, mp_obj_new_attrtuple(wlan_scan_info_fields, 5, tuple)); - - } while (_index < MODWLAN_SL_MAX_NETWORKS); - - return nets; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_scan_obj, wlan_scan); - -STATIC mp_obj_t wlan_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t allowed_args[] = { - { MP_QSTR_ssid, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_auth, MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - }; - - // check for the correct wlan mode - if (wlan_obj.mode == ROLE_AP) { - mp_raise_OSError(MP_EPERM); - } - - // 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 the ssid - size_t ssid_len; - const char *ssid = mp_obj_str_get_data(args[0].u_obj, &ssid_len); - wlan_validate_ssid_len(ssid_len); - - // get the auth config - uint8_t auth = SL_SEC_TYPE_OPEN; - size_t key_len = 0; - const char *key = NULL; - if (args[1].u_obj != mp_const_none) { - mp_obj_t *sec; - mp_obj_get_array_fixed_n(args[1].u_obj, 2, &sec); - auth = mp_obj_get_int(sec[0]); - key = mp_obj_str_get_data(sec[1], &key_len); - wlan_validate_security(auth, key, key_len); - - // convert the wep key if needed - if (auth == SL_SEC_TYPE_WEP) { - _u8 wep_key[32]; - wlan_wep_key_unhexlify(key, (char *)&wep_key); - key = (const char *)&wep_key; - key_len /= 2; - } - } - - // get the bssid - const char *bssid = NULL; - if (args[2].u_obj != mp_const_none) { - bssid = mp_obj_str_get_str(args[2].u_obj); - } - - // get the timeout - int32_t timeout = -1; - if (args[3].u_obj != mp_const_none) { - timeout = mp_obj_get_int(args[3].u_obj); - } - - // connect to the requested access point - modwlan_Status_t status; - status = wlan_do_connect (ssid, ssid_len, bssid, auth, key, key_len, timeout); - if (status == MODWLAN_ERROR_TIMEOUT) { - mp_raise_OSError(MP_ETIMEDOUT); - } else if (status == MODWLAN_ERROR_INVALID_PARAMS) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wlan_connect_obj, 1, wlan_connect); - -STATIC mp_obj_t wlan_disconnect(mp_obj_t self_in) { - wlan_sl_disconnect(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_disconnect_obj, wlan_disconnect); - -STATIC mp_obj_t wlan_isconnected(mp_obj_t self_in) { - return wlan_is_connected() ? mp_const_true : mp_const_false; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_isconnected_obj, wlan_isconnected); - -STATIC mp_obj_t wlan_ifconfig(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t wlan_ifconfig_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_config, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - }; - - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(wlan_ifconfig_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), wlan_ifconfig_args, args); - - // check the interface id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_EPERM); - } - - // get the configuration - if (args[1].u_obj == MP_OBJ_NULL) { - // get - unsigned char len = sizeof(SlNetCfgIpV4Args_t); - unsigned char dhcpIsOn; - SlNetCfgIpV4Args_t ipV4; - sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO, &dhcpIsOn, &len, (uint8_t *)&ipV4); - - mp_obj_t ifconfig[4] = { - netutils_format_ipv4_addr((uint8_t *)&ipV4.ipV4, NETUTILS_LITTLE), - netutils_format_ipv4_addr((uint8_t *)&ipV4.ipV4Mask, NETUTILS_LITTLE), - netutils_format_ipv4_addr((uint8_t *)&ipV4.ipV4Gateway, NETUTILS_LITTLE), - netutils_format_ipv4_addr((uint8_t *)&ipV4.ipV4DnsServer, NETUTILS_LITTLE) - }; - return mp_obj_new_tuple(4, ifconfig); - } else { // set the configuration - if (MP_OBJ_IS_TYPE(args[1].u_obj, &mp_type_tuple)) { - // set a static ip - mp_obj_t *items; - mp_obj_get_array_fixed_n(args[1].u_obj, 4, &items); - - SlNetCfgIpV4Args_t ipV4; - netutils_parse_ipv4_addr(items[0], (uint8_t *)&ipV4.ipV4, NETUTILS_LITTLE); - netutils_parse_ipv4_addr(items[1], (uint8_t *)&ipV4.ipV4Mask, NETUTILS_LITTLE); - netutils_parse_ipv4_addr(items[2], (uint8_t *)&ipV4.ipV4Gateway, NETUTILS_LITTLE); - netutils_parse_ipv4_addr(items[3], (uint8_t *)&ipV4.ipV4DnsServer, NETUTILS_LITTLE); - - if (wlan_obj.mode == ROLE_AP) { - ASSERT_ON_ERROR(sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE, IPCONFIG_MODE_ENABLE_IPV4, sizeof(SlNetCfgIpV4Args_t), (_u8 *)&ipV4)); - SlNetAppDhcpServerBasicOpt_t dhcpParams; - dhcpParams.lease_time = 4096; // lease time (in seconds) of the IP Address - dhcpParams.ipv4_addr_start = ipV4.ipV4 + 1; // first IP Address for allocation. - dhcpParams.ipv4_addr_last = (ipV4.ipV4 & 0xFFFFFF00) + 254; // last IP Address for allocation. - ASSERT_ON_ERROR(sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID)); // stop DHCP server before settings - ASSERT_ON_ERROR(sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, - sizeof(SlNetAppDhcpServerBasicOpt_t), (_u8* )&dhcpParams)); // set parameters - ASSERT_ON_ERROR(sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID)); // start DHCP server with new settings - } else { - ASSERT_ON_ERROR(sl_NetCfgSet(SL_IPV4_STA_P2P_CL_STATIC_ENABLE, IPCONFIG_MODE_ENABLE_IPV4, sizeof(SlNetCfgIpV4Args_t), (_u8 *)&ipV4)); - } - } else { - // check for the correct string - const char *mode = mp_obj_str_get_str(args[1].u_obj); - if (strcmp("dhcp", mode)) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - - // only if we are not in AP mode - if (wlan_obj.mode != ROLE_AP) { - _u8 val = 1; - sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE, IPCONFIG_MODE_ENABLE_IPV4, 1, &val); - } - } - // config values have changed, so reset - wlan_reset(); - // set current time and date (needed to validate certificates) - wlan_set_current_time (pyb_rtc_get_seconds()); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wlan_ifconfig_obj, 1, wlan_ifconfig); - -STATIC mp_obj_t wlan_mode(size_t n_args, const mp_obj_t *args) { - wlan_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_int(self->mode); - } else { - uint mode = mp_obj_get_int(args[1]); - wlan_validate_mode(mode); - wlan_set_mode(mode); - wlan_reset(); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_mode_obj, 1, 2, wlan_mode); - -STATIC mp_obj_t wlan_ssid(size_t n_args, const mp_obj_t *args) { - wlan_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_str((const char *)self->ssid, strlen((const char *)self->ssid), false); - } else { - size_t len; - const char *ssid = mp_obj_str_get_data(args[1], &len); - wlan_validate_ssid_len(len); - wlan_set_ssid(ssid, len, false); - wlan_reset(); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_ssid_obj, 1, 2, wlan_ssid); - -STATIC mp_obj_t wlan_auth(size_t n_args, const mp_obj_t *args) { - wlan_obj_t *self = args[0]; - if (n_args == 1) { - if (self->auth == SL_SEC_TYPE_OPEN) { - return mp_const_none; - } else { - mp_obj_t security[2]; - security[0] = mp_obj_new_int(self->auth); - security[1] = mp_obj_new_str((const char *)self->key, strlen((const char *)self->key), false); - return mp_obj_new_tuple(2, security); - } - } else { - // get the auth config - uint8_t auth = SL_SEC_TYPE_OPEN; - size_t key_len = 0; - const char *key = NULL; - if (args[1] != mp_const_none) { - mp_obj_t *sec; - mp_obj_get_array_fixed_n(args[1], 2, &sec); - auth = mp_obj_get_int(sec[0]); - key = mp_obj_str_get_data(sec[1], &key_len); - wlan_validate_security(auth, key, key_len); - } - wlan_set_security(auth, key, key_len); - wlan_reset(); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_auth_obj, 1, 2, wlan_auth); - -STATIC mp_obj_t wlan_channel(size_t n_args, const mp_obj_t *args) { - wlan_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_int(self->channel); - } else { - uint8_t channel = mp_obj_get_int(args[1]); - wlan_validate_channel(channel); - wlan_set_channel(channel); - wlan_reset(); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_channel_obj, 1, 2, wlan_channel); - -STATIC mp_obj_t wlan_antenna(size_t n_args, const mp_obj_t *args) { - wlan_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_int(self->antenna); - } else { - #if MICROPY_HW_ANTENNA_DIVERSITY - uint8_t antenna = mp_obj_get_int(args[1]); - wlan_validate_antenna(antenna); - wlan_set_antenna(antenna); - #endif - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_antenna_obj, 1, 2, wlan_antenna); - -STATIC mp_obj_t wlan_mac(size_t n_args, const mp_obj_t *args) { - wlan_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_bytes((const byte *)self->mac, SL_BSSID_LENGTH); - } else { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); - if (bufinfo.len != 6) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - memcpy(self->mac, bufinfo.buf, SL_MAC_ADDR_LEN); - sl_NetCfgSet(SL_MAC_ADDRESS_SET, 1, SL_MAC_ADDR_LEN, (_u8 *)self->mac); - wlan_reset(); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_mac_obj, 1, 2, wlan_mac); - -STATIC mp_obj_t wlan_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[mp_irq_INIT_NUM_ARGS]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, mp_irq_INIT_NUM_ARGS, mp_irq_init_args, args); - - wlan_obj_t *self = pos_args[0]; - - // check the trigger, only one type is supported - if (mp_obj_get_int(args[0].u_obj) != MODWLAN_WIFI_EVENT_ANY) { - goto invalid_args; - } - - // check the power mode - if (mp_obj_get_int(args[3].u_obj) != PYB_PWR_MODE_LPDS) { - goto invalid_args; - } - - // create the callback - mp_obj_t _irq = mp_irq_new (self, args[2].u_obj, &wlan_irq_methods); - self->irq_obj = _irq; - - // enable the irq just before leaving - wlan_lpds_irq_enable(self); - - return _irq; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wlan_irq_obj, 1, wlan_irq); - -//STATIC mp_obj_t wlan_connections (mp_obj_t self_in) { -// mp_obj_t device[2]; -// mp_obj_t connections = mp_obj_new_list(0, NULL); -// -// if (wlan_is_connected()) { -// device[0] = mp_obj_new_str((const char *)wlan_obj.ssid_o, strlen((const char *)wlan_obj.ssid_o), false); -// device[1] = mp_obj_new_bytes((const byte *)wlan_obj.bssid, SL_BSSID_LENGTH); -// // add the device to the list -// mp_obj_list_append(connections, mp_obj_new_tuple(MP_ARRAY_SIZE(device), device)); -// } -// return connections; -//} -//STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_connections_obj, wlan_connections); - -//STATIC mp_obj_t wlan_urn (uint n_args, const mp_obj_t *args) { -// char urn[MAX_DEVICE_URN_LEN]; -// uint8_t len = MAX_DEVICE_URN_LEN; -// -// // an URN is given, so set it -// if (n_args == 2) { -// const char *p = mp_obj_str_get_str(args[1]); -// uint8_t len = strlen(p); -// -// // the call to sl_NetAppSet corrupts the input string URN=args[1], so we copy into a local buffer -// if (len > MAX_DEVICE_URN_LEN) { -// mp_raise_ValueError(mpexception_value_invalid_arguments); -// } -// strcpy(urn, p); -// -// if (sl_NetAppSet(SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN, len, (unsigned char *)urn) < 0) { -// mp_raise_OSError(MP_EIO); -// } -// } -// else { -// // get the URN -// if (sl_NetAppGet(SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN, &len, (uint8_t *)urn) < 0) { -// mp_raise_OSError(MP_EIO); -// } -// return mp_obj_new_str(urn, (len - 1), false); -// } -// -// return mp_const_none; -//} -//STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wlan_urn_obj, 1, 2, wlan_urn); - -STATIC mp_obj_t wlan_print_ver(void) { - SlVersionFull ver; - byte config_opt = SL_DEVICE_GENERAL_VERSION; - byte config_len = sizeof(ver); - sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &config_opt, &config_len, (byte*)&ver); - printf("NWP: %d.%d.%d.%d\n", (int)ver.NwpVersion[0], (int)ver.NwpVersion[1], (int)ver.NwpVersion[2], (int)ver.NwpVersion[3]); - printf("MAC: %d.%d.%d.%d\n", (int)ver.ChipFwAndPhyVersion.FwVersion[0], (int)ver.ChipFwAndPhyVersion.FwVersion[1], - (int)ver.ChipFwAndPhyVersion.FwVersion[2], (int)ver.ChipFwAndPhyVersion.FwVersion[3]); - printf("PHY: %d.%d.%d.%d\n", ver.ChipFwAndPhyVersion.PhyVersion[0], ver.ChipFwAndPhyVersion.PhyVersion[1], - ver.ChipFwAndPhyVersion.PhyVersion[2], ver.ChipFwAndPhyVersion.PhyVersion[3]); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_0(wlan_print_ver_fun_obj, wlan_print_ver); -STATIC MP_DEFINE_CONST_STATICMETHOD_OBJ(wlan_print_ver_obj, MP_ROM_PTR(&wlan_print_ver_fun_obj)); - -STATIC const mp_rom_map_elem_t wlan_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&wlan_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&wlan_scan_obj) }, - { MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&wlan_connect_obj) }, - { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&wlan_disconnect_obj) }, - { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&wlan_isconnected_obj) }, - { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&wlan_ifconfig_obj) }, - { MP_ROM_QSTR(MP_QSTR_mode), MP_ROM_PTR(&wlan_mode_obj) }, - { MP_ROM_QSTR(MP_QSTR_ssid), MP_ROM_PTR(&wlan_ssid_obj) }, - { MP_ROM_QSTR(MP_QSTR_auth), MP_ROM_PTR(&wlan_auth_obj) }, - { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&wlan_channel_obj) }, - { MP_ROM_QSTR(MP_QSTR_antenna), MP_ROM_PTR(&wlan_antenna_obj) }, - { MP_ROM_QSTR(MP_QSTR_mac), MP_ROM_PTR(&wlan_mac_obj) }, - { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&wlan_irq_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_connections), MP_ROM_PTR(&wlan_connections_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_urn), MP_ROM_PTR(&wlan_urn_obj) }, - { MP_ROM_QSTR(MP_QSTR_print_ver), MP_ROM_PTR(&wlan_print_ver_obj) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_STA), MP_ROM_INT(ROLE_STA) }, - { MP_ROM_QSTR(MP_QSTR_AP), MP_ROM_INT(ROLE_AP) }, - { MP_ROM_QSTR(MP_QSTR_WEP), MP_ROM_INT(SL_SEC_TYPE_WEP) }, - { MP_ROM_QSTR(MP_QSTR_WPA), MP_ROM_INT(SL_SEC_TYPE_WPA_WPA2) }, - { MP_ROM_QSTR(MP_QSTR_WPA2), MP_ROM_INT(SL_SEC_TYPE_WPA_WPA2) }, - #if MICROPY_HW_ANTENNA_DIVERSITY - { MP_ROM_QSTR(MP_QSTR_INT_ANT), MP_ROM_INT(ANTENNA_TYPE_INTERNAL) }, - { MP_ROM_QSTR(MP_QSTR_EXT_ANT), MP_ROM_INT(ANTENNA_TYPE_EXTERNAL) }, - #endif - { MP_ROM_QSTR(MP_QSTR_ANY_EVENT), MP_ROM_INT(MODWLAN_WIFI_EVENT_ANY) }, -}; -STATIC MP_DEFINE_CONST_DICT(wlan_locals_dict, wlan_locals_dict_table); - -const mod_network_nic_type_t mod_network_nic_type_wlan = { - .base = { - { &mp_type_type }, - .name = MP_QSTR_WLAN, - .make_new = wlan_make_new, - .locals_dict = (mp_obj_t)&wlan_locals_dict, - }, -}; - -STATIC const mp_irq_methods_t wlan_irq_methods = { - .init = wlan_irq, - .enable = wlan_lpds_irq_enable, - .disable = wlan_lpds_irq_disable, - .flags = wlan_irq_flags, -}; diff --git a/cc3200/mods/modwlan.h b/cc3200/mods/modwlan.h deleted file mode 100644 index b806644f5..000000000 --- a/cc3200/mods/modwlan.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_MODWLAN_H -#define MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define SIMPLELINK_SPAWN_TASK_PRIORITY 3 -#define SIMPLELINK_TASK_STACK_SIZE 2048 -#define SL_STOP_TIMEOUT 35 -#define SL_STOP_TIMEOUT_LONG 575 - -#define MODWLAN_WIFI_EVENT_ANY 0x01 - -#define MODWLAN_SSID_LEN_MAX 32 - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef enum { - MODWLAN_OK = 0, - MODWLAN_ERROR_INVALID_PARAMS = -1, - MODWLAN_ERROR_TIMEOUT = -2, - MODWLAN_ERROR_UNKNOWN = -3, -} modwlan_Status_t; - -typedef struct _wlan_obj_t { - mp_obj_base_t base; - mp_obj_t irq_obj; - uint32_t status; - - uint32_t ip; - - int8_t mode; - uint8_t auth; - uint8_t channel; - uint8_t antenna; - - // my own ssid, key and mac - uint8_t ssid[(MODWLAN_SSID_LEN_MAX + 1)]; - uint8_t key[65]; - uint8_t mac[SL_MAC_ADDR_LEN]; - - // the sssid (or name) and mac of the other device - uint8_t ssid_o[33]; - uint8_t bssid[6]; - uint8_t irq_flags; - bool irq_enabled; - -#if (MICROPY_PORT_HAS_TELNET || MICROPY_PORT_HAS_FTP) - bool servers_enabled; -#endif -} wlan_obj_t; - -/****************************************************************************** - DECLARE PUBLIC DATA - ******************************************************************************/ -extern _SlLockObj_t wlan_LockObj; - -/****************************************************************************** - DECLARE PUBLIC FUNCTIONS - ******************************************************************************/ -extern void wlan_pre_init (void); -extern void wlan_sl_init (int8_t mode, const char *ssid, uint8_t ssid_len, uint8_t auth, const char *key, uint8_t key_len, - uint8_t channel, uint8_t antenna, bool add_mac); -extern void wlan_first_start (void); -extern void wlan_update(void); -extern void wlan_stop (uint32_t timeout); -extern void wlan_get_mac (uint8_t *macAddress); -extern void wlan_get_ip (uint32_t *ip); -extern bool wlan_is_connected (void); -extern void wlan_set_current_time (uint32_t seconds_since_2000); -extern void wlan_off_on (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_MODWLAN_H diff --git a/cc3200/mods/pybadc.c b/cc3200/mods/pybadc.c deleted file mode 100644 index 850664cab..000000000 --- a/cc3200/mods/pybadc.c +++ /dev/null @@ -1,312 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpconfig.h" -#include "py/nlr.h" -#include "py/runtime.h" -#include "py/binary.h" -#include "py/gc.h" -#include "py/mperrno.h" -#include "bufhelper.h" -#include "inc/hw_types.h" -#include "inc/hw_adc.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "interrupt.h" -#include "pin.h" -#include "gpio.h" -#include "prcm.h" -#include "adc.h" -#include "pybadc.h" -#include "pybpin.h" -#include "pybsleep.h" -#include "pins.h" -#include "mpexception.h" - - -/****************************************************************************** - DECLARE CONSTANTS - ******************************************************************************/ -#define PYB_ADC_NUM_CHANNELS 4 - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef struct { - mp_obj_base_t base; - bool enabled; -} pyb_adc_obj_t; - -typedef struct { - mp_obj_base_t base; - pin_obj_t *pin; - byte channel; - byte id; - bool enabled; -} pyb_adc_channel_obj_t; - - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC pyb_adc_channel_obj_t pyb_adc_channel_obj[PYB_ADC_NUM_CHANNELS] = { {.pin = &pin_GP2, .channel = ADC_CH_0, .id = 0, .enabled = false}, - {.pin = &pin_GP3, .channel = ADC_CH_1, .id = 1, .enabled = false}, - {.pin = &pin_GP4, .channel = ADC_CH_2, .id = 2, .enabled = false}, - {.pin = &pin_GP5, .channel = ADC_CH_3, .id = 3, .enabled = false} }; -STATIC pyb_adc_obj_t pyb_adc_obj = {.enabled = false}; - -STATIC const mp_obj_type_t pyb_adc_channel_type; - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC mp_obj_t adc_channel_deinit(mp_obj_t self_in); - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -STATIC void pyb_adc_init (pyb_adc_obj_t *self) { - // enable and configure the timer - MAP_ADCTimerConfig(ADC_BASE, (1 << 17) - 1); - MAP_ADCTimerEnable(ADC_BASE); - // enable the ADC peripheral - MAP_ADCEnable(ADC_BASE); - self->enabled = true; -} - -STATIC void pyb_adc_check_init(void) { - // not initialized - if (!pyb_adc_obj.enabled) { - mp_raise_OSError(MP_EPERM); - } -} - -STATIC void pyb_adc_channel_init (pyb_adc_channel_obj_t *self) { - // the ADC block must be enabled first - pyb_adc_check_init(); - // configure the pin in analog mode - pin_config (self->pin, -1, PIN_TYPE_ANALOG, PIN_TYPE_STD, -1, PIN_STRENGTH_2MA); - // enable the ADC channel - MAP_ADCChannelEnable(ADC_BASE, self->channel); - self->enabled = true; -} - -STATIC void pyb_adc_deinit_all_channels (void) { - for (int i = 0; i < PYB_ADC_NUM_CHANNELS; i++) { - adc_channel_deinit(&pyb_adc_channel_obj[i]); - } -} - -/******************************************************************************/ -/* MicroPython bindings : adc object */ - -STATIC void adc_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_adc_obj_t *self = self_in; - if (self->enabled) { - mp_printf(print, "ADC(0, bits=12)"); - } else { - mp_printf(print, "ADC(0)"); - } -} - -STATIC const mp_arg_t pyb_adc_init_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 12} }, -}; -STATIC mp_obj_t adc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_adc_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_adc_init_args, args); - - // check the peripheral id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_ENODEV); - } - - // check the number of bits - if (args[1].u_int != 12) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - - // setup the object - pyb_adc_obj_t *self = &pyb_adc_obj; - self->base.type = &pyb_adc_type; - - // initialize and register with the sleep module - pyb_adc_init(self); - pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)pyb_adc_init); - return self; -} - -STATIC mp_obj_t adc_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_adc_init_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &pyb_adc_init_args[1], args); - // check the number of bits - if (args[0].u_int != 12) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - pyb_adc_init(pos_args[0]); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(adc_init_obj, 1, adc_init); - -STATIC mp_obj_t adc_deinit(mp_obj_t self_in) { - pyb_adc_obj_t *self = self_in; - // first deinit all channels - pyb_adc_deinit_all_channels(); - MAP_ADCDisable(ADC_BASE); - self->enabled = false; - // unregister it with the sleep module - pyb_sleep_remove ((const mp_obj_t)self); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_deinit_obj, adc_deinit); - -STATIC mp_obj_t adc_channel(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t pyb_adc_channel_args[] = { - { MP_QSTR_id, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - }; - - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_adc_channel_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), pyb_adc_channel_args, args); - - uint ch_id; - if (args[0].u_obj != MP_OBJ_NULL) { - ch_id = mp_obj_get_int(args[0].u_obj); - if (ch_id >= PYB_ADC_NUM_CHANNELS) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } else if (args[1].u_obj != mp_const_none) { - uint pin_ch_id = pin_find_peripheral_type (args[1].u_obj, PIN_FN_ADC, 0); - if (ch_id != pin_ch_id) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - } - } else { - ch_id = pin_find_peripheral_type (args[1].u_obj, PIN_FN_ADC, 0); - } - - // setup the object - pyb_adc_channel_obj_t *self = &pyb_adc_channel_obj[ch_id]; - self->base.type = &pyb_adc_channel_type; - pyb_adc_channel_init (self); - // register it with the sleep module - pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)pyb_adc_channel_init); - return self; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(adc_channel_obj, 1, adc_channel); - -STATIC const mp_rom_map_elem_t adc_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&adc_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&adc_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&adc_channel_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(adc_locals_dict, adc_locals_dict_table); - -const mp_obj_type_t pyb_adc_type = { - { &mp_type_type }, - .name = MP_QSTR_ADC, - .print = adc_print, - .make_new = adc_make_new, - .locals_dict = (mp_obj_t)&adc_locals_dict, -}; - -STATIC void adc_channel_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_adc_channel_obj_t *self = self_in; - if (self->enabled) { - mp_printf(print, "ADCChannel(%u, pin=%q)", self->id, self->pin->name); - } else { - mp_printf(print, "ADCChannel(%u)", self->id); - } -} - -STATIC mp_obj_t adc_channel_init(mp_obj_t self_in) { - pyb_adc_channel_obj_t *self = self_in; - // re-enable it - pyb_adc_channel_init(self); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_channel_init_obj, adc_channel_init); - -STATIC mp_obj_t adc_channel_deinit(mp_obj_t self_in) { - pyb_adc_channel_obj_t *self = self_in; - - MAP_ADCChannelDisable(ADC_BASE, self->channel); - // unregister it with the sleep module - pyb_sleep_remove ((const mp_obj_t)self); - self->enabled = false; - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_channel_deinit_obj, adc_channel_deinit); - -STATIC mp_obj_t adc_channel_value(mp_obj_t self_in) { - pyb_adc_channel_obj_t *self = self_in; - uint32_t value; - - // the channel must be enabled - if (!self->enabled) { - mp_raise_OSError(MP_EPERM); - } - - // wait until a new value is available - while (!MAP_ADCFIFOLvlGet(ADC_BASE, self->channel)); - // read the sample - value = MAP_ADCFIFORead(ADC_BASE, self->channel); - // the 12 bit sampled value is stored in bits [13:2] - return MP_OBJ_NEW_SMALL_INT((value & 0x3FFF) >> 2); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(adc_channel_value_obj, adc_channel_value); - -STATIC mp_obj_t adc_channel_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, 0, false); - return adc_channel_value (self_in); -} - -STATIC const mp_rom_map_elem_t adc_channel_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&adc_channel_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&adc_channel_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&adc_channel_value_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(adc_channel_locals_dict, adc_channel_locals_dict_table); - -STATIC const mp_obj_type_t pyb_adc_channel_type = { - { &mp_type_type }, - .name = MP_QSTR_ADCChannel, - .print = adc_channel_print, - .call = adc_channel_call, - .locals_dict = (mp_obj_t)&adc_channel_locals_dict, -}; diff --git a/cc3200/mods/pybadc.h b/cc3200/mods/pybadc.h deleted file mode 100644 index db04b006b..000000000 --- a/cc3200/mods/pybadc.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBADC_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBADC_H - -extern const mp_obj_type_t pyb_adc_type; - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBADC_H diff --git a/cc3200/mods/pybflash.c b/cc3200/mods/pybflash.c deleted file mode 100644 index 51f4cb517..000000000 --- a/cc3200/mods/pybflash.c +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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 <stdint.h> -//#include <string.h> - -#include "py/runtime.h" -#include "lib/oofatfs/ff.h" -#include "lib/oofatfs/diskio.h" -#include "extmod/vfs_fat.h" - -#include "fatfs/src/drivers/sflash_diskio.h" -#include "mods/pybflash.h" - -/******************************************************************************/ -// MicroPython bindings to expose the internal flash as an object with the -// block protocol. - -// there is a singleton Flash object -STATIC const mp_obj_base_t pyb_flash_obj = {&pyb_flash_type}; - -STATIC mp_obj_t pyb_flash_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, 0, false); - - // return singleton object - return (mp_obj_t)&pyb_flash_obj; -} - -STATIC mp_obj_t pyb_flash_readblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_WRITE); - DRESULT res = sflash_disk_read(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / SFLASH_SECTOR_SIZE); - return MP_OBJ_NEW_SMALL_INT(res != RES_OK); // return of 0 means success -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_readblocks_obj, pyb_flash_readblocks); - -STATIC mp_obj_t pyb_flash_writeblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); - DRESULT res = sflash_disk_write(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / SFLASH_SECTOR_SIZE); - return MP_OBJ_NEW_SMALL_INT(res != RES_OK); // return of 0 means success -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_writeblocks_obj, pyb_flash_writeblocks); - -STATIC mp_obj_t pyb_flash_ioctl(mp_obj_t self, mp_obj_t cmd_in, mp_obj_t arg_in) { - mp_int_t cmd = mp_obj_get_int(cmd_in); - switch (cmd) { - case BP_IOCTL_INIT: return MP_OBJ_NEW_SMALL_INT(sflash_disk_init() != RES_OK); - case BP_IOCTL_DEINIT: sflash_disk_flush(); return MP_OBJ_NEW_SMALL_INT(0); - case BP_IOCTL_SYNC: sflash_disk_flush(); return MP_OBJ_NEW_SMALL_INT(0); - case BP_IOCTL_SEC_COUNT: return MP_OBJ_NEW_SMALL_INT(SFLASH_SECTOR_COUNT); - case BP_IOCTL_SEC_SIZE: return MP_OBJ_NEW_SMALL_INT(SFLASH_SECTOR_SIZE); - default: return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_flash_ioctl_obj, pyb_flash_ioctl); - -STATIC const mp_rom_map_elem_t pyb_flash_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&pyb_flash_readblocks_obj) }, - { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&pyb_flash_writeblocks_obj) }, - { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&pyb_flash_ioctl_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(pyb_flash_locals_dict, pyb_flash_locals_dict_table); - -const mp_obj_type_t pyb_flash_type = { - { &mp_type_type }, - .name = MP_QSTR_Flash, - .make_new = pyb_flash_make_new, - .locals_dict = (mp_obj_t)&pyb_flash_locals_dict, -}; - -void pyb_flash_init_vfs(fs_user_mount_t *vfs) { - vfs->base.type = &mp_fat_vfs_type; - vfs->flags |= FSUSER_NATIVE | FSUSER_HAVE_IOCTL; - vfs->fatfs.drv = vfs; - vfs->readblocks[0] = (mp_obj_t)&pyb_flash_readblocks_obj; - vfs->readblocks[1] = (mp_obj_t)&pyb_flash_obj; - vfs->readblocks[2] = (mp_obj_t)sflash_disk_read; // native version - vfs->writeblocks[0] = (mp_obj_t)&pyb_flash_writeblocks_obj; - vfs->writeblocks[1] = (mp_obj_t)&pyb_flash_obj; - vfs->writeblocks[2] = (mp_obj_t)sflash_disk_write; // native version - vfs->u.ioctl[0] = (mp_obj_t)&pyb_flash_ioctl_obj; - vfs->u.ioctl[1] = (mp_obj_t)&pyb_flash_obj; -} diff --git a/cc3200/mods/pybflash.h b/cc3200/mods/pybflash.h deleted file mode 100644 index 6f8ddf291..000000000 --- a/cc3200/mods/pybflash.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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_CC3200_MODS_PYBFLASH_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBFLASH_H - -#include "py/obj.h" - -extern const mp_obj_type_t pyb_flash_type; - -void pyb_flash_init_vfs(fs_user_mount_t *vfs); - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBFLASH_H diff --git a/cc3200/mods/pybi2c.c b/cc3200/mods/pybi2c.c deleted file mode 100644 index efb78a44d..000000000 --- a/cc3200/mods/pybi2c.c +++ /dev/null @@ -1,532 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpstate.h" -#include "py/runtime.h" -#include "py/mperrno.h" -#include "py/mphal.h" -#include "bufhelper.h" -#include "inc/hw_types.h" -#include "inc/hw_i2c.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "pin.h" -#include "prcm.h" -#include "i2c.h" -#include "pybi2c.h" -#include "mpexception.h" -#include "pybsleep.h" -#include "utils.h" -#include "pybpin.h" -#include "pins.h" - -/// \moduleref pyb -/// \class I2C - a two-wire serial protocol - -typedef struct _pyb_i2c_obj_t { - mp_obj_base_t base; - uint baudrate; -} pyb_i2c_obj_t; - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define PYBI2C_MIN_BAUD_RATE_HZ (50000) -#define PYBI2C_MAX_BAUD_RATE_HZ (400000) - -#define PYBI2C_TRANSC_TIMEOUT_MS (20) -#define PYBI2C_TRANSAC_WAIT_DELAY_US (10) - -#define PYBI2C_TIMEOUT_TO_COUNT(to_us, baud) (((baud) * to_us) / 16000000) - -#define RET_IF_ERR(Func) { \ - if (!Func) { \ - return false; \ - } \ - } - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC pyb_i2c_obj_t pyb_i2c_obj = {.baudrate = 0}; - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC bool pyb_i2c_write(byte addr, byte *data, uint len, bool stop); - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -// only master mode is available for the moment -STATIC void i2c_init (pyb_i2c_obj_t *self) { - // Enable the I2C Peripheral - MAP_PRCMPeripheralClkEnable(PRCM_I2CA0, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - MAP_PRCMPeripheralReset(PRCM_I2CA0); - // Configure I2C module with the specified baudrate - MAP_I2CMasterInitExpClk(I2CA0_BASE, self->baudrate); -} - -STATIC bool pyb_i2c_transaction(uint cmd) { - // Convert the timeout to microseconds - int32_t timeout = PYBI2C_TRANSC_TIMEOUT_MS * 1000; - // Sanity check, t_timeout must be between 1 and 255 - uint t_timeout = MIN(PYBI2C_TIMEOUT_TO_COUNT(timeout, pyb_i2c_obj.baudrate), 255); - // Clear all interrupts - MAP_I2CMasterIntClearEx(I2CA0_BASE, MAP_I2CMasterIntStatusEx(I2CA0_BASE, false)); - // Set the time-out in terms of clock cycles. Not to be used with breakpoints. - MAP_I2CMasterTimeoutSet(I2CA0_BASE, t_timeout); - // Initiate the transfer. - MAP_I2CMasterControl(I2CA0_BASE, cmd); - // Wait until the current byte has been transferred. - // Poll on the raw interrupt status. - while ((MAP_I2CMasterIntStatusEx(I2CA0_BASE, false) & (I2C_MASTER_INT_DATA | I2C_MASTER_INT_TIMEOUT)) == 0) { - if (timeout < 0) { - // the peripheral is not responding, so stop - return false; - } - // wait for a few microseconds - UtilsDelay(UTILS_DELAY_US_TO_COUNT(PYBI2C_TRANSAC_WAIT_DELAY_US)); - timeout -= PYBI2C_TRANSAC_WAIT_DELAY_US; - } - - // Check for any errors in the transfer - if (MAP_I2CMasterErr(I2CA0_BASE) != I2C_MASTER_ERR_NONE) { - switch(cmd) { - case I2C_MASTER_CMD_BURST_SEND_START: - case I2C_MASTER_CMD_BURST_SEND_CONT: - case I2C_MASTER_CMD_BURST_SEND_STOP: - MAP_I2CMasterControl(I2CA0_BASE, I2C_MASTER_CMD_BURST_SEND_ERROR_STOP); - break; - case I2C_MASTER_CMD_BURST_RECEIVE_START: - case I2C_MASTER_CMD_BURST_RECEIVE_CONT: - case I2C_MASTER_CMD_BURST_RECEIVE_FINISH: - MAP_I2CMasterControl(I2CA0_BASE, I2C_MASTER_CMD_BURST_RECEIVE_ERROR_STOP); - break; - default: - break; - } - return false; - } - return true; -} - -STATIC void pyb_i2c_check_init(pyb_i2c_obj_t *self) { - // not initialized - if (!self->baudrate) { - mp_raise_OSError(MP_EPERM); - } -} - -STATIC bool pyb_i2c_scan_device(byte devAddr) { - bool ret = false; - // Set the I2C slave address - MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, devAddr, true); - // Initiate the transfer. - if (pyb_i2c_transaction(I2C_MASTER_CMD_SINGLE_RECEIVE)) { - ret = true; - } - // Send the stop bit to cancel the read transaction - MAP_I2CMasterControl(I2CA0_BASE, I2C_MASTER_CMD_BURST_SEND_ERROR_STOP); - if (!ret) { - uint8_t data = 0; - if (pyb_i2c_write(devAddr, &data, sizeof(data), true)) { - ret = true; - } - } - return ret; -} - -STATIC bool pyb_i2c_mem_addr_write (byte addr, byte *mem_addr, uint mem_addr_len) { - // Set I2C codec slave address - MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, addr, false); - // Write the first byte to the controller. - MAP_I2CMasterDataPut(I2CA0_BASE, *mem_addr++); - // Initiate the transfer. - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_START)); - - // Loop until the completion of transfer or error - while (--mem_addr_len) { - // Write the next byte of data - MAP_I2CMasterDataPut(I2CA0_BASE, *mem_addr++); - // Transact over I2C to send the next byte - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_CONT)); - } - return true; -} - -STATIC bool pyb_i2c_mem_write (byte addr, byte *mem_addr, uint mem_addr_len, byte *data, uint data_len) { - if (pyb_i2c_mem_addr_write (addr, mem_addr, mem_addr_len)) { - // Loop until the completion of transfer or error - while (data_len--) { - // Write the next byte of data - MAP_I2CMasterDataPut(I2CA0_BASE, *data++); - // Transact over I2C to send the byte - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_CONT)); - } - // send the stop bit - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_STOP)); - return true; - } - return false; -} - -STATIC bool pyb_i2c_write(byte addr, byte *data, uint len, bool stop) { - // Set I2C codec slave address - MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, addr, false); - // Write the first byte to the controller. - MAP_I2CMasterDataPut(I2CA0_BASE, *data++); - // Initiate the transfer. - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_START)); - - // Loop until the completion of transfer or error - while (--len) { - // Write the next byte of data - MAP_I2CMasterDataPut(I2CA0_BASE, *data++); - // Transact over I2C to send the byte - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_CONT)); - } - - // If a stop bit is to be sent, do it. - if (stop) { - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_SEND_STOP)); - } - return true; -} - -STATIC bool pyb_i2c_read(byte addr, byte *data, uint len) { - // Initiate a burst or single receive sequence - uint cmd = --len > 0 ? I2C_MASTER_CMD_BURST_RECEIVE_START : I2C_MASTER_CMD_SINGLE_RECEIVE; - // Set I2C codec slave address - MAP_I2CMasterSlaveAddrSet(I2CA0_BASE, addr, true); - // Initiate the transfer. - RET_IF_ERR(pyb_i2c_transaction(cmd)); - // Loop until the completion of reception or error - while (len) { - // Receive the byte over I2C - *data++ = MAP_I2CMasterDataGet(I2CA0_BASE); - if (--len) { - // Continue with reception - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_RECEIVE_CONT)); - } else { - // Complete the last reception - RET_IF_ERR(pyb_i2c_transaction(I2C_MASTER_CMD_BURST_RECEIVE_FINISH)); - } - } - - // Receive the last byte over I2C - *data = MAP_I2CMasterDataGet(I2CA0_BASE); - return true; -} - -STATIC void pyb_i2c_read_into (mp_arg_val_t *args, vstr_t *vstr) { - pyb_i2c_check_init(&pyb_i2c_obj); - // get the buffer to receive into - pyb_buf_get_for_recv(args[1].u_obj, vstr); - - // receive the data - if (!pyb_i2c_read(args[0].u_int, (byte *)vstr->buf, vstr->len)) { - mp_raise_OSError(MP_EIO); - } -} - -STATIC void pyb_i2c_readmem_into (mp_arg_val_t *args, vstr_t *vstr) { - pyb_i2c_check_init(&pyb_i2c_obj); - // get the buffer to receive into - pyb_buf_get_for_recv(args[2].u_obj, vstr); - - // get the addresses - mp_uint_t i2c_addr = args[0].u_int; - mp_uint_t mem_addr = args[1].u_int; - // determine the width of mem_addr (1 or 2 bytes) - mp_uint_t mem_addr_size = args[3].u_int >> 3; - - // write the register address to be read from - if (pyb_i2c_mem_addr_write (i2c_addr, (byte *)&mem_addr, mem_addr_size)) { - // Read the specified length of data - if (!pyb_i2c_read (i2c_addr, (byte *)vstr->buf, vstr->len)) { - mp_raise_OSError(MP_EIO); - } - } else { - mp_raise_OSError(MP_EIO); - } -} - -/******************************************************************************/ -/* MicroPython bindings */ -/******************************************************************************/ -STATIC void pyb_i2c_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_i2c_obj_t *self = self_in; - if (self->baudrate > 0) { - mp_printf(print, "I2C(0, baudrate=%u)", self->baudrate); - } else { - mp_print_str(print, "I2C(0)"); - } -} - -STATIC mp_obj_t pyb_i2c_init_helper(pyb_i2c_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_scl, ARG_sda, ARG_freq }; - static const mp_arg_t allowed_args[] = { - { MP_QSTR_scl, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_sda, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 100000} }, - }; - 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); - - // make sure the baudrate is between the valid range - self->baudrate = MIN(MAX(args[ARG_freq].u_int, PYBI2C_MIN_BAUD_RATE_HZ), PYBI2C_MAX_BAUD_RATE_HZ); - - // assign the pins - mp_obj_t pins[2] = {&pin_GP13, &pin_GP23}; // default (SDA, SCL) pins - if (args[ARG_scl].u_obj != MP_OBJ_NULL) { - pins[1] = args[ARG_scl].u_obj; - } - if (args[ARG_sda].u_obj != MP_OBJ_NULL) { - pins[0] = args[ARG_sda].u_obj; - } - pin_assign_pins_af(pins, 2, PIN_TYPE_STD_PU, PIN_FN_I2C, 0); - - // init the I2C bus - i2c_init(self); - - // register it with the sleep module - pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)i2c_init); - - return mp_const_none; -} - -STATIC mp_obj_t pyb_i2c_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // check the id argument, if given - if (n_args > 0) { - if (all_args[0] != MP_OBJ_NEW_SMALL_INT(0)) { - mp_raise_OSError(MP_ENODEV); - } - --n_args; - ++all_args; - } - - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - - // setup the object - pyb_i2c_obj_t *self = &pyb_i2c_obj; - self->base.type = &pyb_i2c_type; - - // start the peripheral - pyb_i2c_init_helper(self, n_args, all_args, &kw_args); - - return (mp_obj_t)self; -} - -STATIC mp_obj_t pyb_i2c_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - return pyb_i2c_init_helper(pos_args[0], n_args - 1, pos_args + 1, kw_args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_init_obj, 1, pyb_i2c_init); - -STATIC mp_obj_t pyb_i2c_deinit(mp_obj_t self_in) { - // disable the peripheral - MAP_I2CMasterDisable(I2CA0_BASE); - MAP_PRCMPeripheralClkDisable(PRCM_I2CA0, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - // invalidate the baudrate - pyb_i2c_obj.baudrate = 0; - // unregister it with the sleep module - pyb_sleep_remove ((const mp_obj_t)self_in); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_deinit_obj, pyb_i2c_deinit); - -STATIC mp_obj_t pyb_i2c_scan(mp_obj_t self_in) { - pyb_i2c_check_init(&pyb_i2c_obj); - mp_obj_t list = mp_obj_new_list(0, NULL); - for (uint addr = 0x08; addr <= 0x77; addr++) { - for (int i = 0; i < 3; i++) { - if (pyb_i2c_scan_device(addr)) { - mp_obj_list_append(list, mp_obj_new_int(addr)); - break; - } - } - } - return list; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_i2c_scan_obj, pyb_i2c_scan); - -STATIC mp_obj_t pyb_i2c_readfrom(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t pyb_i2c_readfrom_args[] = { - { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_nbytes, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - }; - - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_readfrom_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), pyb_i2c_readfrom_args, args); - - vstr_t vstr; - pyb_i2c_read_into(args, &vstr); - - // return the received data - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_readfrom_obj, 3, pyb_i2c_readfrom); - -STATIC mp_obj_t pyb_i2c_readfrom_into(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t pyb_i2c_readfrom_into_args[] = { - { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_buf, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - }; - - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_readfrom_into_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), pyb_i2c_readfrom_into_args, args); - - vstr_t vstr; - pyb_i2c_read_into(args, &vstr); - - // return the number of bytes received - return mp_obj_new_int(vstr.len); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_readfrom_into_obj, 1, pyb_i2c_readfrom_into); - -STATIC mp_obj_t pyb_i2c_writeto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t pyb_i2c_writeto_args[] = { - { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_buf, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_stop, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, - }; - - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_writeto_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), pyb_i2c_writeto_args, args); - - pyb_i2c_check_init(&pyb_i2c_obj); - - // get the buffer to send from - mp_buffer_info_t bufinfo; - uint8_t data[1]; - pyb_buf_get_for_send(args[1].u_obj, &bufinfo, data); - - // send the data - if (!pyb_i2c_write(args[0].u_int, bufinfo.buf, bufinfo.len, args[2].u_bool)) { - mp_raise_OSError(MP_EIO); - } - - // return the number of bytes written - return mp_obj_new_int(bufinfo.len); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_writeto_obj, 1, pyb_i2c_writeto); - -STATIC mp_obj_t pyb_i2c_readfrom_mem(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t pyb_i2c_readfrom_mem_args[] = { - { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_memaddr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_nbytes, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_addrsize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, - }; - - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_readfrom_mem_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), pyb_i2c_readfrom_mem_args, args); - - vstr_t vstr; - pyb_i2c_readmem_into (args, &vstr); - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_readfrom_mem_obj, 1, pyb_i2c_readfrom_mem); - -STATIC const mp_arg_t pyb_i2c_readfrom_mem_into_args[] = { - { MP_QSTR_addr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_memaddr, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_buf, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_addrsize, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, -}; - -STATIC mp_obj_t pyb_i2c_readfrom_mem_into(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_readfrom_mem_into_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), pyb_i2c_readfrom_mem_into_args, args); - - // get the buffer to read into - vstr_t vstr; - pyb_i2c_readmem_into (args, &vstr); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_readfrom_mem_into_obj, 1, pyb_i2c_readfrom_mem_into); - -STATIC mp_obj_t pyb_i2c_writeto_mem(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_i2c_readfrom_mem_into_args)]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(pyb_i2c_readfrom_mem_into_args), pyb_i2c_readfrom_mem_into_args, args); - - pyb_i2c_check_init(&pyb_i2c_obj); - - // get the buffer to write from - mp_buffer_info_t bufinfo; - uint8_t data[1]; - pyb_buf_get_for_send(args[2].u_obj, &bufinfo, data); - - // get the addresses - mp_uint_t i2c_addr = args[0].u_int; - mp_uint_t mem_addr = args[1].u_int; - // determine the width of mem_addr (1 or 2 bytes) - mp_uint_t mem_addr_size = args[3].u_int >> 3; - - // write the register address to write to. - if (pyb_i2c_mem_write (i2c_addr, (byte *)&mem_addr, mem_addr_size, bufinfo.buf, bufinfo.len)) { - return mp_const_none; - } - - mp_raise_OSError(MP_EIO); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_i2c_writeto_mem_obj, 1, pyb_i2c_writeto_mem); - -STATIC const mp_rom_map_elem_t pyb_i2c_locals_dict_table[] = { - // instance methods - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_i2c_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_i2c_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&pyb_i2c_scan_obj) }, - { MP_ROM_QSTR(MP_QSTR_readfrom), MP_ROM_PTR(&pyb_i2c_readfrom_obj) }, - { MP_ROM_QSTR(MP_QSTR_readfrom_into), MP_ROM_PTR(&pyb_i2c_readfrom_into_obj) }, - { MP_ROM_QSTR(MP_QSTR_writeto), MP_ROM_PTR(&pyb_i2c_writeto_obj) }, - { MP_ROM_QSTR(MP_QSTR_readfrom_mem), MP_ROM_PTR(&pyb_i2c_readfrom_mem_obj) }, - { MP_ROM_QSTR(MP_QSTR_readfrom_mem_into), MP_ROM_PTR(&pyb_i2c_readfrom_mem_into_obj) }, - { MP_ROM_QSTR(MP_QSTR_writeto_mem), MP_ROM_PTR(&pyb_i2c_writeto_mem_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(pyb_i2c_locals_dict, pyb_i2c_locals_dict_table); - -const mp_obj_type_t pyb_i2c_type = { - { &mp_type_type }, - .name = MP_QSTR_I2C, - .print = pyb_i2c_print, - .make_new = pyb_i2c_make_new, - .locals_dict = (mp_obj_t)&pyb_i2c_locals_dict, -}; diff --git a/cc3200/mods/pybi2c.h b/cc3200/mods/pybi2c.h deleted file mode 100644 index dcc3f0468..000000000 --- a/cc3200/mods/pybi2c.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBI2C_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H - -extern const mp_obj_type_t pyb_i2c_type; - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBI2C_H diff --git a/cc3200/mods/pybpin.c b/cc3200/mods/pybpin.c deleted file mode 100644 index 2402332d5..000000000 --- a/cc3200/mods/pybpin.c +++ /dev/null @@ -1,965 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpconfig.h" -#include "py/obj.h" -#include "py/runtime.h" -#include "py/gc.h" -#include "py/mpstate.h" -#include "inc/hw_types.h" -#include "inc/hw_gpio.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "pin.h" -#include "prcm.h" -#include "gpio.h" -#include "interrupt.h" -#include "pybpin.h" -#include "mpirq.h" -#include "pins.h" -#include "pybsleep.h" -#include "mpexception.h" -#include "mperror.h" - - -/// \moduleref pyb -/// \class Pin - control I/O pins -/// -/****************************************************************************** -DECLARE PRIVATE FUNCTIONS -******************************************************************************/ -STATIC pin_obj_t *pin_find_named_pin(const mp_obj_dict_t *named_pins, mp_obj_t name); -STATIC pin_obj_t *pin_find_pin_by_port_bit (const mp_obj_dict_t *named_pins, uint port, uint bit); -STATIC int8_t pin_obj_find_af (const pin_obj_t* pin, uint8_t fn, uint8_t unit, uint8_t type); -STATIC void pin_free_af_from_pins (uint8_t fn, uint8_t unit, uint8_t type); -STATIC void pin_deassign (pin_obj_t* pin); -STATIC void pin_obj_configure (const pin_obj_t *self); -STATIC void pin_get_hibernate_pin_and_idx (const pin_obj_t *self, uint *wake_pin, uint *idx); -STATIC void pin_irq_enable (mp_obj_t self_in); -STATIC void pin_irq_disable (mp_obj_t self_in); -STATIC void pin_extint_register(pin_obj_t *self, uint32_t intmode, uint32_t priority); -STATIC void pin_validate_mode (uint mode); -STATIC void pin_validate_pull (uint pull); -STATIC void pin_validate_drive (uint strength); -STATIC void pin_validate_af(const pin_obj_t* pin, int8_t idx, uint8_t *fn, uint8_t *unit, uint8_t *type); -STATIC uint8_t pin_get_value(const pin_obj_t* self); -STATIC void GPIOA0IntHandler (void); -STATIC void GPIOA1IntHandler (void); -STATIC void GPIOA2IntHandler (void); -STATIC void GPIOA3IntHandler (void); -STATIC void EXTI_Handler(uint port); - -/****************************************************************************** -DEFINE CONSTANTS -******************************************************************************/ -#define PYBPIN_NUM_WAKE_PINS (6) -#define PYBPIN_WAKES_NOT (-1) - -#define GPIO_DIR_MODE_ALT 0x00000002 // Pin is NOT controlled by the PGIO module -#define GPIO_DIR_MODE_ALT_OD 0x00000003 // Pin is NOT controlled by the PGIO module and is in open drain mode - -#define PYB_PIN_FALLING_EDGE 0x01 -#define PYB_PIN_RISING_EDGE 0x02 -#define PYB_PIN_LOW_LEVEL 0x04 -#define PYB_PIN_HIGH_LEVEL 0x08 - -/****************************************************************************** -DEFINE TYPES -******************************************************************************/ -typedef struct { - bool active; - int8_t lpds; - int8_t hib; -} pybpin_wake_pin_t; - -/****************************************************************************** -DECLARE PRIVATE DATA -******************************************************************************/ -STATIC const mp_irq_methods_t pin_irq_methods; -STATIC pybpin_wake_pin_t pybpin_wake_pin[PYBPIN_NUM_WAKE_PINS] = - { {.active = false, .lpds = PYBPIN_WAKES_NOT, .hib = PYBPIN_WAKES_NOT}, - {.active = false, .lpds = PYBPIN_WAKES_NOT, .hib = PYBPIN_WAKES_NOT}, - {.active = false, .lpds = PYBPIN_WAKES_NOT, .hib = PYBPIN_WAKES_NOT}, - {.active = false, .lpds = PYBPIN_WAKES_NOT, .hib = PYBPIN_WAKES_NOT}, - {.active = false, .lpds = PYBPIN_WAKES_NOT, .hib = PYBPIN_WAKES_NOT}, - {.active = false, .lpds = PYBPIN_WAKES_NOT, .hib = PYBPIN_WAKES_NOT} } ; - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -void pin_init0(void) { -// this initalization also reconfigures the JTAG/SWD pins -#ifndef DEBUG - // assign all pins to the GPIO module so that peripherals can be connected to any - // pins without conflicts after a soft reset - mp_map_t *named_map = mp_obj_dict_get_map((mp_obj_t)&pin_board_pins_locals_dict); - for (uint i = 0; i < named_map->used - 1; i++) { - pin_obj_t * pin = (pin_obj_t *)named_map->table[i].value; - pin_deassign (pin); - } -#endif -} - -// C API used to convert a user-supplied pin name into an ordinal pin number. -pin_obj_t *pin_find(mp_obj_t user_obj) { - pin_obj_t *pin_obj; - - // if a pin was provided, use it - if (MP_OBJ_IS_TYPE(user_obj, &pin_type)) { - pin_obj = user_obj; - return pin_obj; - } - - // otherwise see if the pin name matches a cpu pin - pin_obj = pin_find_named_pin(&pin_board_pins_locals_dict, user_obj); - if (pin_obj) { - return pin_obj; - } - - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -void pin_config (pin_obj_t *self, int af, uint mode, uint pull, int value, uint strength) { - self->mode = mode, self->pull = pull, self->strength = strength; - // if af is -1, then we want to keep it as it is - if (af != -1) { - self->af = af; - } - - // if value is -1, then we want to keep it as it is - if (value != -1) { - self->value = value; - } - - // mark the pin as used - self->used = true; - pin_obj_configure ((const pin_obj_t *)self); - - // register it with the sleep module - pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)pin_obj_configure); -} - -void pin_assign_pins_af (mp_obj_t *pins, uint32_t n_pins, uint32_t pull, uint32_t fn, uint32_t unit) { - for (int i = 0; i < n_pins; i++) { - pin_free_af_from_pins(fn, unit, i); - if (pins[i] != mp_const_none) { - pin_obj_t *pin = pin_find(pins[i]); - pin_config (pin, pin_find_af_index(pin, fn, unit, i), 0, pull, -1, PIN_STRENGTH_2MA); - } - } -} - -uint8_t pin_find_peripheral_unit (const mp_obj_t pin, uint8_t fn, uint8_t type) { - pin_obj_t *pin_o = pin_find(pin); - for (int i = 0; i < pin_o->num_afs; i++) { - if (pin_o->af_list[i].fn == fn && pin_o->af_list[i].type == type) { - return pin_o->af_list[i].unit; - } - } - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -uint8_t pin_find_peripheral_type (const mp_obj_t pin, uint8_t fn, uint8_t unit) { - pin_obj_t *pin_o = pin_find(pin); - for (int i = 0; i < pin_o->num_afs; i++) { - if (pin_o->af_list[i].fn == fn && pin_o->af_list[i].unit == unit) { - return pin_o->af_list[i].type; - } - } - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -int8_t pin_find_af_index (const pin_obj_t* pin, uint8_t fn, uint8_t unit, uint8_t type) { - int8_t af = pin_obj_find_af(pin, fn, unit, type); - if (af < 0) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - return af; -} - -/****************************************************************************** -DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC pin_obj_t *pin_find_named_pin(const mp_obj_dict_t *named_pins, mp_obj_t name) { - mp_map_t *named_map = mp_obj_dict_get_map((mp_obj_t)named_pins); - mp_map_elem_t *named_elem = mp_map_lookup(named_map, name, MP_MAP_LOOKUP); - if (named_elem != NULL && named_elem->value != NULL) { - return named_elem->value; - } - return NULL; -} - -STATIC pin_obj_t *pin_find_pin_by_port_bit (const mp_obj_dict_t *named_pins, uint port, uint bit) { - mp_map_t *named_map = mp_obj_dict_get_map((mp_obj_t)named_pins); - for (uint i = 0; i < named_map->used; i++) { - if ((((pin_obj_t *)named_map->table[i].value)->port == port) && - (((pin_obj_t *)named_map->table[i].value)->bit == bit)) { - return named_map->table[i].value; - } - } - return NULL; -} - -STATIC int8_t pin_obj_find_af (const pin_obj_t* pin, uint8_t fn, uint8_t unit, uint8_t type) { - for (int i = 0; i < pin->num_afs; i++) { - if (pin->af_list[i].fn == fn && pin->af_list[i].unit == unit && pin->af_list[i].type == type) { - return pin->af_list[i].idx; - } - } - return -1; -} - -STATIC void pin_free_af_from_pins (uint8_t fn, uint8_t unit, uint8_t type) { - mp_map_t *named_map = mp_obj_dict_get_map((mp_obj_t)&pin_board_pins_locals_dict); - for (uint i = 0; i < named_map->used - 1; i++) { - pin_obj_t * pin = (pin_obj_t *)named_map->table[i].value; - // af is different than GPIO - if (pin->af > PIN_MODE_0) { - // check if the pin supports the target af - int af = pin_obj_find_af(pin, fn, unit, type); - if (af > 0 && af == pin->af) { - // the pin supports the target af, de-assign it - pin_deassign (pin); - } - } - } -} - -STATIC void pin_deassign (pin_obj_t* pin) { - pin_config (pin, PIN_MODE_0, GPIO_DIR_MODE_IN, PIN_TYPE_STD, -1, PIN_STRENGTH_4MA); - pin->used = false; -} - -STATIC void pin_obj_configure (const pin_obj_t *self) { - uint32_t type; - if (self->mode == PIN_TYPE_ANALOG) { - type = PIN_TYPE_ANALOG; - } else { - type = self->pull; - uint32_t direction = self->mode; - if (direction == PIN_TYPE_OD || direction == GPIO_DIR_MODE_ALT_OD) { - direction = GPIO_DIR_MODE_OUT; - type |= PIN_TYPE_OD; - } - if (self->mode != GPIO_DIR_MODE_ALT && self->mode != GPIO_DIR_MODE_ALT_OD) { - // enable the peripheral clock for the GPIO port of this pin - switch (self->port) { - case PORT_A0: - MAP_PRCMPeripheralClkEnable(PRCM_GPIOA0, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - break; - case PORT_A1: - MAP_PRCMPeripheralClkEnable(PRCM_GPIOA1, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - break; - case PORT_A2: - MAP_PRCMPeripheralClkEnable(PRCM_GPIOA2, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - break; - case PORT_A3: - MAP_PRCMPeripheralClkEnable(PRCM_GPIOA3, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - break; - default: - break; - } - // configure the direction - MAP_GPIODirModeSet(self->port, self->bit, direction); - // set the pin value - if (self->value) { - MAP_GPIOPinWrite(self->port, self->bit, self->bit); - } else { - MAP_GPIOPinWrite(self->port, self->bit, 0); - } - } - // now set the alternate function - MAP_PinModeSet (self->pin_num, self->af); - } - MAP_PinConfigSet(self->pin_num, self->strength, type); -} - -STATIC void pin_get_hibernate_pin_and_idx (const pin_obj_t *self, uint *hib_pin, uint *idx) { - // pin_num is actually : (package_pin - 1) - switch (self->pin_num) { - case 56: // GP2 - *hib_pin = PRCM_HIB_GPIO2; - *idx = 0; - break; - case 58: // GP4 - *hib_pin = PRCM_HIB_GPIO4; - *idx = 1; - break; - case 3: // GP13 - *hib_pin = PRCM_HIB_GPIO13; - *idx = 2; - break; - case 7: // GP17 - *hib_pin = PRCM_HIB_GPIO17; - *idx = 3; - break; - case 1: // GP11 - *hib_pin = PRCM_HIB_GPIO11; - *idx = 4; - break; - case 16: // GP24 - *hib_pin = PRCM_HIB_GPIO24; - *idx = 5; - break; - default: - *idx = 0xFF; - break; - } -} - -STATIC void pin_irq_enable (mp_obj_t self_in) { - const pin_obj_t *self = self_in; - uint hib_pin, idx; - - pin_get_hibernate_pin_and_idx (self, &hib_pin, &idx); - if (idx < PYBPIN_NUM_WAKE_PINS) { - if (pybpin_wake_pin[idx].lpds != PYBPIN_WAKES_NOT) { - // enable GPIO as a wake source during LPDS - MAP_PRCMLPDSWakeUpGPIOSelect(idx, pybpin_wake_pin[idx].lpds); - MAP_PRCMLPDSWakeupSourceEnable(PRCM_LPDS_GPIO); - } - - if (pybpin_wake_pin[idx].hib != PYBPIN_WAKES_NOT) { - // enable GPIO as a wake source during hibernate - MAP_PRCMHibernateWakeUpGPIOSelect(hib_pin, pybpin_wake_pin[idx].hib); - MAP_PRCMHibernateWakeupSourceEnable(hib_pin); - } - else { - MAP_PRCMHibernateWakeupSourceDisable(hib_pin); - } - } - // if idx is invalid, the pin supports active interrupts for sure - if (idx >= PYBPIN_NUM_WAKE_PINS || pybpin_wake_pin[idx].active) { - MAP_GPIOIntClear(self->port, self->bit); - MAP_GPIOIntEnable(self->port, self->bit); - } - // in case it was enabled before - else if (idx < PYBPIN_NUM_WAKE_PINS && !pybpin_wake_pin[idx].active) { - MAP_GPIOIntDisable(self->port, self->bit); - } -} - -STATIC void pin_irq_disable (mp_obj_t self_in) { - const pin_obj_t *self = self_in; - uint hib_pin, idx; - - pin_get_hibernate_pin_and_idx (self, &hib_pin, &idx); - if (idx < PYBPIN_NUM_WAKE_PINS) { - if (pybpin_wake_pin[idx].lpds != PYBPIN_WAKES_NOT) { - // disable GPIO as a wake source during LPDS - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_GPIO); - } - if (pybpin_wake_pin[idx].hib != PYBPIN_WAKES_NOT) { - // disable GPIO as a wake source during hibernate - MAP_PRCMHibernateWakeupSourceDisable(hib_pin); - } - } - // not need to check for the active flag, it's safe to disable it anyway - MAP_GPIOIntDisable(self->port, self->bit); -} - -STATIC int pin_irq_flags (mp_obj_t self_in) { - const pin_obj_t *self = self_in; - return self->irq_flags; -} - -STATIC void pin_extint_register(pin_obj_t *self, uint32_t intmode, uint32_t priority) { - void *handler; - uint32_t intnum; - - // configure the interrupt type - MAP_GPIOIntTypeSet(self->port, self->bit, intmode); - switch (self->port) { - case GPIOA0_BASE: - handler = GPIOA0IntHandler; - intnum = INT_GPIOA0; - break; - case GPIOA1_BASE: - handler = GPIOA1IntHandler; - intnum = INT_GPIOA1; - break; - case GPIOA2_BASE: - handler = GPIOA2IntHandler; - intnum = INT_GPIOA2; - break; - case GPIOA3_BASE: - default: - handler = GPIOA3IntHandler; - intnum = INT_GPIOA3; - break; - } - MAP_GPIOIntRegister(self->port, handler); - // set the interrupt to the lowest priority, to make sure that - // no other ISRs will be preemted by this one - MAP_IntPrioritySet(intnum, priority); -} - -STATIC void pin_validate_mode (uint mode) { - if (mode != GPIO_DIR_MODE_IN && mode != GPIO_DIR_MODE_OUT && mode != PIN_TYPE_OD && - mode != GPIO_DIR_MODE_ALT && mode != GPIO_DIR_MODE_ALT_OD) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} -STATIC void pin_validate_pull (uint pull) { - if (pull != PIN_TYPE_STD && pull != PIN_TYPE_STD_PU && pull != PIN_TYPE_STD_PD) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} - -STATIC void pin_validate_drive(uint strength) { - if (strength != PIN_STRENGTH_2MA && strength != PIN_STRENGTH_4MA && strength != PIN_STRENGTH_6MA) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } -} - -STATIC void pin_validate_af(const pin_obj_t* pin, int8_t idx, uint8_t *fn, uint8_t *unit, uint8_t *type) { - for (int i = 0; i < pin->num_afs; i++) { - if (pin->af_list[i].idx == idx) { - *fn = pin->af_list[i].fn; - *unit = pin->af_list[i].unit; - *type = pin->af_list[i].type; - return; - } - } - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -STATIC uint8_t pin_get_value (const pin_obj_t* self) { - uint32_t value; - bool setdir = false; - if (self->mode == PIN_TYPE_OD || self->mode == GPIO_DIR_MODE_ALT_OD) { - setdir = true; - // configure the direction to IN for a moment in order to read the pin value - MAP_GPIODirModeSet(self->port, self->bit, GPIO_DIR_MODE_IN); - } - // now get the value - value = MAP_GPIOPinRead(self->port, self->bit); - if (setdir) { - // set the direction back to output - MAP_GPIODirModeSet(self->port, self->bit, GPIO_DIR_MODE_OUT); - if (self->value) { - MAP_GPIOPinWrite(self->port, self->bit, self->bit); - } else { - MAP_GPIOPinWrite(self->port, self->bit, 0); - } - } - // return it - return value ? 1 : 0; -} - -STATIC void GPIOA0IntHandler (void) { - EXTI_Handler(GPIOA0_BASE); -} - -STATIC void GPIOA1IntHandler (void) { - EXTI_Handler(GPIOA1_BASE); -} - -STATIC void GPIOA2IntHandler (void) { - EXTI_Handler(GPIOA2_BASE); -} - -STATIC void GPIOA3IntHandler (void) { - EXTI_Handler(GPIOA3_BASE); -} - -// common interrupt handler -STATIC void EXTI_Handler(uint port) { - uint32_t bits = MAP_GPIOIntStatus(port, true); - MAP_GPIOIntClear(port, bits); - - // might be that we have more than one pin interrupt pending - // therefore we must loop through all of the 8 possible bits - for (int i = 0; i < 8; i++) { - uint32_t bit = (1 << i); - if (bit & bits) { - pin_obj_t *self = (pin_obj_t *)pin_find_pin_by_port_bit(&pin_board_pins_locals_dict, port, bit); - if (self->irq_trigger == (PYB_PIN_FALLING_EDGE | PYB_PIN_RISING_EDGE)) { - // read the pin value (hoping that the pin level has remained stable) - self->irq_flags = MAP_GPIOPinRead(self->port, self->bit) ? PYB_PIN_RISING_EDGE : PYB_PIN_FALLING_EDGE; - } else { - // same as the triggers - self->irq_flags = self->irq_trigger; - } - mp_irq_handler(mp_irq_find(self)); - // always clear the flags after leaving the user handler - self->irq_flags = 0; - } - } -} - - -/******************************************************************************/ -// MicroPython bindings - -STATIC const mp_arg_t pin_init_args[] = { - { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_pull, MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_drive, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = PIN_STRENGTH_4MA} }, - { MP_QSTR_alt, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = -1} }, -}; -#define pin_INIT_NUM_ARGS MP_ARRAY_SIZE(pin_init_args) - -STATIC mp_obj_t pin_obj_init_helper(pin_obj_t *self, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[pin_INIT_NUM_ARGS]; - mp_arg_parse_all(n_args, pos_args, kw_args, pin_INIT_NUM_ARGS, pin_init_args, args); - - // get the io mode - uint mode; - // default is input - if (args[0].u_obj == MP_OBJ_NULL) { - mode = GPIO_DIR_MODE_IN; - } else { - mode = mp_obj_get_int(args[0].u_obj); - pin_validate_mode (mode); - } - - // get the pull type - uint pull; - if (args[1].u_obj == mp_const_none) { - pull = PIN_TYPE_STD; - } else { - pull = mp_obj_get_int(args[1].u_obj); - pin_validate_pull (pull); - } - - // get the value - int value = -1; - if (args[2].u_obj != MP_OBJ_NULL) { - if (mp_obj_is_true(args[2].u_obj)) { - value = 1; - } else { - value = 0; - } - } - - // get the strenght - uint strength = args[3].u_int; - pin_validate_drive(strength); - - // get the alternate function - int af = args[4].u_int; - if (mode != GPIO_DIR_MODE_ALT && mode != GPIO_DIR_MODE_ALT_OD) { - if (af == -1) { - af = 0; - } else { - goto invalid_args; - } - } else if (af < -1 || af > 15) { - goto invalid_args; - } - - // check for a valid af and then free it from any other pins - if (af > PIN_MODE_0) { - uint8_t fn, unit, type; - pin_validate_af (self, af, &fn, &unit, &type); - pin_free_af_from_pins(fn, unit, type); - } - pin_config (self, af, mode, pull, value, strength); - - return mp_const_none; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -STATIC void pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pin_obj_t *self = self_in; - uint32_t pull = self->pull; - uint32_t drive = self->strength; - - // pin name - mp_printf(print, "Pin('%q'", self->name); - - // pin mode - qstr mode_qst; - uint32_t mode = self->mode; - if (mode == GPIO_DIR_MODE_IN) { - mode_qst = MP_QSTR_IN; - } else if (mode == GPIO_DIR_MODE_OUT) { - mode_qst = MP_QSTR_OUT; - } else if (mode == GPIO_DIR_MODE_ALT) { - mode_qst = MP_QSTR_ALT; - } else if (mode == GPIO_DIR_MODE_ALT_OD) { - mode_qst = MP_QSTR_ALT_OPEN_DRAIN; - } else { - mode_qst = MP_QSTR_OPEN_DRAIN; - } - mp_printf(print, ", mode=Pin.%q", mode_qst); - - // pin pull - qstr pull_qst; - if (pull == PIN_TYPE_STD) { - mp_printf(print, ", pull=%q", MP_QSTR_None); - } else { - if (pull == PIN_TYPE_STD_PU) { - pull_qst = MP_QSTR_PULL_UP; - } else { - pull_qst = MP_QSTR_PULL_DOWN; - } - mp_printf(print, ", pull=Pin.%q", pull_qst); - } - - // pin drive - qstr drv_qst; - if (drive == PIN_STRENGTH_2MA) { - drv_qst = MP_QSTR_LOW_POWER; - } else if (drive == PIN_STRENGTH_4MA) { - drv_qst = MP_QSTR_MED_POWER; - } else { - drv_qst = MP_QSTR_HIGH_POWER; - } - mp_printf(print, ", drive=Pin.%q", drv_qst); - - // pin af - int alt = (self->af == 0) ? -1 : self->af; - mp_printf(print, ", alt=%d)", alt); -} - -STATIC mp_obj_t 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. - pin_obj_t *pin = (pin_obj_t *)pin_find(args[0]); - - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); - pin_obj_init_helper(pin, n_args - 1, args + 1, &kw_args); - - return (mp_obj_t)pin; -} - -STATIC mp_obj_t pin_obj_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - return pin_obj_init_helper(args[0], n_args - 1, args + 1, kw_args); -} -MP_DEFINE_CONST_FUN_OBJ_KW(pin_init_obj, 1, pin_obj_init); - -STATIC mp_obj_t pin_value(size_t n_args, const mp_obj_t *args) { - pin_obj_t *self = args[0]; - if (n_args == 1) { - // get the value - return MP_OBJ_NEW_SMALL_INT(pin_get_value(self)); - } else { - // set the pin value - if (mp_obj_is_true(args[1])) { - self->value = 1; - MAP_GPIOPinWrite(self->port, self->bit, self->bit); - } else { - self->value = 0; - MAP_GPIOPinWrite(self->port, self->bit, 0); - } - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_value_obj, 1, 2, pin_value); - -STATIC mp_obj_t pin_id(mp_obj_t self_in) { - pin_obj_t *self = self_in; - return MP_OBJ_NEW_QSTR(self->name); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_id_obj, pin_id); - -STATIC mp_obj_t pin_mode(size_t n_args, const mp_obj_t *args) { - pin_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_int(self->mode); - } else { - uint32_t mode = mp_obj_get_int(args[1]); - pin_validate_mode (mode); - self->mode = mode; - pin_obj_configure(self); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_mode_obj, 1, 2, pin_mode); - -STATIC mp_obj_t pin_pull(size_t n_args, const mp_obj_t *args) { - pin_obj_t *self = args[0]; - if (n_args == 1) { - if (self->pull == PIN_TYPE_STD) { - return mp_const_none; - } - return mp_obj_new_int(self->pull); - } else { - uint32_t pull; - if (args[1] == mp_const_none) { - pull = PIN_TYPE_STD; - } else { - pull = mp_obj_get_int(args[1]); - pin_validate_pull (pull); - } - self->pull = pull; - pin_obj_configure(self); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_pull_obj, 1, 2, pin_pull); - -STATIC mp_obj_t pin_drive(size_t n_args, const mp_obj_t *args) { - pin_obj_t *self = args[0]; - if (n_args == 1) { - return mp_obj_new_int(self->strength); - } else { - uint32_t strength = mp_obj_get_int(args[1]); - pin_validate_drive (strength); - self->strength = strength; - pin_obj_configure(self); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pin_drive_obj, 1, 2, pin_drive); - -STATIC mp_obj_t 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); - mp_obj_t _args[2] = {self_in, *args}; - return pin_value (n_args + 1, _args); -} - -STATIC mp_obj_t pin_alt_list(mp_obj_t self_in) { - pin_obj_t *self = self_in; - mp_obj_t af[2]; - mp_obj_t afs = mp_obj_new_list(0, NULL); - - for (int i = 0; i < self->num_afs; i++) { - af[0] = MP_OBJ_NEW_QSTR(self->af_list[i].name); - af[1] = mp_obj_new_int(self->af_list[i].idx); - mp_obj_list_append(afs, mp_obj_new_tuple(MP_ARRAY_SIZE(af), af)); - } - return afs; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pin_alt_list_obj, pin_alt_list); - -/// \method irq(trigger, priority, handler, wake) -STATIC mp_obj_t pin_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[mp_irq_INIT_NUM_ARGS]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, mp_irq_INIT_NUM_ARGS, mp_irq_init_args, args); - pin_obj_t *self = pos_args[0]; - - // convert the priority to the correct value - uint priority = mp_irq_translate_priority (args[1].u_int); - - // verify and translate the interrupt mode - uint mp_trigger = mp_obj_get_int(args[0].u_obj); - uint trigger; - if (mp_trigger == (PYB_PIN_FALLING_EDGE | PYB_PIN_RISING_EDGE)) { - trigger = GPIO_BOTH_EDGES; - } else { - switch (mp_trigger) { - case PYB_PIN_FALLING_EDGE: - trigger = GPIO_FALLING_EDGE; - break; - case PYB_PIN_RISING_EDGE: - trigger = GPIO_RISING_EDGE; - break; - case PYB_PIN_LOW_LEVEL: - trigger = GPIO_LOW_LEVEL; - break; - case PYB_PIN_HIGH_LEVEL: - trigger = GPIO_HIGH_LEVEL; - break; - default: - goto invalid_args; - } - } - - uint8_t pwrmode = (args[3].u_obj == mp_const_none) ? PYB_PWR_MODE_ACTIVE : mp_obj_get_int(args[3].u_obj); - if (pwrmode > (PYB_PWR_MODE_ACTIVE | PYB_PWR_MODE_LPDS | PYB_PWR_MODE_HIBERNATE)) { - goto invalid_args; - } - - // get the wake info from this pin - uint hib_pin, idx; - pin_get_hibernate_pin_and_idx ((const pin_obj_t *)self, &hib_pin, &idx); - if (pwrmode & PYB_PWR_MODE_LPDS) { - if (idx >= PYBPIN_NUM_WAKE_PINS) { - goto invalid_args; - } - // wake modes are different in LDPS - uint wake_mode; - switch (trigger) { - case GPIO_FALLING_EDGE: - wake_mode = PRCM_LPDS_FALL_EDGE; - break; - case GPIO_RISING_EDGE: - wake_mode = PRCM_LPDS_RISE_EDGE; - break; - case GPIO_LOW_LEVEL: - wake_mode = PRCM_LPDS_LOW_LEVEL; - break; - case GPIO_HIGH_LEVEL: - wake_mode = PRCM_LPDS_HIGH_LEVEL; - break; - default: - goto invalid_args; - break; - } - - // first clear the lpds value from all wake-able pins - for (uint i = 0; i < PYBPIN_NUM_WAKE_PINS; i++) { - pybpin_wake_pin[i].lpds = PYBPIN_WAKES_NOT; - } - - // enable this pin as a wake-up source during LPDS - pybpin_wake_pin[idx].lpds = wake_mode; - } else if (idx < PYBPIN_NUM_WAKE_PINS) { - // this pin was the previous LPDS wake source, so disable it completely - if (pybpin_wake_pin[idx].lpds != PYBPIN_WAKES_NOT) { - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_GPIO); - } - pybpin_wake_pin[idx].lpds = PYBPIN_WAKES_NOT; - } - - if (pwrmode & PYB_PWR_MODE_HIBERNATE) { - if (idx >= PYBPIN_NUM_WAKE_PINS) { - goto invalid_args; - } - // wake modes are different in hibernate - uint wake_mode; - switch (trigger) { - case GPIO_FALLING_EDGE: - wake_mode = PRCM_HIB_FALL_EDGE; - break; - case GPIO_RISING_EDGE: - wake_mode = PRCM_HIB_RISE_EDGE; - break; - case GPIO_LOW_LEVEL: - wake_mode = PRCM_HIB_LOW_LEVEL; - break; - case GPIO_HIGH_LEVEL: - wake_mode = PRCM_HIB_HIGH_LEVEL; - break; - default: - goto invalid_args; - break; - } - - // enable this pin as wake-up source during hibernate - pybpin_wake_pin[idx].hib = wake_mode; - } else if (idx < PYBPIN_NUM_WAKE_PINS) { - pybpin_wake_pin[idx].hib = PYBPIN_WAKES_NOT; - } - - // we need to update the callback atomically, so we disable the - // interrupt before we update anything. - pin_irq_disable(self); - if (pwrmode & PYB_PWR_MODE_ACTIVE) { - // register the interrupt - pin_extint_register((pin_obj_t *)self, trigger, priority); - if (idx < PYBPIN_NUM_WAKE_PINS) { - pybpin_wake_pin[idx].active = true; - } - } else if (idx < PYBPIN_NUM_WAKE_PINS) { - pybpin_wake_pin[idx].active = false; - } - - // all checks have passed, we can create the irq object - mp_obj_t _irq = mp_irq_new (self, args[2].u_obj, &pin_irq_methods); - if (pwrmode & PYB_PWR_MODE_LPDS) { - pyb_sleep_set_gpio_lpds_callback (_irq); - } - - // save the mp_trigge for later - self->irq_trigger = mp_trigger; - - // enable the interrupt just before leaving - pin_irq_enable(self); - - return _irq; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pin_irq_obj, 1, pin_irq); - -STATIC const mp_rom_map_elem_t pin_locals_dict_table[] = { - // instance methods - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pin_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&pin_value_obj) }, - { MP_ROM_QSTR(MP_QSTR_id), MP_ROM_PTR(&pin_id_obj) }, - { MP_ROM_QSTR(MP_QSTR_mode), MP_ROM_PTR(&pin_mode_obj) }, - { MP_ROM_QSTR(MP_QSTR_pull), MP_ROM_PTR(&pin_pull_obj) }, - { MP_ROM_QSTR(MP_QSTR_drive), MP_ROM_PTR(&pin_drive_obj) }, - { MP_ROM_QSTR(MP_QSTR_alt_list), MP_ROM_PTR(&pin_alt_list_obj) }, - { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pin_irq_obj) }, - - // class attributes - { MP_ROM_QSTR(MP_QSTR_board), MP_ROM_PTR(&pin_board_pins_obj_type) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_IN), MP_ROM_INT(GPIO_DIR_MODE_IN) }, - { MP_ROM_QSTR(MP_QSTR_OUT), MP_ROM_INT(GPIO_DIR_MODE_OUT) }, - { MP_ROM_QSTR(MP_QSTR_OPEN_DRAIN), MP_ROM_INT(PIN_TYPE_OD) }, - { MP_ROM_QSTR(MP_QSTR_ALT), MP_ROM_INT(GPIO_DIR_MODE_ALT) }, - { MP_ROM_QSTR(MP_QSTR_ALT_OPEN_DRAIN), MP_ROM_INT(GPIO_DIR_MODE_ALT_OD) }, - { MP_ROM_QSTR(MP_QSTR_PULL_UP), MP_ROM_INT(PIN_TYPE_STD_PU) }, - { MP_ROM_QSTR(MP_QSTR_PULL_DOWN), MP_ROM_INT(PIN_TYPE_STD_PD) }, - { MP_ROM_QSTR(MP_QSTR_LOW_POWER), MP_ROM_INT(PIN_STRENGTH_2MA) }, - { MP_ROM_QSTR(MP_QSTR_MED_POWER), MP_ROM_INT(PIN_STRENGTH_4MA) }, - { MP_ROM_QSTR(MP_QSTR_HIGH_POWER), MP_ROM_INT(PIN_STRENGTH_6MA) }, - { MP_ROM_QSTR(MP_QSTR_IRQ_FALLING), MP_ROM_INT(PYB_PIN_FALLING_EDGE) }, - { MP_ROM_QSTR(MP_QSTR_IRQ_RISING), MP_ROM_INT(PYB_PIN_RISING_EDGE) }, - { MP_ROM_QSTR(MP_QSTR_IRQ_LOW_LEVEL), MP_ROM_INT(PYB_PIN_LOW_LEVEL) }, - { MP_ROM_QSTR(MP_QSTR_IRQ_HIGH_LEVEL), MP_ROM_INT(PYB_PIN_HIGH_LEVEL) }, -}; - -STATIC MP_DEFINE_CONST_DICT(pin_locals_dict, pin_locals_dict_table); - -const mp_obj_type_t pin_type = { - { &mp_type_type }, - .name = MP_QSTR_Pin, - .print = pin_print, - .make_new = pin_make_new, - .call = pin_call, - .locals_dict = (mp_obj_t)&pin_locals_dict, -}; - -STATIC const mp_irq_methods_t pin_irq_methods = { - .init = pin_irq, - .enable = pin_irq_enable, - .disable = pin_irq_disable, - .flags = pin_irq_flags, -}; - -STATIC void pin_named_pins_obj_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pin_named_pins_obj_t *self = self_in; - mp_printf(print, "<Pin.%q>", self->name); -} - -const mp_obj_type_t pin_board_pins_obj_type = { - { &mp_type_type }, - .name = MP_QSTR_board, - .print = pin_named_pins_obj_print, - .locals_dict = (mp_obj_t)&pin_board_pins_locals_dict, -}; - diff --git a/cc3200/mods/pybpin.h b/cc3200/mods/pybpin.h deleted file mode 100644 index 74f0af2b3..000000000 --- a/cc3200/mods/pybpin.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBPIN_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H - -enum { - PORT_A0 = GPIOA0_BASE, - PORT_A1 = GPIOA1_BASE, - PORT_A2 = GPIOA2_BASE, - PORT_A3 = GPIOA3_BASE, -}; - -enum { - PIN_FN_UART = 0, - PIN_FN_SPI, - PIN_FN_I2S, - PIN_FN_I2C, - PIN_FN_TIM, - PIN_FN_SD, - PIN_FN_ADC, -}; - -enum { - PIN_TYPE_UART_TX = 0, - PIN_TYPE_UART_RX, - PIN_TYPE_UART_RTS, - PIN_TYPE_UART_CTS, -}; - -enum { - PIN_TYPE_SPI_CLK = 0, - PIN_TYPE_SPI_MOSI, - PIN_TYPE_SPI_MISO, - PIN_TYPE_SPI_CS0, -}; - -enum { - PIN_TYPE_I2S_CLK = 0, - PIN_TYPE_I2S_FS, - PIN_TYPE_I2S_DAT0, - PIN_TYPE_I2S_DAT1, -}; - -enum { - PIN_TYPE_I2C_SDA = 0, - PIN_TYPE_I2C_SCL, -}; - -enum { - PIN_TYPE_TIM_PWM = 0, -}; - -enum { - PIN_TYPE_SD_CLK = 0, - PIN_TYPE_SD_CMD, - PIN_TYPE_SD_DAT0, -}; - -enum { - PIN_TYPE_ADC_CH0 = 0, - PIN_TYPE_ADC_CH1, - PIN_TYPE_ADC_CH2, - PIN_TYPE_ADC_CH3, -}; - -typedef struct { - qstr name; - int8_t idx; - uint8_t fn; - uint8_t unit; - uint8_t type; -} pin_af_t; - -typedef struct { - const mp_obj_base_t base; - const qstr name; - const uint32_t port; - const pin_af_t *af_list; - uint16_t pull; - const uint8_t bit; - const uint8_t pin_num; - int8_t af; - uint8_t strength; - uint8_t mode; // this is now a combination of type and mode - const uint8_t num_afs; // 255 AFs - uint8_t value; - uint8_t used; - uint8_t irq_trigger; - uint8_t irq_flags; -} pin_obj_t; - -extern const mp_obj_type_t pin_type; - -typedef struct { - const char *name; - const pin_obj_t *pin; -} pin_named_pin_t; - -typedef struct { - mp_obj_base_t base; - qstr name; - const pin_named_pin_t *named_pins; -} pin_named_pins_obj_t; - -extern const mp_obj_type_t pin_board_pins_obj_type; -extern const mp_obj_dict_t pin_board_pins_locals_dict; - -void pin_init0(void); -void pin_config(pin_obj_t *self, int af, uint mode, uint type, int value, uint strength); -pin_obj_t *pin_find(mp_obj_t user_obj); -void pin_assign_pins_af (mp_obj_t *pins, uint32_t n_pins, uint32_t pull, uint32_t fn, uint32_t unit); -uint8_t pin_find_peripheral_unit (const mp_obj_t pin, uint8_t fn, uint8_t type); -uint8_t pin_find_peripheral_type (const mp_obj_t pin, uint8_t fn, uint8_t unit); -int8_t pin_find_af_index (const pin_obj_t* pin, uint8_t fn, uint8_t unit, uint8_t type);; - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBPIN_H diff --git a/cc3200/mods/pybrtc.c b/cc3200/mods/pybrtc.c deleted file mode 100644 index e7b9cf258..000000000 --- a/cc3200/mods/pybrtc.c +++ /dev/null @@ -1,485 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/obj.h" -#include "py/runtime.h" -#include "py/mperrno.h" -#include "lib/timeutils/timeutils.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "prcm.h" -#include "pybrtc.h" -#include "mpirq.h" -#include "pybsleep.h" -#include "simplelink.h" -#include "modnetwork.h" -#include "modwlan.h" -#include "mpexception.h" - -/// \moduleref pyb -/// \class RTC - real time clock - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC const mp_irq_methods_t pyb_rtc_irq_methods; -STATIC pyb_rtc_obj_t pyb_rtc_obj; - -/****************************************************************************** - FUNCTION-LIKE MACROS - ******************************************************************************/ -#define RTC_U16MS_CYCLES(msec) ((msec * 1024) / 1000) -#define RTC_CYCLES_U16MS(cycles) ((cycles * 1000) / 1024) - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void pyb_rtc_set_time (uint32_t secs, uint16_t msecs); -STATIC uint32_t pyb_rtc_reset (void); -STATIC void pyb_rtc_disable_interupt (void); -STATIC void pyb_rtc_irq_enable (mp_obj_t self_in); -STATIC void pyb_rtc_irq_disable (mp_obj_t self_in); -STATIC int pyb_rtc_irq_flags (mp_obj_t self_in); -STATIC uint pyb_rtc_datetime_s_us(const mp_obj_t datetime, uint32_t *seconds); -STATIC mp_obj_t pyb_rtc_datetime(mp_obj_t self, const mp_obj_t datetime); -STATIC void pyb_rtc_set_alarm (pyb_rtc_obj_t *self, uint32_t seconds, uint16_t mseconds); -STATIC void rtc_msec_add(uint16_t msecs_1, uint32_t *secs, uint16_t *msecs_2); - -/****************************************************************************** - DECLARE PUBLIC FUNCTIONS - ******************************************************************************/ -__attribute__ ((section (".boot"))) -void pyb_rtc_pre_init(void) { - // only if comming out of a power-on reset - if (MAP_PRCMSysResetCauseGet() == PRCM_POWER_ON) { - // Mark the RTC in use first - MAP_PRCMRTCInUseSet(); - // reset the time and date - pyb_rtc_reset(); - } -} - -void pyb_rtc_get_time (uint32_t *secs, uint16_t *msecs) { - uint16_t cycles; - MAP_PRCMRTCGet (secs, &cycles); - *msecs = RTC_CYCLES_U16MS(cycles); -} - -uint32_t pyb_rtc_get_seconds (void) { - uint32_t seconds; - uint16_t mseconds; - pyb_rtc_get_time(&seconds, &mseconds); - return seconds; -} - -void pyb_rtc_calc_future_time (uint32_t a_mseconds, uint32_t *f_seconds, uint16_t *f_mseconds) { - uint32_t c_seconds; - uint16_t c_mseconds; - // get the current time - pyb_rtc_get_time(&c_seconds, &c_mseconds); - // calculate the future seconds - *f_seconds = c_seconds + (a_mseconds / 1000); - // calculate the "remaining" future mseconds - *f_mseconds = a_mseconds % 1000; - // add the current milliseconds - rtc_msec_add (c_mseconds, f_seconds, f_mseconds); -} - -void pyb_rtc_repeat_alarm (pyb_rtc_obj_t *self) { - if (self->repeat) { - uint32_t f_seconds, c_seconds; - uint16_t f_mseconds, c_mseconds; - - pyb_rtc_get_time(&c_seconds, &c_mseconds); - - // substract the time elapsed between waking up and setting up the alarm again - int32_t wake_ms = ((c_seconds * 1000) + c_mseconds) - ((self->alarm_time_s * 1000) + self->alarm_time_ms); - int32_t next_alarm = self->alarm_ms - wake_ms; - next_alarm = next_alarm > 0 ? next_alarm : PYB_RTC_MIN_ALARM_TIME_MS; - pyb_rtc_calc_future_time (next_alarm, &f_seconds, &f_mseconds); - - // now configure the alarm - pyb_rtc_set_alarm (self, f_seconds, f_mseconds); - } -} - -void pyb_rtc_disable_alarm (void) { - pyb_rtc_obj.alarmset = false; - pyb_rtc_disable_interupt(); -} - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void pyb_rtc_set_time (uint32_t secs, uint16_t msecs) { - // add the RTC access time - rtc_msec_add(RTC_ACCESS_TIME_MSEC, &secs, &msecs); - // convert from mseconds to cycles - msecs = RTC_U16MS_CYCLES(msecs); - // now set the time - MAP_PRCMRTCSet(secs, msecs); -} - -STATIC uint32_t pyb_rtc_reset (void) { - // fresh reset; configure the RTC Calendar - // set the date to 1st Jan 2015 - // set the time to 00:00:00 - uint32_t seconds = timeutils_seconds_since_2000(2015, 1, 1, 0, 0, 0); - // disable any running alarm - pyb_rtc_disable_alarm(); - // Now set the RTC calendar time - pyb_rtc_set_time(seconds, 0); - return seconds; -} - -STATIC void pyb_rtc_disable_interupt (void) { - uint primsk = disable_irq(); - MAP_PRCMIntDisable(PRCM_INT_SLOW_CLK_CTR); - (void)MAP_PRCMIntStatus(); - enable_irq(primsk); -} - -STATIC void pyb_rtc_irq_enable (mp_obj_t self_in) { - pyb_rtc_obj_t *self = self_in; - // we always need interrupts if repeat is enabled - if ((self->pwrmode & PYB_PWR_MODE_ACTIVE) || self->repeat) { - MAP_PRCMIntEnable(PRCM_INT_SLOW_CLK_CTR); - } else { // just in case it was already enabled before - MAP_PRCMIntDisable(PRCM_INT_SLOW_CLK_CTR); - } - self->irq_enabled = true; -} - -STATIC void pyb_rtc_irq_disable (mp_obj_t self_in) { - pyb_rtc_obj_t *self = self_in; - self->irq_enabled = false; - if (!self->repeat) { // we always need interrupts if repeat is enabled - pyb_rtc_disable_interupt(); - } -} - -STATIC int pyb_rtc_irq_flags (mp_obj_t self_in) { - pyb_rtc_obj_t *self = self_in; - return self->irq_flags; -} - -STATIC uint pyb_rtc_datetime_s_us(const mp_obj_t datetime, uint32_t *seconds) { - timeutils_struct_time_t tm; - uint32_t useconds; - - // set date and time - mp_obj_t *items; - size_t len; - mp_obj_get_array(datetime, &len, &items); - - // verify the tuple - if (len < 3 || len > 8) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - - tm.tm_year = mp_obj_get_int(items[0]); - tm.tm_mon = mp_obj_get_int(items[1]); - tm.tm_mday = mp_obj_get_int(items[2]); - if (len < 7) { - useconds = 0; - } else { - useconds = mp_obj_get_int(items[6]); - } - if (len < 6) { - tm.tm_sec = 0; - } else { - tm.tm_sec = mp_obj_get_int(items[5]); - } - if (len < 5) { - tm.tm_min = 0; - } else { - tm.tm_min = mp_obj_get_int(items[4]); - } - if (len < 4) { - tm.tm_hour = 0; - } else { - tm.tm_hour = mp_obj_get_int(items[3]); - } - *seconds = timeutils_seconds_since_2000(tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); - return useconds; -} - -/// The 8-tuple has the same format as CPython's datetime object: -/// -/// (year, month, day, hours, minutes, seconds, milliseconds, tzinfo=None) -/// -STATIC mp_obj_t pyb_rtc_datetime(mp_obj_t self_in, const mp_obj_t datetime) { - uint32_t seconds; - uint32_t useconds; - - if (datetime != MP_OBJ_NULL) { - useconds = pyb_rtc_datetime_s_us(datetime, &seconds); - pyb_rtc_set_time (seconds, useconds / 1000); - } else { - seconds = pyb_rtc_reset(); - } - - // set WLAN time and date, this is needed to verify certificates - wlan_set_current_time(seconds); - return mp_const_none; -} - -STATIC void pyb_rtc_set_alarm (pyb_rtc_obj_t *self, uint32_t seconds, uint16_t mseconds) { - // disable the interrupt before updating anything - if (self->irq_enabled) { - MAP_PRCMIntDisable(PRCM_INT_SLOW_CLK_CTR); - } - // set the match value - MAP_PRCMRTCMatchSet(seconds, RTC_U16MS_CYCLES(mseconds)); - self->alarmset = true; - self->alarm_time_s = seconds; - self->alarm_time_ms = mseconds; - // enabled the interrupts again if applicable - if (self->irq_enabled || self->repeat) { - MAP_PRCMIntEnable(PRCM_INT_SLOW_CLK_CTR); - } -} - -STATIC void rtc_msec_add (uint16_t msecs_1, uint32_t *secs, uint16_t *msecs_2) { - if (msecs_1 + *msecs_2 >= 1000) { // larger than one second - *msecs_2 = (msecs_1 + *msecs_2) - 1000; - *secs += 1; // carry flag - } else { - // simply add the mseconds - *msecs_2 = msecs_1 + *msecs_2; - } -} - -/******************************************************************************/ -// MicroPython bindings - -STATIC const mp_arg_t pyb_rtc_init_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_datetime, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -}; -STATIC mp_obj_t pyb_rtc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_rtc_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_rtc_init_args, args); - - // check the peripheral id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_ENODEV); - } - - // setup the object - pyb_rtc_obj_t *self = &pyb_rtc_obj; - self->base.type = &pyb_rtc_type; - - // set the time and date - pyb_rtc_datetime((mp_obj_t)&pyb_rtc_obj, args[1].u_obj); - - // pass it to the sleep module - pyb_sleep_set_rtc_obj (self); - - // return constant object - return (mp_obj_t)&pyb_rtc_obj; -} - -STATIC mp_obj_t pyb_rtc_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_rtc_init_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &pyb_rtc_init_args[1], args); - return pyb_rtc_datetime(pos_args[0], args[0].u_obj); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_rtc_init_obj, 1, pyb_rtc_init); - -STATIC mp_obj_t pyb_rtc_now (mp_obj_t self_in) { - timeutils_struct_time_t tm; - uint32_t seconds; - uint16_t mseconds; - - // get the time from the RTC - pyb_rtc_get_time(&seconds, &mseconds); - timeutils_seconds_since_2000_to_struct_time(seconds, &tm); - - mp_obj_t tuple[8] = { - mp_obj_new_int(tm.tm_year), - mp_obj_new_int(tm.tm_mon), - mp_obj_new_int(tm.tm_mday), - mp_obj_new_int(tm.tm_hour), - mp_obj_new_int(tm.tm_min), - mp_obj_new_int(tm.tm_sec), - mp_obj_new_int(mseconds * 1000), - mp_const_none - }; - return mp_obj_new_tuple(8, tuple); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_rtc_now_obj, pyb_rtc_now); - -STATIC mp_obj_t pyb_rtc_deinit (mp_obj_t self_in) { - pyb_rtc_reset(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_rtc_deinit_obj, pyb_rtc_deinit); - -STATIC mp_obj_t pyb_rtc_alarm(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - STATIC const mp_arg_t allowed_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_time, MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_repeat, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, - }; - - // parse args - pyb_rtc_obj_t *self = 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(args), allowed_args, args); - - // check the alarm id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_ENODEV); - } - - uint32_t f_seconds; - uint16_t f_mseconds; - bool repeat = args[2].u_bool; - if (MP_OBJ_IS_TYPE(args[1].u_obj, &mp_type_tuple)) { // datetime tuple given - // repeat cannot be used with a datetime tuple - if (repeat) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - f_mseconds = pyb_rtc_datetime_s_us (args[1].u_obj, &f_seconds) / 1000; - } else { // then it must be an integer - self->alarm_ms = mp_obj_get_int(args[1].u_obj); - pyb_rtc_calc_future_time (self->alarm_ms, &f_seconds, &f_mseconds); - } - - // store the repepat flag - self->repeat = repeat; - - // now configure the alarm - pyb_rtc_set_alarm (self, f_seconds, f_mseconds); - - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_rtc_alarm_obj, 1, pyb_rtc_alarm); - -STATIC mp_obj_t pyb_rtc_alarm_left(size_t n_args, const mp_obj_t *args) { - pyb_rtc_obj_t *self = args[0]; - int32_t ms_left; - uint32_t c_seconds; - uint16_t c_mseconds; - - // only alarm id 0 is available - if (n_args > 1 && mp_obj_get_int(args[1]) != 0) { - mp_raise_OSError(MP_ENODEV); - } - - // get the current time - pyb_rtc_get_time(&c_seconds, &c_mseconds); - - // calculate the ms left - ms_left = ((self->alarm_time_s * 1000) + self->alarm_time_ms) - ((c_seconds * 1000) + c_mseconds); - if (!self->alarmset || ms_left < 0) { - ms_left = 0; - } - return mp_obj_new_int(ms_left); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_rtc_alarm_left_obj, 1, 2, pyb_rtc_alarm_left); - -STATIC mp_obj_t pyb_rtc_alarm_cancel(size_t n_args, const mp_obj_t *args) { - // only alarm id 0 is available - if (n_args > 1 && mp_obj_get_int(args[1]) != 0) { - mp_raise_OSError(MP_ENODEV); - } - // disable the alarm - pyb_rtc_disable_alarm(); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_rtc_alarm_cancel_obj, 1, 2, pyb_rtc_alarm_cancel); - -/// \method irq(trigger, priority, handler, wake) -STATIC mp_obj_t pyb_rtc_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[mp_irq_INIT_NUM_ARGS]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, mp_irq_INIT_NUM_ARGS, mp_irq_init_args, args); - pyb_rtc_obj_t *self = pos_args[0]; - - // save the power mode data for later - uint8_t pwrmode = (args[3].u_obj == mp_const_none) ? PYB_PWR_MODE_ACTIVE : mp_obj_get_int(args[3].u_obj); - if (pwrmode > (PYB_PWR_MODE_ACTIVE | PYB_PWR_MODE_LPDS | PYB_PWR_MODE_HIBERNATE)) { - goto invalid_args; - } - - // check the trigger - if (mp_obj_get_int(args[0].u_obj) == PYB_RTC_ALARM0) { - self->pwrmode = pwrmode; - pyb_rtc_irq_enable((mp_obj_t)self); - } else { - goto invalid_args; - } - - // the interrupt priority is ignored since it's already set to to highest level by the sleep module - // to make sure that the wakeup irqs are always called first when resuming from sleep - - // create the callback - mp_obj_t _irq = mp_irq_new ((mp_obj_t)self, args[2].u_obj, &pyb_rtc_irq_methods); - self->irq_obj = _irq; - - return _irq; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_rtc_irq_obj, 1, pyb_rtc_irq); - -STATIC const mp_rom_map_elem_t pyb_rtc_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_rtc_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_rtc_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_now), MP_ROM_PTR(&pyb_rtc_now_obj) }, - { MP_ROM_QSTR(MP_QSTR_alarm), MP_ROM_PTR(&pyb_rtc_alarm_obj) }, - { MP_ROM_QSTR(MP_QSTR_alarm_left), MP_ROM_PTR(&pyb_rtc_alarm_left_obj) }, - { MP_ROM_QSTR(MP_QSTR_alarm_cancel), MP_ROM_PTR(&pyb_rtc_alarm_cancel_obj) }, - { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pyb_rtc_irq_obj) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_ALARM0), MP_ROM_INT(PYB_RTC_ALARM0) }, -}; -STATIC MP_DEFINE_CONST_DICT(pyb_rtc_locals_dict, pyb_rtc_locals_dict_table); - -const mp_obj_type_t pyb_rtc_type = { - { &mp_type_type }, - .name = MP_QSTR_RTC, - .make_new = pyb_rtc_make_new, - .locals_dict = (mp_obj_t)&pyb_rtc_locals_dict, -}; - -STATIC const mp_irq_methods_t pyb_rtc_irq_methods = { - .init = pyb_rtc_irq, - .enable = pyb_rtc_irq_enable, - .disable = pyb_rtc_irq_disable, - .flags = pyb_rtc_irq_flags -}; diff --git a/cc3200/mods/pybrtc.h b/cc3200/mods/pybrtc.h deleted file mode 100644 index f73de3f5a..000000000 --- a/cc3200/mods/pybrtc.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBRTC_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H - -// RTC triggers -#define PYB_RTC_ALARM0 (0x01) - -#define RTC_ACCESS_TIME_MSEC (5) -#define PYB_RTC_MIN_ALARM_TIME_MS (RTC_ACCESS_TIME_MSEC * 2) - -typedef struct _pyb_rtc_obj_t { - mp_obj_base_t base; - mp_obj_t irq_obj; - uint32_t irq_flags; - uint32_t alarm_ms; - uint32_t alarm_time_s; - uint16_t alarm_time_ms; - byte pwrmode; - bool alarmset; - bool repeat; - bool irq_enabled; -} pyb_rtc_obj_t; - -extern const mp_obj_type_t pyb_rtc_type; - -extern void pyb_rtc_pre_init(void); -extern void pyb_rtc_get_time (uint32_t *secs, uint16_t *msecs); -extern uint32_t pyb_rtc_get_seconds (void); -extern void pyb_rtc_calc_future_time (uint32_t a_mseconds, uint32_t *f_seconds, uint16_t *f_mseconds); -extern void pyb_rtc_repeat_alarm (pyb_rtc_obj_t *self); -extern void pyb_rtc_disable_alarm (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBRTC_H diff --git a/cc3200/mods/pybsd.c b/cc3200/mods/pybsd.c deleted file mode 100644 index c47d4e945..000000000 --- a/cc3200/mods/pybsd.c +++ /dev/null @@ -1,221 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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/obj.h" -#include "py/runtime.h" -#include "py/mperrno.h" -#include "lib/oofatfs/ff.h" -#include "lib/oofatfs/diskio.h" -#include "extmod/vfs_fat.h" -#include "inc/hw_types.h" -#include "inc/hw_gpio.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "pin.h" -#include "prcm.h" -#include "gpio.h" -#include "sdhost.h" -#include "sd_diskio.h" -#include "pybsd.h" -#include "mpexception.h" -#include "pybsleep.h" -#include "pybpin.h" -#include "pins.h" - -/****************************************************************************** - DEFINE PRIVATE CONSTANTS - ******************************************************************************/ -#define PYBSD_FREQUENCY_HZ 15000000 // 15MHz - -/****************************************************************************** - DECLARE PUBLIC DATA - ******************************************************************************/ -pybsd_obj_t pybsd_obj; - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC const mp_obj_t pyb_sd_def_pin[3] = {&pin_GP10, &pin_GP11, &pin_GP15}; - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void pyb_sd_hw_init (pybsd_obj_t *self); -STATIC mp_obj_t pyb_sd_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args); -STATIC mp_obj_t pyb_sd_deinit (mp_obj_t self_in); - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -/// Initalizes the sd card hardware driver -STATIC void pyb_sd_hw_init (pybsd_obj_t *self) { - if (self->pin_clk) { - // Configure the clock pin as output only - MAP_PinDirModeSet(((pin_obj_t *)(self->pin_clk))->pin_num, PIN_DIR_MODE_OUT); - } - // Enable SD peripheral clock - MAP_PRCMPeripheralClkEnable(PRCM_SDHOST, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - // Reset MMCHS - MAP_PRCMPeripheralReset(PRCM_SDHOST); - // Initialize MMCHS - MAP_SDHostInit(SDHOST_BASE); - // Configure the card clock - MAP_SDHostSetExpClk(SDHOST_BASE, MAP_PRCMPeripheralClockGet(PRCM_SDHOST), PYBSD_FREQUENCY_HZ); - // Set card rd/wr block len - MAP_SDHostBlockSizeSet(SDHOST_BASE, SD_SECTOR_SIZE); - self->enabled = true; -} - -STATIC mp_obj_t pyb_sd_init_helper (pybsd_obj_t *self, const mp_arg_val_t *args) { - // assign the pins - mp_obj_t pins_o = args[0].u_obj; - if (pins_o != mp_const_none) { - mp_obj_t *pins; - if (pins_o == MP_OBJ_NULL) { - // use the default pins - pins = (mp_obj_t *)pyb_sd_def_pin; - } else { - mp_obj_get_array_fixed_n(pins_o, MP_ARRAY_SIZE(pyb_sd_def_pin), &pins); - } - pin_assign_pins_af (pins, MP_ARRAY_SIZE(pyb_sd_def_pin), PIN_TYPE_STD_PU, PIN_FN_SD, 0); - // save the pins clock - self->pin_clk = pin_find(pins[0]); - } - - pyb_sd_hw_init (self); - if (sd_disk_init() != 0) { - mp_raise_OSError(MP_EIO); - } - - // register it with the sleep module - pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)pyb_sd_hw_init); - return mp_const_none; -} - -/******************************************************************************/ -// MicroPython bindings -// - -STATIC const mp_arg_t pyb_sd_init_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_pins, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -}; -STATIC mp_obj_t pyb_sd_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_sd_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_sd_init_args, args); - - // check the peripheral id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_ENODEV); - } - - // setup and initialize the object - mp_obj_t self = &pybsd_obj; - pybsd_obj.base.type = &pyb_sd_type; - pyb_sd_init_helper (self, &args[1]); - return self; -} - -STATIC mp_obj_t pyb_sd_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_sd_init_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &pyb_sd_init_args[1], args); - return pyb_sd_init_helper(pos_args[0], args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_sd_init_obj, 1, pyb_sd_init); - -STATIC mp_obj_t pyb_sd_deinit (mp_obj_t self_in) { - pybsd_obj_t *self = self_in; - // disable the peripheral - self->enabled = false; - MAP_PRCMPeripheralClkDisable(PRCM_SDHOST, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - // de-initialze the sd card at diskio level - sd_disk_deinit(); - // unregister it from the sleep module - pyb_sleep_remove (self); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_sd_deinit_obj, pyb_sd_deinit); - -STATIC mp_obj_t pyb_sd_readblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_WRITE); - DRESULT res = sd_disk_read(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / SD_SECTOR_SIZE); - return MP_OBJ_NEW_SMALL_INT(res != RES_OK); // return of 0 means success -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_sd_readblocks_obj, pyb_sd_readblocks); - -STATIC mp_obj_t pyb_sd_writeblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); - DRESULT res = sd_disk_write(bufinfo.buf, mp_obj_get_int(block_num), bufinfo.len / SD_SECTOR_SIZE); - return MP_OBJ_NEW_SMALL_INT(res != RES_OK); // return of 0 means success -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_sd_writeblocks_obj, pyb_sd_writeblocks); - -STATIC mp_obj_t pyb_sd_ioctl(mp_obj_t self, mp_obj_t cmd_in, mp_obj_t arg_in) { - mp_int_t cmd = mp_obj_get_int(cmd_in); - switch (cmd) { - case BP_IOCTL_INIT: - case BP_IOCTL_DEINIT: - case BP_IOCTL_SYNC: - // nothing to do - return MP_OBJ_NEW_SMALL_INT(0); // success - - case BP_IOCTL_SEC_COUNT: - return MP_OBJ_NEW_SMALL_INT(sd_disk_info.ulNofBlock * (sd_disk_info.ulBlockSize / 512)); - - case BP_IOCTL_SEC_SIZE: - return MP_OBJ_NEW_SMALL_INT(SD_SECTOR_SIZE); - - default: // unknown command - return MP_OBJ_NEW_SMALL_INT(-1); // error - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_sd_ioctl_obj, pyb_sd_ioctl); - -STATIC const mp_rom_map_elem_t pyb_sd_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_sd_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_sd_deinit_obj) }, - // block device protocol - { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&pyb_sd_readblocks_obj) }, - { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&pyb_sd_writeblocks_obj) }, - { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&pyb_sd_ioctl_obj) }, -}; - -STATIC MP_DEFINE_CONST_DICT(pyb_sd_locals_dict, pyb_sd_locals_dict_table); - -const mp_obj_type_t pyb_sd_type = { - { &mp_type_type }, - .name = MP_QSTR_SD, - .make_new = pyb_sd_make_new, - .locals_dict = (mp_obj_t)&pyb_sd_locals_dict, -}; diff --git a/cc3200/mods/pybsd.h b/cc3200/mods/pybsd.h deleted file mode 100644 index af942084d..000000000 --- a/cc3200/mods/pybsd.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBSD_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBSD_H - -/****************************************************************************** - DEFINE PUBLIC TYPES - ******************************************************************************/ -typedef struct { - mp_obj_base_t base; - mp_obj_t pin_clk; - bool enabled; -} pybsd_obj_t; - -/****************************************************************************** - DECLARE EXPORTED DATA - ******************************************************************************/ -extern pybsd_obj_t pybsd_obj; -extern const mp_obj_type_t pyb_sd_type; - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSD_H diff --git a/cc3200/mods/pybsleep.c b/cc3200/mods/pybsleep.c deleted file mode 100644 index a7488c5f1..000000000 --- a/cc3200/mods/pybsleep.c +++ /dev/null @@ -1,657 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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/mpstate.h" -#include "py/runtime.h" -#include "py/mphal.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_nvic.h" -#include "inc/hw_common_reg.h" -#include "inc/hw_memmap.h" -#include "cc3200_asm.h" -#include "rom_map.h" -#include "interrupt.h" -#include "systick.h" -#include "prcm.h" -#include "spi.h" -#include "pin.h" -#include "pybsleep.h" -#include "mpirq.h" -#include "pybpin.h" -#include "simplelink.h" -#include "modnetwork.h" -#include "modwlan.h" -#include "osi.h" -#include "debug.h" -#include "mpexception.h" -#include "mperror.h" -#include "sleeprestore.h" -#include "serverstask.h" -#include "antenna.h" -#include "cryptohash.h" -#include "pybrtc.h" - -/****************************************************************************** - DECLARE PRIVATE CONSTANTS - ******************************************************************************/ -#define SPIFLASH_INSTR_READ_STATUS (0x05) -#define SPIFLASH_INSTR_DEEP_POWER_DOWN (0xB9) -#define SPIFLASH_STATUS_BUSY (0x01) - -#define LPDS_UP_TIME (425) // 13 msec -#define LPDS_DOWN_TIME (98) // 3 msec -#define USER_OFFSET (131) // 4 smec -#define WAKEUP_TIME_LPDS (LPDS_UP_TIME + LPDS_DOWN_TIME + USER_OFFSET) // 20 msec -#define WAKEUP_TIME_HIB (32768) // 1 s - -#define FORCED_TIMER_INTERRUPT_MS (PYB_RTC_MIN_ALARM_TIME_MS) -#define FAILED_SLEEP_DELAY_MS (FORCED_TIMER_INTERRUPT_MS * 3) - -/****************************************************************************** - DECLARE PRIVATE TYPES - ******************************************************************************/ -// storage memory for Cortex M4 registers -typedef struct { - uint32_t msp; - uint32_t psp; - uint32_t psr; - uint32_t primask; - uint32_t faultmask; - uint32_t basepri; - uint32_t control; -} arm_cm4_core_regs_t; - -// storage memory for the NVIC registers -typedef struct { - uint32_t vector_table; // Vector Table Offset - uint32_t aux_ctrl; // Auxiliary control register - uint32_t int_ctrl_state; // Interrupt Control and State - uint32_t app_int; // Application Interrupt Reset control - uint32_t sys_ctrl; // System control - uint32_t config_ctrl; // Configuration control - uint32_t sys_pri_1; // System Handler Priority 1 - uint32_t sys_pri_2; // System Handler Priority 2 - uint32_t sys_pri_3; // System Handler Priority 3 - uint32_t sys_hcrs; // System Handler control and state register - uint32_t systick_ctrl; // SysTick Control Status - uint32_t systick_reload; // SysTick Reload - uint32_t systick_calib; // SysTick Calibration - uint32_t int_en[6]; // Interrupt set enable - uint32_t int_priority[49]; // Interrupt priority -} nvic_reg_store_t; - -typedef struct { - mp_obj_base_t base; - mp_obj_t obj; - WakeUpCB_t wakeup; -} pyb_sleep_obj_t; - -typedef struct { - mp_obj_t gpio_lpds_wake_cb; - wlan_obj_t *wlan_obj; - pyb_rtc_obj_t *rtc_obj; -} pybsleep_data_t; - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC nvic_reg_store_t *nvic_reg_store; -STATIC pybsleep_data_t pybsleep_data = {NULL, NULL, NULL}; -volatile arm_cm4_core_regs_t vault_arm_registers; -STATIC pybsleep_reset_cause_t pybsleep_reset_cause = PYB_SLP_PWRON_RESET; -STATIC pybsleep_wake_reason_t pybsleep_wake_reason = PYB_SLP_WAKED_PWRON; -STATIC const mp_obj_type_t pyb_sleep_type = { - { &mp_type_type }, - .name = MP_QSTR_sleep, -}; - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC pyb_sleep_obj_t *pyb_sleep_find (mp_obj_t obj); -STATIC void pyb_sleep_flash_powerdown (void); -STATIC NORETURN void pyb_sleep_suspend_enter (void); -void pyb_sleep_suspend_exit (void); -STATIC void pyb_sleep_obj_wakeup (void); -STATIC void PRCMInterruptHandler (void); -STATIC void pyb_sleep_iopark (bool hibernate); -STATIC bool setup_timer_lpds_wake (void); -STATIC bool setup_timer_hibernate_wake (void); - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -__attribute__ ((section (".boot"))) -void pyb_sleep_pre_init (void) { - // allocate memory for nvic registers vault - ASSERT ((nvic_reg_store = mem_Malloc(sizeof(nvic_reg_store_t))) != NULL); -} - -void pyb_sleep_init0 (void) { - // initialize the sleep objects list - mp_obj_list_init(&MP_STATE_PORT(pyb_sleep_obj_list), 0); - - // register and enable the PRCM interrupt - osi_InterruptRegister(INT_PRCM, (P_OSI_INTR_ENTRY)PRCMInterruptHandler, INT_PRIORITY_LVL_1); - - // disable all LPDS and hibernate wake up sources (WLAN is disabed/enabled before entering LDPS mode) - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_GPIO); - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER); - MAP_PRCMHibernateWakeupSourceDisable(PRCM_HIB_SLOW_CLK_CTR | PRCM_HIB_GPIO2 | PRCM_HIB_GPIO4 | PRCM_HIB_GPIO13 | - PRCM_HIB_GPIO17 | PRCM_HIB_GPIO11 | PRCM_HIB_GPIO24 | PRCM_HIB_GPIO26); - - // check the reset casue (if it's soft reset, leave it as it is) - if (pybsleep_reset_cause != PYB_SLP_SOFT_RESET) { - switch (MAP_PRCMSysResetCauseGet()) { - case PRCM_POWER_ON: - pybsleep_reset_cause = PYB_SLP_PWRON_RESET; - break; - case PRCM_CORE_RESET: - case PRCM_MCU_RESET: - case PRCM_SOC_RESET: - pybsleep_reset_cause = PYB_SLP_HARD_RESET; - break; - case PRCM_WDT_RESET: - pybsleep_reset_cause = PYB_SLP_WDT_RESET; - break; - case PRCM_HIB_EXIT: - if (PRCMGetSpecialBit(PRCM_WDT_RESET_BIT)) { - pybsleep_reset_cause = PYB_SLP_WDT_RESET; - } - else { - pybsleep_reset_cause = PYB_SLP_HIB_RESET; - // set the correct wake reason - switch (MAP_PRCMHibernateWakeupCauseGet()) { - case PRCM_HIB_WAKEUP_CAUSE_SLOW_CLOCK: - pybsleep_wake_reason = PYB_SLP_WAKED_BY_RTC; - // TODO repeat the alarm - break; - case PRCM_HIB_WAKEUP_CAUSE_GPIO: - pybsleep_wake_reason = PYB_SLP_WAKED_BY_GPIO; - break; - default: - break; - } - } - break; - default: - break; - } - } -} - -void pyb_sleep_signal_soft_reset (void) { - pybsleep_reset_cause = PYB_SLP_SOFT_RESET; -} - -void pyb_sleep_add (const mp_obj_t obj, WakeUpCB_t wakeup) { - pyb_sleep_obj_t *sleep_obj = m_new_obj(pyb_sleep_obj_t); - sleep_obj->base.type = &pyb_sleep_type; - sleep_obj->obj = obj; - sleep_obj->wakeup = wakeup; - // remove it in case it was already registered - pyb_sleep_remove (obj); - mp_obj_list_append(&MP_STATE_PORT(pyb_sleep_obj_list), sleep_obj); -} - -void pyb_sleep_remove (const mp_obj_t obj) { - pyb_sleep_obj_t *sleep_obj; - if ((sleep_obj = pyb_sleep_find(obj))) { - mp_obj_list_remove(&MP_STATE_PORT(pyb_sleep_obj_list), sleep_obj); - } -} - -void pyb_sleep_set_gpio_lpds_callback (mp_obj_t cb_obj) { - pybsleep_data.gpio_lpds_wake_cb = cb_obj; -} - -void pyb_sleep_set_wlan_obj (mp_obj_t wlan_obj) { - pybsleep_data.wlan_obj = (wlan_obj_t *)wlan_obj; -} - -void pyb_sleep_set_rtc_obj (mp_obj_t rtc_obj) { - pybsleep_data.rtc_obj = (pyb_rtc_obj_t *)rtc_obj; -} - -void pyb_sleep_sleep (void) { - nlr_buf_t nlr; - - // check if we should enable timer wake-up - if (pybsleep_data.rtc_obj->irq_enabled && (pybsleep_data.rtc_obj->pwrmode & PYB_PWR_MODE_LPDS)) { - if (!setup_timer_lpds_wake()) { - // lpds entering is not possible, wait for the forced interrupt and return - mp_hal_delay_ms(FAILED_SLEEP_DELAY_MS); - return; - } - } else { - // disable the timer as wake source - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER); - } - - // do we need network wake-up? - if (pybsleep_data.wlan_obj->irq_enabled) { - MAP_PRCMLPDSWakeupSourceEnable (PRCM_LPDS_HOST_IRQ); - server_sleep_sockets(); - } else { - MAP_PRCMLPDSWakeupSourceDisable (PRCM_LPDS_HOST_IRQ); - } - - // entering and exiting suspended mode must be an atomic operation - // therefore interrupts need to be disabled - uint primsk = disable_irq(); - if (nlr_push(&nlr) == 0) { - pyb_sleep_suspend_enter(); - nlr_pop(); - } - - // an exception is always raised when exiting suspend mode - enable_irq(primsk); -} - -void pyb_sleep_deepsleep (void) { - // check if we should enable timer wake-up - if (pybsleep_data.rtc_obj->irq_enabled && (pybsleep_data.rtc_obj->pwrmode & PYB_PWR_MODE_HIBERNATE)) { - if (!setup_timer_hibernate_wake()) { - // hibernating is not possible, wait for the forced interrupt and return - mp_hal_delay_ms(FAILED_SLEEP_DELAY_MS); - return; - } - } else { - // disable the timer as hibernate wake source - MAP_PRCMLPDSWakeupSourceDisable(PRCM_HIB_SLOW_CLK_CTR); - } - - wlan_stop(SL_STOP_TIMEOUT); - pyb_sleep_flash_powerdown(); - // must be done just before entering hibernate mode - pyb_sleep_iopark(true); - MAP_PRCMHibernateEnter(); -} - -pybsleep_reset_cause_t pyb_sleep_get_reset_cause (void) { - return pybsleep_reset_cause; -} - -pybsleep_wake_reason_t pyb_sleep_get_wake_reason (void) { - return pybsleep_wake_reason; -} - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC pyb_sleep_obj_t *pyb_sleep_find (mp_obj_t obj) { - for (mp_uint_t i = 0; i < MP_STATE_PORT(pyb_sleep_obj_list).len; i++) { - // search for the object and then remove it - pyb_sleep_obj_t *sleep_obj = ((pyb_sleep_obj_t *)(MP_STATE_PORT(pyb_sleep_obj_list).items[i])); - if (sleep_obj->obj == obj) { - return sleep_obj; - } - } - return NULL; -} - -STATIC void pyb_sleep_flash_powerdown (void) { - uint32_t status; - - // Enable clock for SSPI module - MAP_PRCMPeripheralClkEnable(PRCM_SSPI, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - // Reset SSPI at PRCM level and wait for reset to complete - MAP_PRCMPeripheralReset(PRCM_SSPI); - while(!MAP_PRCMPeripheralStatusGet(PRCM_SSPI)); - - // Reset SSPI at module level - MAP_SPIReset(SSPI_BASE); - // Configure SSPI module - MAP_SPIConfigSetExpClk (SSPI_BASE, PRCMPeripheralClockGet(PRCM_SSPI), - 20000000, SPI_MODE_MASTER,SPI_SUB_MODE_0, - (SPI_SW_CTRL_CS | - SPI_4PIN_MODE | - SPI_TURBO_OFF | - SPI_CS_ACTIVELOW | - SPI_WL_8)); - - // Enable SSPI module - MAP_SPIEnable(SSPI_BASE); - // Enable chip select for the spi flash. - MAP_SPICSEnable(SSPI_BASE); - // Wait for the spi flash - do { - // Send the status register read instruction and read back a dummy byte. - MAP_SPIDataPut(SSPI_BASE, SPIFLASH_INSTR_READ_STATUS); - MAP_SPIDataGet(SSPI_BASE, &status); - - // Write a dummy byte then read back the actual status. - MAP_SPIDataPut(SSPI_BASE, 0xFF); - MAP_SPIDataGet(SSPI_BASE, &status); - } while ((status & 0xFF) == SPIFLASH_STATUS_BUSY); - - // Disable chip select for the spi flash. - MAP_SPICSDisable(SSPI_BASE); - // Start another CS enable sequence for Power down command. - MAP_SPICSEnable(SSPI_BASE); - // Send Deep Power Down command to spi flash - MAP_SPIDataPut(SSPI_BASE, SPIFLASH_INSTR_DEEP_POWER_DOWN); - // Disable chip select for the spi flash. - MAP_SPICSDisable(SSPI_BASE); -} - -STATIC NORETURN void pyb_sleep_suspend_enter (void) { - // enable full RAM retention - MAP_PRCMSRAMRetentionEnable(PRCM_SRAM_COL_1 | PRCM_SRAM_COL_2 | PRCM_SRAM_COL_3 | PRCM_SRAM_COL_4, PRCM_SRAM_LPDS_RET); - - // save the NVIC control registers - nvic_reg_store->vector_table = HWREG(NVIC_VTABLE); - nvic_reg_store->aux_ctrl = HWREG(NVIC_ACTLR); - nvic_reg_store->int_ctrl_state = HWREG(NVIC_INT_CTRL); - nvic_reg_store->app_int = HWREG(NVIC_APINT); - nvic_reg_store->sys_ctrl = HWREG(NVIC_SYS_CTRL); - nvic_reg_store->config_ctrl = HWREG(NVIC_CFG_CTRL); - nvic_reg_store->sys_pri_1 = HWREG(NVIC_SYS_PRI1); - nvic_reg_store->sys_pri_2 = HWREG(NVIC_SYS_PRI2); - nvic_reg_store->sys_pri_3 = HWREG(NVIC_SYS_PRI3); - nvic_reg_store->sys_hcrs = HWREG(NVIC_SYS_HND_CTRL); - - // save the systick registers - nvic_reg_store->systick_ctrl = HWREG(NVIC_ST_CTRL); - nvic_reg_store->systick_reload = HWREG(NVIC_ST_RELOAD); - nvic_reg_store->systick_calib = HWREG(NVIC_ST_CAL); - - // save the interrupt enable registers - uint32_t *base_reg_addr = (uint32_t *)NVIC_EN0; - for(int32_t i = 0; i < (sizeof(nvic_reg_store->int_en) / 4); i++) { - nvic_reg_store->int_en[i] = base_reg_addr[i]; - } - - // save the interrupt priority registers - base_reg_addr = (uint32_t *)NVIC_PRI0; - for(int32_t i = 0; i < (sizeof(nvic_reg_store->int_priority) / 4); i++) { - nvic_reg_store->int_priority[i] = base_reg_addr[i]; - } - - // switch off the heartbeat led (this makes sure it will blink as soon as we wake up) - mperror_heartbeat_switch_off(); - - // park the gpio pins - pyb_sleep_iopark(false); - - // store the cpu registers - sleep_store(); - - // save the restore info and enter LPDS - MAP_PRCMLPDSRestoreInfoSet(vault_arm_registers.psp, (uint32_t)sleep_restore); - MAP_PRCMLPDSEnter(); - - // let the cpu fade away... - for ( ; ; ); -} - -void pyb_sleep_suspend_exit (void) { - // take the I2C semaphore - uint32_t reg = HWREG(COMMON_REG_BASE + COMMON_REG_O_I2C_Properties_Register); - reg = (reg & ~0x3) | 0x1; - HWREG(COMMON_REG_BASE + COMMON_REG_O_I2C_Properties_Register) = reg; - - // take the GPIO semaphore - reg = HWREG(COMMON_REG_BASE + COMMON_REG_O_GPIO_properties_register); - reg = (reg & ~0x3FF) | 0x155; - HWREG(COMMON_REG_BASE + COMMON_REG_O_GPIO_properties_register) = reg; - - // restore de NVIC control registers - HWREG(NVIC_VTABLE) = nvic_reg_store->vector_table; - HWREG(NVIC_ACTLR) = nvic_reg_store->aux_ctrl; - HWREG(NVIC_INT_CTRL) = nvic_reg_store->int_ctrl_state; - HWREG(NVIC_APINT) = nvic_reg_store->app_int; - HWREG(NVIC_SYS_CTRL) = nvic_reg_store->sys_ctrl; - HWREG(NVIC_CFG_CTRL) = nvic_reg_store->config_ctrl; - HWREG(NVIC_SYS_PRI1) = nvic_reg_store->sys_pri_1; - HWREG(NVIC_SYS_PRI2) = nvic_reg_store->sys_pri_2; - HWREG(NVIC_SYS_PRI3) = nvic_reg_store->sys_pri_3; - HWREG(NVIC_SYS_HND_CTRL) = nvic_reg_store->sys_hcrs; - - // restore the systick register - HWREG(NVIC_ST_CTRL) = nvic_reg_store->systick_ctrl; - HWREG(NVIC_ST_RELOAD) = nvic_reg_store->systick_reload; - HWREG(NVIC_ST_CAL) = nvic_reg_store->systick_calib; - - // restore the interrupt priority registers - uint32_t *base_reg_addr = (uint32_t *)NVIC_PRI0; - for (uint32_t i = 0; i < (sizeof(nvic_reg_store->int_priority) / 4); i++) { - base_reg_addr[i] = nvic_reg_store->int_priority[i]; - } - - // restore the interrupt enable registers - base_reg_addr = (uint32_t *)NVIC_EN0; - for(uint32_t i = 0; i < (sizeof(nvic_reg_store->int_en) / 4); i++) { - base_reg_addr[i] = nvic_reg_store->int_en[i]; - } - - HAL_INTRODUCE_SYNC_BARRIER(); - - // ungate the clock to the shared spi bus - MAP_PRCMPeripheralClkEnable(PRCM_SSPI, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - -#if MICROPY_HW_ANTENNA_DIVERSITY - // re-configure the antenna selection pins - antenna_init0(); -#endif - - // reinitialize simplelink's interface - sl_IfOpen (NULL, 0); - - // restore the configuration of all active peripherals - pyb_sleep_obj_wakeup(); - - // reconfigure all the previously enabled interrupts - mp_irq_wake_all(); - - // we need to init the crypto hash engine again - //CRYPTOHASH_Init(); - - // trigger a sw interrupt - MAP_IntPendSet(INT_PRCM); - - // force an exception to go back to the point where suspend mode was entered - nlr_raise(mp_obj_new_exception(&mp_type_SystemExit)); -} - -STATIC void PRCMInterruptHandler (void) { - // reading the interrupt status automatically clears the interrupt - if (PRCM_INT_SLOW_CLK_CTR == MAP_PRCMIntStatus()) { - // reconfigure it again (if repeat is true) - pyb_rtc_repeat_alarm (pybsleep_data.rtc_obj); - pybsleep_data.rtc_obj->irq_flags = PYB_RTC_ALARM0; - // need to check if irq's are enabled from the user point of view - if (pybsleep_data.rtc_obj->irq_enabled && (pybsleep_data.rtc_obj->pwrmode & PYB_PWR_MODE_ACTIVE)) { - mp_irq_handler(pybsleep_data.rtc_obj->irq_obj); - } - pybsleep_data.rtc_obj->irq_flags = 0; - } else { - // interrupt has been triggered while waking up from LPDS - switch (MAP_PRCMLPDSWakeupCauseGet()) { - case PRCM_LPDS_HOST_IRQ: - pybsleep_data.wlan_obj->irq_flags = MODWLAN_WIFI_EVENT_ANY; - mp_irq_handler(pybsleep_data.wlan_obj->irq_obj); - pybsleep_wake_reason = PYB_SLP_WAKED_BY_WLAN; - pybsleep_data.wlan_obj->irq_flags = 0; - break; - case PRCM_LPDS_GPIO: - mp_irq_handler(pybsleep_data.gpio_lpds_wake_cb); - pybsleep_wake_reason = PYB_SLP_WAKED_BY_GPIO; - break; - case PRCM_LPDS_TIMER: - // reconfigure it again if repeat is true - pyb_rtc_repeat_alarm (pybsleep_data.rtc_obj); - pybsleep_data.rtc_obj->irq_flags = PYB_RTC_ALARM0; - // next one clears the wake cause flag - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER); - mp_irq_handler(pybsleep_data.rtc_obj->irq_obj); - pybsleep_data.rtc_obj->irq_flags = 0; - pybsleep_wake_reason = PYB_SLP_WAKED_BY_RTC; - break; - default: - break; - } - } -} - -STATIC void pyb_sleep_obj_wakeup (void) { - for (mp_uint_t i = 0; i < MP_STATE_PORT(pyb_sleep_obj_list).len; i++) { - pyb_sleep_obj_t *sleep_obj = ((pyb_sleep_obj_t *)MP_STATE_PORT(pyb_sleep_obj_list).items[i]); - sleep_obj->wakeup(sleep_obj->obj); - } -} - -STATIC void pyb_sleep_iopark (bool hibernate) { - mp_map_t *named_map = mp_obj_dict_get_map((mp_obj_t)&pin_board_pins_locals_dict); - for (uint i = 0; i < named_map->used; i++) { - pin_obj_t * pin = (pin_obj_t *)named_map->table[i].value; - switch (pin->pin_num) { -#ifdef DEBUG - // skip the JTAG pins - case PIN_16: - case PIN_17: - case PIN_19: - case PIN_20: - break; -#endif - default: - // enable a weak pull-up if the pin is unused - if (!pin->used) { - MAP_PinConfigSet(pin->pin_num, pin->strength, PIN_TYPE_STD_PU); - } - if (hibernate) { - // make it an input - MAP_PinDirModeSet(pin->pin_num, PIN_DIR_MODE_IN); - } - break; - } - } - - // park the sflash pins - HWREG(0x4402E0E8) &= ~(0x3 << 8); - HWREG(0x4402E0E8) |= (0x2 << 8); - HWREG(0x4402E0EC) &= ~(0x3 << 8); - HWREG(0x4402E0EC) |= (0x2 << 8); - HWREG(0x4402E0F0) &= ~(0x3 << 8); - HWREG(0x4402E0F0) |= (0x2 << 8); - HWREG(0x4402E0F4) &= ~(0x3 << 8); - HWREG(0x4402E0F4) |= (0x1 << 8); - - // if the board has antenna diversity, only park the antenna - // selection pins when going into hibernation -#if MICROPY_HW_ANTENNA_DIVERSITY - if (hibernate) { -#endif - // park the antenna selection pins - // (tri-stated with pull down enabled) - HWREG(0x4402E108) = 0x00000E61; - HWREG(0x4402E10C) = 0x00000E61; -#if MICROPY_HW_ANTENNA_DIVERSITY - } else { - // park the antenna selection pins - // (tri-stated without changing the pull up/down resistors) - HWREG(0x4402E108) &= ~0x000000FF; - HWREG(0x4402E108) |= 0x00000C61; - HWREG(0x4402E10C) &= ~0x000000FF; - HWREG(0x4402E10C) |= 0x00000C61; - } -#endif -} - -STATIC bool setup_timer_lpds_wake (void) { - uint64_t t_match, t_curr; - int64_t t_remaining; - - // get the time remaining for the RTC timer to expire - t_match = MAP_PRCMSlowClkCtrMatchGet(); - t_curr = MAP_PRCMSlowClkCtrGet(); - - // get the time remaining in terms of slow clocks - t_remaining = (t_match - t_curr); - if (t_remaining > WAKEUP_TIME_LPDS) { - // subtract the time it takes to wakeup from lpds - t_remaining -= WAKEUP_TIME_LPDS; - t_remaining = (t_remaining > 0xFFFFFFFF) ? 0xFFFFFFFF: t_remaining; - // setup the LPDS wake time - MAP_PRCMLPDSIntervalSet((uint32_t)t_remaining); - // enable the wake source - MAP_PRCMLPDSWakeupSourceEnable(PRCM_LPDS_TIMER); - return true; - } - - // disable the timer as wake source - MAP_PRCMLPDSWakeupSourceDisable(PRCM_LPDS_TIMER); - - uint32_t f_seconds; - uint16_t f_mseconds; - // setup a timer interrupt immediately - pyb_rtc_calc_future_time (FORCED_TIMER_INTERRUPT_MS, &f_seconds, &f_mseconds); - MAP_PRCMRTCMatchSet(f_seconds, f_mseconds); - // LPDS wake by timer was not possible, force an interrupt in active mode instead - MAP_PRCMIntEnable(PRCM_INT_SLOW_CLK_CTR); - - return false; -} - -STATIC bool setup_timer_hibernate_wake (void) { - uint64_t t_match, t_curr; - int64_t t_remaining; - - // get the time remaining for the RTC timer to expire - t_match = MAP_PRCMSlowClkCtrMatchGet(); - t_curr = MAP_PRCMSlowClkCtrGet(); - - // get the time remaining in terms of slow clocks - t_remaining = (t_match - t_curr); - if (t_remaining > WAKEUP_TIME_HIB) { - // subtract the time it takes for wakeup from hibernate - t_remaining -= WAKEUP_TIME_HIB; - // setup the LPDS wake time - MAP_PRCMHibernateIntervalSet((uint32_t)t_remaining); - // enable the wake source - MAP_PRCMHibernateWakeupSourceEnable(PRCM_HIB_SLOW_CLK_CTR); - return true; - } - - - // disable the timer as wake source - MAP_PRCMLPDSWakeupSourceDisable(PRCM_HIB_SLOW_CLK_CTR); - - uint32_t f_seconds; - uint16_t f_mseconds; - // setup a timer interrupt immediately - pyb_rtc_calc_future_time (FORCED_TIMER_INTERRUPT_MS, &f_seconds, &f_mseconds); - MAP_PRCMRTCMatchSet(f_seconds, f_mseconds); - // LPDS wake by timer was not possible, force an interrupt in active mode instead - MAP_PRCMIntEnable(PRCM_INT_SLOW_CLK_CTR); - - return false; -} - diff --git a/cc3200/mods/pybsleep.h b/cc3200/mods/pybsleep.h deleted file mode 100644 index e98636178..000000000 --- a/cc3200/mods/pybsleep.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBSLEEP_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define PYB_PWR_MODE_ACTIVE (0x01) -#define PYB_PWR_MODE_LPDS (0x02) -#define PYB_PWR_MODE_HIBERNATE (0x04) - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef enum { - PYB_SLP_PWRON_RESET = 0, - PYB_SLP_HARD_RESET, - PYB_SLP_WDT_RESET, - PYB_SLP_HIB_RESET, - PYB_SLP_SOFT_RESET -} pybsleep_reset_cause_t; - -typedef enum { - PYB_SLP_WAKED_PWRON = 0, - PYB_SLP_WAKED_BY_WLAN, - PYB_SLP_WAKED_BY_GPIO, - PYB_SLP_WAKED_BY_RTC -} pybsleep_wake_reason_t; - -typedef void (*WakeUpCB_t)(const mp_obj_t self); - -/****************************************************************************** - DECLARE FUNCTIONS - ******************************************************************************/ -void pyb_sleep_pre_init (void); -void pyb_sleep_init0 (void); -void pyb_sleep_signal_soft_reset (void); -void pyb_sleep_add (const mp_obj_t obj, WakeUpCB_t wakeup); -void pyb_sleep_remove (const mp_obj_t obj); -void pyb_sleep_set_gpio_lpds_callback (mp_obj_t cb_obj); -void pyb_sleep_set_wlan_obj (mp_obj_t wlan_obj); -void pyb_sleep_set_rtc_obj (mp_obj_t rtc_obj); -void pyb_sleep_sleep (void); -void pyb_sleep_deepsleep (void); -pybsleep_reset_cause_t pyb_sleep_get_reset_cause (void); -pybsleep_wake_reason_t pyb_sleep_get_wake_reason (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSLEEP_H diff --git a/cc3200/mods/pybspi.c b/cc3200/mods/pybspi.c deleted file mode 100644 index 8537f649f..000000000 --- a/cc3200/mods/pybspi.c +++ /dev/null @@ -1,388 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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/mpstate.h" -#include "py/runtime.h" -#include "py/mperrno.h" -#include "bufhelper.h" -#include "inc/hw_types.h" -#include "inc/hw_mcspi.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "pin.h" -#include "prcm.h" -#include "spi.h" -#include "pybspi.h" -#include "mpexception.h" -#include "pybsleep.h" -#include "pybpin.h" -#include "pins.h" - -/// \moduleref pyb -/// \class SPI - a master-driven serial protocol - -/****************************************************************************** - DEFINE TYPES - ******************************************************************************/ -typedef struct _pyb_spi_obj_t { - mp_obj_base_t base; - uint baudrate; - uint config; - byte polarity; - byte phase; - byte submode; - byte wlen; -} pyb_spi_obj_t; - -/****************************************************************************** - DEFINE CONSTANTS - ******************************************************************************/ -#define PYBSPI_FIRST_BIT_MSB 0 - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC pyb_spi_obj_t pyb_spi_obj = {.baudrate = 0}; - -STATIC const mp_obj_t pyb_spi_def_pin[3] = {&pin_GP14, &pin_GP16, &pin_GP30}; - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -// only master mode is available for the moment -STATIC void pybspi_init (const pyb_spi_obj_t *self) { - // enable the peripheral clock - MAP_PRCMPeripheralClkEnable(PRCM_GSPI, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - MAP_PRCMPeripheralReset(PRCM_GSPI); - MAP_SPIReset(GSPI_BASE); - - // configure the interface (only master mode supported) - MAP_SPIConfigSetExpClk (GSPI_BASE, MAP_PRCMPeripheralClockGet(PRCM_GSPI), - self->baudrate, SPI_MODE_MASTER, self->submode, self->config); - - // enable the interface - MAP_SPIEnable(GSPI_BASE); -} - -STATIC void pybspi_tx (pyb_spi_obj_t *self, const void *data) { - uint32_t txdata; - switch (self->wlen) { - case 1: - txdata = (uint8_t)(*(char *)data); - break; - case 2: - txdata = (uint16_t)(*(uint16_t *)data); - break; - case 4: - txdata = (uint32_t)(*(uint32_t *)data); - break; - default: - return; - } - MAP_SPIDataPut (GSPI_BASE, txdata); -} - -STATIC void pybspi_rx (pyb_spi_obj_t *self, void *data) { - uint32_t rxdata; - MAP_SPIDataGet (GSPI_BASE, &rxdata); - if (data) { - switch (self->wlen) { - case 1: - *(char *)data = rxdata; - break; - case 2: - *(uint16_t *)data = rxdata; - break; - case 4: - *(uint32_t *)data = rxdata; - break; - default: - return; - } - } -} - -STATIC void pybspi_transfer (pyb_spi_obj_t *self, const char *txdata, char *rxdata, uint32_t len, uint32_t *txchar) { - if (!self->baudrate) { - mp_raise_OSError(MP_EPERM); - } - // send and receive the data - MAP_SPICSEnable(GSPI_BASE); - for (int i = 0; i < len; i += self->wlen) { - pybspi_tx(self, txdata ? (const void *)&txdata[i] : txchar); - pybspi_rx(self, rxdata ? (void *)&rxdata[i] : NULL); - } - MAP_SPICSDisable(GSPI_BASE); -} - -/******************************************************************************/ -/* MicroPython bindings */ -/******************************************************************************/ -STATIC void pyb_spi_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_spi_obj_t *self = self_in; - if (self->baudrate > 0) { - mp_printf(print, "SPI(0, baudrate=%u, bits=%u, polarity=%u, phase=%u, firstbit=SPI.MSB)", - self->baudrate, (self->wlen * 8), self->polarity, self->phase); - } else { - mp_print_str(print, "SPI(0)"); - } -} - -STATIC mp_obj_t pyb_spi_init_helper(pyb_spi_obj_t *self, const mp_arg_val_t *args) { - uint bits; - switch (args[1].u_int) { - case 8: - bits = SPI_WL_8; - break; - case 16: - bits = SPI_WL_16; - break; - case 32: - bits = SPI_WL_32; - break; - default: - goto invalid_args; - break; - } - - uint polarity = args[2].u_int; - uint phase = args[3].u_int; - if (polarity > 1 || phase > 1) { - goto invalid_args; - } - - uint firstbit = args[4].u_int; - if (firstbit != PYBSPI_FIRST_BIT_MSB) { - goto invalid_args; - } - - // build the configuration - self->baudrate = args[0].u_int; - self->wlen = args[1].u_int >> 3; - self->config = bits | SPI_CS_ACTIVELOW | SPI_SW_CTRL_CS | SPI_4PIN_MODE | SPI_TURBO_OFF; - self->polarity = polarity; - self->phase = phase; - self->submode = (polarity << 1) | phase; - - // assign the pins - mp_obj_t pins_o = args[5].u_obj; - if (pins_o != mp_const_none) { - mp_obj_t *pins; - if (pins_o == MP_OBJ_NULL) { - // use the default pins - pins = (mp_obj_t *)pyb_spi_def_pin; - } else { - mp_obj_get_array_fixed_n(pins_o, 3, &pins); - } - pin_assign_pins_af (pins, 3, PIN_TYPE_STD_PU, PIN_FN_SPI, 0); - } - - // init the bus - pybspi_init((const pyb_spi_obj_t *)self); - - // register it with the sleep module - pyb_sleep_add((const mp_obj_t)self, (WakeUpCB_t)pybspi_init); - - return mp_const_none; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -static const mp_arg_t pyb_spi_init_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1000000} }, // 1MHz - { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, - { 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_firstbit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = PYBSPI_FIRST_BIT_MSB} }, - { MP_QSTR_pins, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -}; -STATIC mp_obj_t pyb_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_spi_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_spi_init_args, args); - - // check the peripheral id - if (args[0].u_int != 0) { - mp_raise_OSError(MP_ENODEV); - } - - // setup the object - pyb_spi_obj_t *self = &pyb_spi_obj; - self->base.type = &pyb_spi_type; - - // start the peripheral - pyb_spi_init_helper(self, &args[1]); - - return self; -} - -STATIC mp_obj_t pyb_spi_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_spi_init_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &pyb_spi_init_args[1], args); - return pyb_spi_init_helper(pos_args[0], args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_init_obj, 1, pyb_spi_init); - -/// \method deinit() -/// Turn off the spi bus. -STATIC mp_obj_t pyb_spi_deinit(mp_obj_t self_in) { - // disable the peripheral - MAP_SPIDisable(GSPI_BASE); - MAP_PRCMPeripheralClkDisable(PRCM_GSPI, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - // invalidate the baudrate - pyb_spi_obj.baudrate = 0; - // unregister it with the sleep module - pyb_sleep_remove((const mp_obj_t)self_in); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_spi_deinit_obj, pyb_spi_deinit); - -STATIC mp_obj_t pyb_spi_write (mp_obj_t self_in, mp_obj_t buf) { - // parse args - pyb_spi_obj_t *self = self_in; - - // get the buffer to send from - mp_buffer_info_t bufinfo; - uint8_t data[1]; - pyb_buf_get_for_send(buf, &bufinfo, data); - - // just send - pybspi_transfer(self, (const char *)bufinfo.buf, NULL, bufinfo.len, NULL); - - // return the number of bytes written - return mp_obj_new_int(bufinfo.len); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_2(pyb_spi_write_obj, pyb_spi_write); - -STATIC mp_obj_t pyb_spi_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - static const mp_arg_t allowed_args[] = { - { MP_QSTR_nbytes, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_write, MP_ARG_INT, {.u_int = 0x00} }, - }; - - // parse args - pyb_spi_obj_t *self = 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(args), allowed_args, args); - - // get the buffer to receive into - vstr_t vstr; - pyb_buf_get_for_recv(args[0].u_obj, &vstr); - - // just receive - uint32_t write = args[1].u_int; - pybspi_transfer(self, NULL, vstr.buf, vstr.len, &write); - - // return the received data - return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_read_obj, 1, pyb_spi_read); - -STATIC mp_obj_t pyb_spi_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - static const mp_arg_t allowed_args[] = { - { MP_QSTR_buf, MP_ARG_REQUIRED | MP_ARG_OBJ, }, - { MP_QSTR_write, MP_ARG_INT, {.u_int = 0x00} }, - }; - - // parse args - pyb_spi_obj_t *self = 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(args), allowed_args, args); - - // get the buffer to receive into - vstr_t vstr; - pyb_buf_get_for_recv(args[0].u_obj, &vstr); - - // just receive - uint32_t write = args[1].u_int; - pybspi_transfer(self, NULL, vstr.buf, vstr.len, &write); - - // return the number of bytes received - return mp_obj_new_int(vstr.len); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_spi_readinto_obj, 1, pyb_spi_readinto); - -STATIC mp_obj_t pyb_spi_write_readinto (mp_obj_t self, mp_obj_t writebuf, mp_obj_t readbuf) { - // get buffers to write from/read to - mp_buffer_info_t bufinfo_write; - uint8_t data_send[1]; - mp_buffer_info_t bufinfo_read; - - if (writebuf == readbuf) { - // same object for writing and reading, it must be a r/w buffer - mp_get_buffer_raise(writebuf, &bufinfo_write, MP_BUFFER_RW); - bufinfo_read = bufinfo_write; - } else { - // get the buffer to write from - pyb_buf_get_for_send(writebuf, &bufinfo_write, data_send); - - // get the read buffer - mp_get_buffer_raise(readbuf, &bufinfo_read, MP_BUFFER_WRITE); - if (bufinfo_read.len != bufinfo_write.len) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - } - - // send and receive - pybspi_transfer(self, (const char *)bufinfo_write.buf, bufinfo_read.buf, bufinfo_write.len, NULL); - - // return the number of transferred bytes - return mp_obj_new_int(bufinfo_write.len); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_3(pyb_spi_write_readinto_obj, pyb_spi_write_readinto); - -STATIC const mp_rom_map_elem_t pyb_spi_locals_dict_table[] = { - // instance methods - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_spi_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_spi_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&pyb_spi_write_obj) }, - { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&pyb_spi_read_obj) }, - { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&pyb_spi_readinto_obj) }, - { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&pyb_spi_write_readinto_obj) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_MSB), MP_ROM_INT(PYBSPI_FIRST_BIT_MSB) }, -}; - -STATIC MP_DEFINE_CONST_DICT(pyb_spi_locals_dict, pyb_spi_locals_dict_table); - -const mp_obj_type_t pyb_spi_type = { - { &mp_type_type }, - .name = MP_QSTR_SPI, - .print = pyb_spi_print, - .make_new = pyb_spi_make_new, - .locals_dict = (mp_obj_t)&pyb_spi_locals_dict, -}; diff --git a/cc3200/mods/pybspi.h b/cc3200/mods/pybspi.h deleted file mode 100644 index b0fce8870..000000000 --- a/cc3200/mods/pybspi.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBSPI_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H - -extern const mp_obj_type_t pyb_spi_type; - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBSPI_H diff --git a/cc3200/mods/pybtimer.c b/cc3200/mods/pybtimer.c deleted file mode 100644 index f3a12c5e7..000000000 --- a/cc3200/mods/pybtimer.c +++ /dev/null @@ -1,735 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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 <stdio.h> -#include <string.h> - -#include "py/mpconfig.h" -#include "py/obj.h" -#include "py/nlr.h" -#include "py/runtime.h" -#include "py/gc.h" -#include "py/mperrno.h" -#include "py/mphal.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "inc/hw_timer.h" -#include "rom_map.h" -#include "interrupt.h" -#include "prcm.h" -#include "timer.h" -#include "pin.h" -#include "pybtimer.h" -#include "pybpin.h" -#include "pins.h" -#include "mpirq.h" -#include "pybsleep.h" -#include "mpexception.h" - - -/// \moduleref pyb -/// \class Timer - generate periodic events, count events, and create PWM signals. -/// -/// Each timer consists of a counter that counts up at a certain rate. The rate -/// at which it counts is the peripheral clock frequency (in Hz) divided by the -/// timer prescaler. When the counter reaches the timer period it triggers an -/// event, and the counter resets back to zero. By using the irq method, -/// the timer event can call a Python function. - -/****************************************************************************** - DECLARE PRIVATE CONSTANTS - ******************************************************************************/ -#define PYBTIMER_NUM_TIMERS (4) -#define PYBTIMER_POLARITY_POS (0x01) -#define PYBTIMER_POLARITY_NEG (0x02) - -#define PYBTIMER_TIMEOUT_TRIGGER (0x01) -#define PYBTIMER_MATCH_TRIGGER (0x02) - -#define PYBTIMER_SRC_FREQ_HZ HAL_FCPU_HZ - -/****************************************************************************** - DEFINE PRIVATE TYPES - ******************************************************************************/ -typedef struct _pyb_timer_obj_t { - mp_obj_base_t base; - uint32_t timer; - uint32_t config; - uint16_t irq_trigger; - uint16_t irq_flags; - uint8_t peripheral; - uint8_t id; -} pyb_timer_obj_t; - -typedef struct _pyb_timer_channel_obj_t { - mp_obj_base_t base; - struct _pyb_timer_obj_t *timer; - uint32_t frequency; - uint32_t period; - uint16_t channel; - uint16_t duty_cycle; - uint8_t polarity; -} pyb_timer_channel_obj_t; - -/****************************************************************************** - DEFINE PRIVATE DATA - ******************************************************************************/ -STATIC const mp_irq_methods_t pyb_timer_channel_irq_methods; -STATIC pyb_timer_obj_t pyb_timer_obj[PYBTIMER_NUM_TIMERS] = {{.timer = TIMERA0_BASE, .peripheral = PRCM_TIMERA0}, - {.timer = TIMERA1_BASE, .peripheral = PRCM_TIMERA1}, - {.timer = TIMERA2_BASE, .peripheral = PRCM_TIMERA2}, - {.timer = TIMERA3_BASE, .peripheral = PRCM_TIMERA3}}; -STATIC const mp_obj_type_t pyb_timer_channel_type; -STATIC const mp_obj_t pyb_timer_pwm_pin[8] = {&pin_GP24, MP_OBJ_NULL, &pin_GP25, MP_OBJ_NULL, MP_OBJ_NULL, &pin_GP9, &pin_GP10, &pin_GP11}; - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC mp_obj_t pyb_timer_channel_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args); -STATIC void timer_disable (pyb_timer_obj_t *tim); -STATIC void timer_channel_init (pyb_timer_channel_obj_t *ch); -STATIC void TIMER0AIntHandler(void); -STATIC void TIMER0BIntHandler(void); -STATIC void TIMER1AIntHandler(void); -STATIC void TIMER1BIntHandler(void); -STATIC void TIMER2AIntHandler(void); -STATIC void TIMER2BIntHandler(void); -STATIC void TIMER3AIntHandler(void); -STATIC void TIMER3BIntHandler(void); - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -void timer_init0 (void) { - mp_obj_list_init(&MP_STATE_PORT(pyb_timer_channel_obj_list), 0); -} - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void pyb_timer_channel_irq_enable (mp_obj_t self_in) { - pyb_timer_channel_obj_t *self = self_in; - MAP_TimerIntClear(self->timer->timer, self->timer->irq_trigger & self->channel); - MAP_TimerIntEnable(self->timer->timer, self->timer->irq_trigger & self->channel); -} - -STATIC void pyb_timer_channel_irq_disable (mp_obj_t self_in) { - pyb_timer_channel_obj_t *self = self_in; - MAP_TimerIntDisable(self->timer->timer, self->timer->irq_trigger & self->channel); -} - -STATIC int pyb_timer_channel_irq_flags (mp_obj_t self_in) { - pyb_timer_channel_obj_t *self = self_in; - return self->timer->irq_flags; -} - -STATIC pyb_timer_channel_obj_t *pyb_timer_channel_find (uint32_t timer, uint16_t channel_n) { - for (mp_uint_t i = 0; i < MP_STATE_PORT(pyb_timer_channel_obj_list).len; i++) { - pyb_timer_channel_obj_t *ch = ((pyb_timer_channel_obj_t *)(MP_STATE_PORT(pyb_timer_channel_obj_list).items[i])); - // any 32-bit timer must be matched by any of its 16-bit versions - if (ch->timer->timer == timer && ((ch->channel & TIMER_A) == channel_n || (ch->channel & TIMER_B) == channel_n)) { - return ch; - } - } - return MP_OBJ_NULL; -} - -STATIC void pyb_timer_channel_remove (pyb_timer_channel_obj_t *ch) { - pyb_timer_channel_obj_t *channel; - if ((channel = pyb_timer_channel_find(ch->timer->timer, ch->channel))) { - mp_obj_list_remove(&MP_STATE_PORT(pyb_timer_channel_obj_list), channel); - // unregister it with the sleep module - pyb_sleep_remove((const mp_obj_t)channel); - } -} - -STATIC void pyb_timer_channel_add (pyb_timer_channel_obj_t *ch) { - // remove it in case it already exists - pyb_timer_channel_remove(ch); - mp_obj_list_append(&MP_STATE_PORT(pyb_timer_channel_obj_list), ch); - // register it with the sleep module - pyb_sleep_add((const mp_obj_t)ch, (WakeUpCB_t)timer_channel_init); -} - -STATIC void timer_disable (pyb_timer_obj_t *tim) { - // disable all timers and it's interrupts - MAP_TimerDisable(tim->timer, TIMER_A | TIMER_B); - MAP_TimerIntDisable(tim->timer, tim->irq_trigger); - MAP_TimerIntClear(tim->timer, tim->irq_trigger); - pyb_timer_channel_obj_t *ch; - // disable its channels - if ((ch = pyb_timer_channel_find (tim->timer, TIMER_A))) { - pyb_sleep_remove(ch); - } - if ((ch = pyb_timer_channel_find (tim->timer, TIMER_B))) { - pyb_sleep_remove(ch); - } - MAP_PRCMPeripheralClkDisable(tim->peripheral, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); -} - -// computes prescaler period and match value so timer triggers at freq-Hz -STATIC uint32_t compute_prescaler_period_and_match_value(pyb_timer_channel_obj_t *ch, uint32_t *period_out, uint32_t *match_out) { - uint32_t maxcount = (ch->channel == (TIMER_A | TIMER_B)) ? 0xFFFFFFFF : 0xFFFF; - uint32_t prescaler; - uint32_t period_c = (ch->frequency > 0) ? PYBTIMER_SRC_FREQ_HZ / ch->frequency : ((PYBTIMER_SRC_FREQ_HZ / 1000000) * ch->period); - - period_c = MAX(1, period_c) - 1; - if (period_c == 0) { - goto error; - } - - prescaler = period_c >> 16; // The prescaler is an extension of the timer counter - *period_out = period_c; - - if (prescaler > 0xFF && maxcount == 0xFFFF) { - goto error; - } - // check limit values for the duty cycle - if (ch->duty_cycle == 0) { - *match_out = period_c - 1; - } else { - if (period_c > 0xFFFF) { - uint32_t match = (period_c * 100) / 10000; - *match_out = period_c - ((match * ch->duty_cycle) / 100); - } else { - *match_out = period_c - ((period_c * ch->duty_cycle) / 10000); - } - } - return prescaler; - -error: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -STATIC void timer_init (pyb_timer_obj_t *tim) { - MAP_PRCMPeripheralClkEnable(tim->peripheral, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - MAP_PRCMPeripheralReset(tim->peripheral); - MAP_TimerConfigure(tim->timer, tim->config); -} - -STATIC void timer_channel_init (pyb_timer_channel_obj_t *ch) { - // calculate the period, the prescaler and the match value - uint32_t period_c; - uint32_t match; - uint32_t prescaler = compute_prescaler_period_and_match_value(ch, &period_c, &match); - - // set the prescaler - MAP_TimerPrescaleSet(ch->timer->timer, ch->channel, (prescaler < 0xFF) ? prescaler : 0); - - // set the load value - MAP_TimerLoadSet(ch->timer->timer, ch->channel, period_c); - - // configure the pwm if we are in such mode - if ((ch->timer->config & 0x0F) == TIMER_CFG_A_PWM) { - // invert the timer output if required - MAP_TimerControlLevel(ch->timer->timer, ch->channel, (ch->polarity == PYBTIMER_POLARITY_NEG) ? true : false); - // set the match value (which is simply the duty cycle translated to ticks) - MAP_TimerMatchSet(ch->timer->timer, ch->channel, match); - MAP_TimerPrescaleMatchSet(ch->timer->timer, ch->channel, match >> 16); - } - -#ifdef DEBUG - // stall the timer when the processor is halted while debugging - MAP_TimerControlStall(ch->timer->timer, ch->channel, true); -#endif - - // now enable the timer channel - MAP_TimerEnable(ch->timer->timer, ch->channel); -} - -/******************************************************************************/ -/* MicroPython bindings */ - -STATIC void pyb_timer_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_timer_obj_t *tim = self_in; - uint32_t mode = tim->config & 0xFF; - - // timer mode - qstr mode_qst = MP_QSTR_PWM; - switch(mode) { - case TIMER_CFG_A_ONE_SHOT_UP: - mode_qst = MP_QSTR_ONE_SHOT; - break; - case TIMER_CFG_A_PERIODIC_UP: - mode_qst = MP_QSTR_PERIODIC; - break; - default: - break; - } - mp_printf(print, "Timer(%u, mode=Timer.%q)", tim->id, mode_qst); -} - -STATIC mp_obj_t pyb_timer_init_helper(pyb_timer_obj_t *tim, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - static const mp_arg_t allowed_args[] = { - { MP_QSTR_mode, MP_ARG_REQUIRED | MP_ARG_INT, }, - { MP_QSTR_width, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 16} }, - }; - - // 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); - - // check the mode - uint32_t _mode = args[0].u_int; - if (_mode != TIMER_CFG_A_ONE_SHOT_UP && _mode != TIMER_CFG_A_PERIODIC_UP && _mode != TIMER_CFG_A_PWM) { - goto error; - } - - // check the width - if (args[1].u_int != 16 && args[1].u_int != 32) { - goto error; - } - bool is16bit = (args[1].u_int == 16); - - if (!is16bit && _mode == TIMER_CFG_A_PWM) { - // 32-bit mode is only available when in free running modes - goto error; - } - tim->config = is16bit ? ((_mode | (_mode << 8)) | TIMER_CFG_SPLIT_PAIR) : _mode; - - timer_init(tim); - // register it with the sleep module - pyb_sleep_add ((const mp_obj_t)tim, (WakeUpCB_t)timer_init); - - return mp_const_none; - -error: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -STATIC mp_obj_t pyb_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, 1, MP_OBJ_FUN_ARGS_MAX, true); - - // create a new Timer object - int32_t timer_idx = mp_obj_get_int(args[0]); - if (timer_idx < 0 || timer_idx > (PYBTIMER_NUM_TIMERS - 1)) { - mp_raise_OSError(MP_ENODEV); - } - - pyb_timer_obj_t *tim = &pyb_timer_obj[timer_idx]; - tim->base.type = &pyb_timer_type; - tim->id = timer_idx; - - if (n_args > 1 || n_kw > 0) { - // start the peripheral - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); - pyb_timer_init_helper(tim, n_args - 1, args + 1, &kw_args); - } - return (mp_obj_t)tim; -} - -STATIC mp_obj_t pyb_timer_init(size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - return pyb_timer_init_helper(args[0], n_args - 1, args + 1, kw_args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_init_obj, 1, pyb_timer_init); - -STATIC mp_obj_t pyb_timer_deinit(mp_obj_t self_in) { - pyb_timer_obj_t *self = self_in; - timer_disable(self); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_timer_deinit_obj, pyb_timer_deinit); - -STATIC mp_obj_t pyb_timer_channel(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - static const mp_arg_t allowed_args[] = { - { MP_QSTR_freq, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_period, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = PYBTIMER_POLARITY_POS} }, - { MP_QSTR_duty_cycle, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, - }; - - pyb_timer_obj_t *tim = pos_args[0]; - mp_int_t channel_n = mp_obj_get_int(pos_args[1]); - - // verify that the timer has been already initialized - if (!tim->config) { - mp_raise_OSError(MP_EPERM); - } - if (channel_n != TIMER_A && channel_n != TIMER_B && channel_n != (TIMER_A | TIMER_B)) { - // invalid channel - goto error; - } - if (channel_n == (TIMER_A | TIMER_B) && (tim->config & TIMER_CFG_SPLIT_PAIR)) { - // 32-bit channel selected when the timer is in 16-bit mode - goto error; - } - - // if only the channel number is given return the previously - // allocated channel (or None if no previous channel) - if (n_args == 2 && kw_args->used == 0) { - pyb_timer_channel_obj_t *ch; - if ((ch = pyb_timer_channel_find(tim->timer, channel_n))) { - return ch; - } - return mp_const_none; - } - - // parse the arguments - 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); - - // throw an exception if both frequency and period are given - if (args[0].u_int != 0 && args[1].u_int != 0) { - goto error; - } - // check that at least one of them has a valid value - if (args[0].u_int <= 0 && args[1].u_int <= 0) { - goto error; - } - // check that the polarity is not 'both' in pwm mode - if ((tim->config & TIMER_A) == TIMER_CFG_A_PWM && args[2].u_int == (PYBTIMER_POLARITY_POS | PYBTIMER_POLARITY_NEG)) { - goto error; - } - - // allocate a new timer channel - pyb_timer_channel_obj_t *ch = m_new_obj(pyb_timer_channel_obj_t); - ch->base.type = &pyb_timer_channel_type; - ch->timer = tim; - ch->channel = channel_n; - - // get the frequency the polarity and the duty cycle - ch->frequency = args[0].u_int; - ch->period = args[1].u_int; - ch->polarity = args[2].u_int; - ch->duty_cycle = MIN(10000, MAX(0, args[3].u_int)); - - timer_channel_init(ch); - - // assign the pin - if ((ch->timer->config & 0x0F) == TIMER_CFG_A_PWM) { - uint32_t ch_idx = (ch->channel == TIMER_A) ? 0 : 1; - // use the default pin if available - mp_obj_t pin_o = (mp_obj_t)pyb_timer_pwm_pin[(ch->timer->id * 2) + ch_idx]; - if (pin_o != MP_OBJ_NULL) { - pin_obj_t *pin = pin_find(pin_o); - pin_config (pin, pin_find_af_index(pin, PIN_FN_TIM, ch->timer->id, PIN_TYPE_TIM_PWM), - 0, PIN_TYPE_STD, -1, PIN_STRENGTH_4MA); - } - } - - // add the timer to the list - pyb_timer_channel_add(ch); - - return ch; - -error: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_obj, 2, pyb_timer_channel); - -STATIC const mp_rom_map_elem_t pyb_timer_locals_dict_table[] = { - // instance methods - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_timer_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_timer_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_channel), MP_ROM_PTR(&pyb_timer_channel_obj) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_A), MP_ROM_INT(TIMER_A) }, - { MP_ROM_QSTR(MP_QSTR_B), MP_ROM_INT(TIMER_B) }, - { MP_ROM_QSTR(MP_QSTR_ONE_SHOT), MP_ROM_INT(TIMER_CFG_A_ONE_SHOT_UP) }, - { MP_ROM_QSTR(MP_QSTR_PERIODIC), MP_ROM_INT(TIMER_CFG_A_PERIODIC_UP) }, - { MP_ROM_QSTR(MP_QSTR_PWM), MP_ROM_INT(TIMER_CFG_A_PWM) }, - { MP_ROM_QSTR(MP_QSTR_POSITIVE), MP_ROM_INT(PYBTIMER_POLARITY_POS) }, - { MP_ROM_QSTR(MP_QSTR_NEGATIVE), MP_ROM_INT(PYBTIMER_POLARITY_NEG) }, - { MP_ROM_QSTR(MP_QSTR_TIMEOUT), MP_ROM_INT(PYBTIMER_TIMEOUT_TRIGGER) }, - { MP_ROM_QSTR(MP_QSTR_MATCH), MP_ROM_INT(PYBTIMER_MATCH_TRIGGER) }, -}; -STATIC MP_DEFINE_CONST_DICT(pyb_timer_locals_dict, pyb_timer_locals_dict_table); - -const mp_obj_type_t pyb_timer_type = { - { &mp_type_type }, - .name = MP_QSTR_Timer, - .print = pyb_timer_print, - .make_new = pyb_timer_make_new, - .locals_dict = (mp_obj_t)&pyb_timer_locals_dict, -}; - -STATIC const mp_irq_methods_t pyb_timer_channel_irq_methods = { - .init = pyb_timer_channel_irq, - .enable = pyb_timer_channel_irq_enable, - .disable = pyb_timer_channel_irq_disable, - .flags = pyb_timer_channel_irq_flags, -}; - -STATIC void TIMERGenericIntHandler(uint32_t timer, uint16_t channel) { - pyb_timer_channel_obj_t *self; - uint32_t status; - if ((self = pyb_timer_channel_find(timer, channel))) { - status = MAP_TimerIntStatus(self->timer->timer, true) & self->channel; - MAP_TimerIntClear(self->timer->timer, status); - mp_irq_handler(mp_irq_find(self)); - } -} - -STATIC void TIMER0AIntHandler(void) { - TIMERGenericIntHandler(TIMERA0_BASE, TIMER_A); -} - -STATIC void TIMER0BIntHandler(void) { - TIMERGenericIntHandler(TIMERA0_BASE, TIMER_B); -} - -STATIC void TIMER1AIntHandler(void) { - TIMERGenericIntHandler(TIMERA1_BASE, TIMER_A); -} - -STATIC void TIMER1BIntHandler(void) { - TIMERGenericIntHandler(TIMERA1_BASE, TIMER_B); -} - -STATIC void TIMER2AIntHandler(void) { - TIMERGenericIntHandler(TIMERA2_BASE, TIMER_A); -} - -STATIC void TIMER2BIntHandler(void) { - TIMERGenericIntHandler(TIMERA2_BASE, TIMER_B); -} - -STATIC void TIMER3AIntHandler(void) { - TIMERGenericIntHandler(TIMERA3_BASE, TIMER_A); -} - -STATIC void TIMER3BIntHandler(void) { - TIMERGenericIntHandler(TIMERA3_BASE, TIMER_B); -} - -STATIC void pyb_timer_channel_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_timer_channel_obj_t *ch = self_in; - char *ch_id = "AB"; - // timer channel - if (ch->channel == TIMER_A) { - ch_id = "A"; - } else if (ch->channel == TIMER_B) { - ch_id = "B"; - } - - mp_printf(print, "timer.channel(Timer.%s, %q=%u", ch_id, MP_QSTR_freq, ch->frequency); - - uint32_t mode = ch->timer->config & 0xFF; - if (mode == TIMER_CFG_A_PWM) { - mp_printf(print, ", %q=Timer.", MP_QSTR_polarity); - switch (ch->polarity) { - case PYBTIMER_POLARITY_POS: - mp_printf(print, "POSITIVE"); - break; - case PYBTIMER_POLARITY_NEG: - mp_printf(print, "NEGATIVE"); - break; - default: - mp_printf(print, "BOTH"); - break; - } - mp_printf(print, ", %q=%u.%02u", MP_QSTR_duty_cycle, ch->duty_cycle / 100, ch->duty_cycle % 100); - } - mp_printf(print, ")"); -} - -STATIC mp_obj_t pyb_timer_channel_freq(size_t n_args, const mp_obj_t *args) { - pyb_timer_channel_obj_t *ch = args[0]; - if (n_args == 1) { - // get - return mp_obj_new_int(ch->frequency); - } else { - // set - int32_t _frequency = mp_obj_get_int(args[1]); - if (_frequency <= 0) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - ch->frequency = _frequency; - ch->period = 1000000 / _frequency; - timer_channel_init(ch); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_freq_obj, 1, 2, pyb_timer_channel_freq); - -STATIC mp_obj_t pyb_timer_channel_period(size_t n_args, const mp_obj_t *args) { - pyb_timer_channel_obj_t *ch = args[0]; - if (n_args == 1) { - // get - return mp_obj_new_int(ch->period); - } else { - // set - int32_t _period = mp_obj_get_int(args[1]); - if (_period <= 0) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - ch->period = _period; - ch->frequency = 1000000 / _period; - timer_channel_init(ch); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_period_obj, 1, 2, pyb_timer_channel_period); - -STATIC mp_obj_t pyb_timer_channel_duty_cycle(size_t n_args, const mp_obj_t *args) { - pyb_timer_channel_obj_t *ch = args[0]; - if (n_args == 1) { - // get - return mp_obj_new_int(ch->duty_cycle); - } else { - // duty cycle must be converted from percentage to ticks - // calculate the period, the prescaler and the match value - uint32_t period_c; - uint32_t match; - ch->duty_cycle = MIN(10000, MAX(0, mp_obj_get_int(args[1]))); - compute_prescaler_period_and_match_value(ch, &period_c, &match); - if (n_args == 3) { - // set the new polarity if requested - ch->polarity = mp_obj_get_int(args[2]); - MAP_TimerControlLevel(ch->timer->timer, ch->channel, (ch->polarity == PYBTIMER_POLARITY_NEG) ? true : false); - } - MAP_TimerMatchSet(ch->timer->timer, ch->channel, match); - MAP_TimerPrescaleMatchSet(ch->timer->timer, ch->channel, match >> 16); - return mp_const_none; - } -} -STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(pyb_timer_channel_duty_cycle_obj, 1, 3, pyb_timer_channel_duty_cycle); - -STATIC mp_obj_t pyb_timer_channel_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[mp_irq_INIT_NUM_ARGS]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, mp_irq_INIT_NUM_ARGS, mp_irq_init_args, args); - pyb_timer_channel_obj_t *ch = pos_args[0]; - - // convert the priority to the correct value - uint priority = mp_irq_translate_priority (args[1].u_int); - - // validate the power mode - uint8_t pwrmode = (args[3].u_obj == mp_const_none) ? PYB_PWR_MODE_ACTIVE : mp_obj_get_int(args[3].u_obj); - if (pwrmode != PYB_PWR_MODE_ACTIVE) { - goto invalid_args; - } - - // get the trigger - uint trigger = mp_obj_get_int(args[0].u_obj); - - // disable the callback first - pyb_timer_channel_irq_disable(ch); - - uint8_t shift = (ch->channel == TIMER_B) ? 8 : 0; - uint32_t _config = (ch->channel == TIMER_B) ? ((ch->timer->config & TIMER_B) >> 8) : (ch->timer->config & TIMER_A); - switch (_config) { - case TIMER_CFG_A_ONE_SHOT_UP: - case TIMER_CFG_A_PERIODIC_UP: - ch->timer->irq_trigger |= TIMER_TIMA_TIMEOUT << shift; - if (trigger != PYBTIMER_TIMEOUT_TRIGGER) { - goto invalid_args; - } - break; - case TIMER_CFG_A_PWM: - // special case for the PWM match interrupt - ch->timer->irq_trigger |= ((ch->channel & TIMER_A) == TIMER_A) ? TIMER_TIMA_MATCH : TIMER_TIMB_MATCH; - if (trigger != PYBTIMER_MATCH_TRIGGER) { - goto invalid_args; - } - break; - default: - break; - } - // special case for a 32-bit timer - if (ch->channel == (TIMER_A | TIMER_B)) { - ch->timer->irq_trigger |= (ch->timer->irq_trigger << 8); - } - - void (*pfnHandler)(void); - uint32_t intregister; - switch (ch->timer->timer) { - case TIMERA0_BASE: - if (ch->channel == TIMER_B) { - pfnHandler = &TIMER0BIntHandler; - intregister = INT_TIMERA0B; - } else { - pfnHandler = &TIMER0AIntHandler; - intregister = INT_TIMERA0A; - } - break; - case TIMERA1_BASE: - if (ch->channel == TIMER_B) { - pfnHandler = &TIMER1BIntHandler; - intregister = INT_TIMERA1B; - } else { - pfnHandler = &TIMER1AIntHandler; - intregister = INT_TIMERA1A; - } - break; - case TIMERA2_BASE: - if (ch->channel == TIMER_B) { - pfnHandler = &TIMER2BIntHandler; - intregister = INT_TIMERA2B; - } else { - pfnHandler = &TIMER2AIntHandler; - intregister = INT_TIMERA2A; - } - break; - default: - if (ch->channel == TIMER_B) { - pfnHandler = &TIMER3BIntHandler; - intregister = INT_TIMERA3B; - } else { - pfnHandler = &TIMER3AIntHandler; - intregister = INT_TIMERA3A; - } - break; - } - - // register the interrupt and configure the priority - MAP_IntPrioritySet(intregister, priority); - MAP_TimerIntRegister(ch->timer->timer, ch->channel, pfnHandler); - - // create the callback - mp_obj_t _irq = mp_irq_new (ch, args[2].u_obj, &pyb_timer_channel_irq_methods); - - // enable the callback before returning - pyb_timer_channel_irq_enable(ch); - - return _irq; - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_timer_channel_irq_obj, 1, pyb_timer_channel_irq); - -STATIC const mp_rom_map_elem_t pyb_timer_channel_locals_dict_table[] = { - // instance methods - { MP_ROM_QSTR(MP_QSTR_freq), MP_ROM_PTR(&pyb_timer_channel_freq_obj) }, - { MP_ROM_QSTR(MP_QSTR_period), MP_ROM_PTR(&pyb_timer_channel_period_obj) }, - { MP_ROM_QSTR(MP_QSTR_duty_cycle), MP_ROM_PTR(&pyb_timer_channel_duty_cycle_obj) }, - { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pyb_timer_channel_irq_obj) }, -}; -STATIC MP_DEFINE_CONST_DICT(pyb_timer_channel_locals_dict, pyb_timer_channel_locals_dict_table); - -STATIC const mp_obj_type_t pyb_timer_channel_type = { - { &mp_type_type }, - .name = MP_QSTR_TimerChannel, - .print = pyb_timer_channel_print, - .locals_dict = (mp_obj_t)&pyb_timer_channel_locals_dict, -}; - diff --git a/cc3200/mods/pybtimer.h b/cc3200/mods/pybtimer.h deleted file mode 100644 index 0af0864ca..000000000 --- a/cc3200/mods/pybtimer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBTIMER_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H - -/****************************************************************************** - DECLARE EXPORTED DATA - ******************************************************************************/ -extern const mp_obj_type_t pyb_timer_type; - -/****************************************************************************** - DECLARE PUBLIC FUNCTIONS - ******************************************************************************/ -void timer_init0 (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBTIMER_H diff --git a/cc3200/mods/pybuart.c b/cc3200/mods/pybuart.c deleted file mode 100644 index 135e0f2a3..000000000 --- a/cc3200/mods/pybuart.c +++ /dev/null @@ -1,672 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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 <stdio.h> -#include <string.h> - -#include "py/mpconfig.h" -#include "py/obj.h" -#include "py/runtime.h" -#include "py/objlist.h" -#include "py/stream.h" -#include "py/mphal.h" -#include "lib/utils/interrupt_char.h" -#include "inc/hw_types.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "inc/hw_uart.h" -#include "rom_map.h" -#include "interrupt.h" -#include "prcm.h" -#include "uart.h" -#include "pybuart.h" -#include "mpirq.h" -#include "pybsleep.h" -#include "mpexception.h" -#include "py/mpstate.h" -#include "osi.h" -#include "utils.h" -#include "pin.h" -#include "pybpin.h" -#include "pins.h" -#include "moduos.h" - -/// \moduleref pyb -/// \class UART - duplex serial communication bus - -/****************************************************************************** - DEFINE CONSTANTS - *******-***********************************************************************/ -#define PYBUART_FRAME_TIME_US(baud) ((11 * 1000000) / baud) -#define PYBUART_2_FRAMES_TIME_US(baud) (PYBUART_FRAME_TIME_US(baud) * 2) -#define PYBUART_RX_TIMEOUT_US(baud) (PYBUART_2_FRAMES_TIME_US(baud) * 8) // we need at least characters in the FIFO - -#define PYBUART_TX_WAIT_US(baud) ((PYBUART_FRAME_TIME_US(baud)) + 1) -#define PYBUART_TX_MAX_TIMEOUT_MS (5) - -#define PYBUART_RX_BUFFER_LEN (256) - -// interrupt triggers -#define UART_TRIGGER_RX_ANY (0x01) -#define UART_TRIGGER_RX_HALF (0x02) -#define UART_TRIGGER_RX_FULL (0x04) -#define UART_TRIGGER_TX_DONE (0x08) - -/****************************************************************************** - DECLARE PRIVATE FUNCTIONS - ******************************************************************************/ -STATIC void uart_init (pyb_uart_obj_t *self); -STATIC bool uart_rx_wait (pyb_uart_obj_t *self); -STATIC void uart_check_init(pyb_uart_obj_t *self); -STATIC mp_obj_t uart_irq_new (pyb_uart_obj_t *self, byte trigger, mp_int_t priority, mp_obj_t handler); -STATIC void UARTGenericIntHandler(uint32_t uart_id); -STATIC void UART0IntHandler(void); -STATIC void UART1IntHandler(void); -STATIC void uart_irq_enable (mp_obj_t self_in); -STATIC void uart_irq_disable (mp_obj_t self_in); - -/****************************************************************************** - DEFINE PRIVATE TYPES - ******************************************************************************/ -struct _pyb_uart_obj_t { - mp_obj_base_t base; - pyb_uart_id_t uart_id; - uint reg; - uint baudrate; - uint config; - uint flowcontrol; - byte *read_buf; // read buffer pointer - volatile uint16_t read_buf_head; // indexes first empty slot - uint16_t read_buf_tail; // indexes first full slot (not full if equals head) - byte peripheral; - byte irq_trigger; - bool irq_enabled; - byte irq_flags; -}; - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC pyb_uart_obj_t pyb_uart_obj[PYB_NUM_UARTS] = { {.reg = UARTA0_BASE, .baudrate = 0, .read_buf = NULL, .peripheral = PRCM_UARTA0}, - {.reg = UARTA1_BASE, .baudrate = 0, .read_buf = NULL, .peripheral = PRCM_UARTA1} }; -STATIC const mp_irq_methods_t uart_irq_methods; - -STATIC const mp_obj_t pyb_uart_def_pin[PYB_NUM_UARTS][2] = { {&pin_GP1, &pin_GP2}, {&pin_GP3, &pin_GP4} }; - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -void uart_init0 (void) { - // save references of the UART objects, to prevent the read buffers from being trashed by the gc - MP_STATE_PORT(pyb_uart_objs)[0] = &pyb_uart_obj[0]; - MP_STATE_PORT(pyb_uart_objs)[1] = &pyb_uart_obj[1]; -} - -uint32_t uart_rx_any(pyb_uart_obj_t *self) { - if (self->read_buf_tail != self->read_buf_head) { - // buffering via irq - return (self->read_buf_head > self->read_buf_tail) ? self->read_buf_head - self->read_buf_tail : - PYBUART_RX_BUFFER_LEN - self->read_buf_tail + self->read_buf_head; - } - return MAP_UARTCharsAvail(self->reg) ? 1 : 0; -} - -int uart_rx_char(pyb_uart_obj_t *self) { - if (self->read_buf_tail != self->read_buf_head) { - // buffering via irq - int data = self->read_buf[self->read_buf_tail]; - self->read_buf_tail = (self->read_buf_tail + 1) % PYBUART_RX_BUFFER_LEN; - return data; - } else { - // no buffering - return MAP_UARTCharGetNonBlocking(self->reg); - } -} - -bool uart_tx_char(pyb_uart_obj_t *self, int c) { - uint32_t timeout = 0; - while (!MAP_UARTCharPutNonBlocking(self->reg, c)) { - if (timeout++ > ((PYBUART_TX_MAX_TIMEOUT_MS * 1000) / PYBUART_TX_WAIT_US(self->baudrate))) { - return false; - } - UtilsDelay(UTILS_DELAY_US_TO_COUNT(PYBUART_TX_WAIT_US(self->baudrate))); - } - return true; -} - -bool uart_tx_strn(pyb_uart_obj_t *self, const char *str, uint len) { - for (const char *top = str + len; str < top; str++) { - if (!uart_tx_char(self, *str)) { - return false; - } - } - return true; -} - -/****************************************************************************** - DEFINE PRIVATE FUNCTIONS - ******************************************************************************/ -// assumes init parameters have been set up correctly -STATIC void uart_init (pyb_uart_obj_t *self) { - // Enable the peripheral clock - MAP_PRCMPeripheralClkEnable(self->peripheral, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - - // Reset the uart - MAP_PRCMPeripheralReset(self->peripheral); - - // re-allocate the read buffer after resetting the uart (which automatically disables any irqs) - self->read_buf_head = 0; - self->read_buf_tail = 0; - self->read_buf = MP_OBJ_NULL; // free the read buffer before allocating again - self->read_buf = m_new(byte, PYBUART_RX_BUFFER_LEN); - - // Initialize the UART - MAP_UARTConfigSetExpClk(self->reg, MAP_PRCMPeripheralClockGet(self->peripheral), - self->baudrate, self->config); - - // Enable the FIFO - MAP_UARTFIFOEnable(self->reg); - - // Configure the FIFO interrupt levels - MAP_UARTFIFOLevelSet(self->reg, UART_FIFO_TX4_8, UART_FIFO_RX4_8); - - // Configure the flow control mode - UARTFlowControlSet(self->reg, self->flowcontrol); -} - -// Waits at most timeout microseconds for at least 1 char to become ready for -// reading (from buf or for direct reading). -// Returns true if something available, false if not. -STATIC bool uart_rx_wait (pyb_uart_obj_t *self) { - int timeout = PYBUART_RX_TIMEOUT_US(self->baudrate); - for ( ; ; ) { - if (uart_rx_any(self)) { - return true; // we have at least 1 char ready for reading - } - if (timeout > 0) { - UtilsDelay(UTILS_DELAY_US_TO_COUNT(1)); - timeout--; - } - else { - return false; - } - } -} - -STATIC mp_obj_t uart_irq_new (pyb_uart_obj_t *self, byte trigger, mp_int_t priority, mp_obj_t handler) { - // disable the uart interrupts before updating anything - uart_irq_disable (self); - - if (self->uart_id == PYB_UART_0) { - MAP_IntPrioritySet(INT_UARTA0, priority); - MAP_UARTIntRegister(self->reg, UART0IntHandler); - } else { - MAP_IntPrioritySet(INT_UARTA1, priority); - MAP_UARTIntRegister(self->reg, UART1IntHandler); - } - - // create the callback - mp_obj_t _irq = mp_irq_new ((mp_obj_t)self, handler, &uart_irq_methods); - - // enable the interrupts now - self->irq_trigger = trigger; - uart_irq_enable (self); - return _irq; -} - -STATIC void UARTGenericIntHandler(uint32_t uart_id) { - pyb_uart_obj_t *self; - uint32_t status; - - self = &pyb_uart_obj[uart_id]; - status = MAP_UARTIntStatus(self->reg, true); - // receive interrupt - if (status & (UART_INT_RX | UART_INT_RT)) { - // set the flags - self->irq_flags = UART_TRIGGER_RX_ANY; - MAP_UARTIntClear(self->reg, UART_INT_RX | UART_INT_RT); - while (UARTCharsAvail(self->reg)) { - int data = MAP_UARTCharGetNonBlocking(self->reg); - if (MP_STATE_PORT(os_term_dup_obj) && MP_STATE_PORT(os_term_dup_obj)->stream_o == self && data == mp_interrupt_char) { - // raise an exception when interrupts are finished - mp_keyboard_interrupt(); - } else { // there's always a read buffer available - uint16_t next_head = (self->read_buf_head + 1) % PYBUART_RX_BUFFER_LEN; - if (next_head != self->read_buf_tail) { - // only store data if room in buf - self->read_buf[self->read_buf_head] = data; - self->read_buf_head = next_head; - } - } - } - } - - // check the flags to see if the user handler should be called - if ((self->irq_trigger & self->irq_flags) && self->irq_enabled) { - // call the user defined handler - mp_irq_handler(mp_irq_find(self)); - } - - // clear the flags - self->irq_flags = 0; -} - -STATIC void uart_check_init(pyb_uart_obj_t *self) { - // not initialized - if (!self->baudrate) { - mp_raise_OSError(MP_EPERM); - } -} - -STATIC void UART0IntHandler(void) { - UARTGenericIntHandler(0); -} - -STATIC void UART1IntHandler(void) { - UARTGenericIntHandler(1); -} - -STATIC void uart_irq_enable (mp_obj_t self_in) { - pyb_uart_obj_t *self = self_in; - // check for any of the rx interrupt types - if (self->irq_trigger & (UART_TRIGGER_RX_ANY | UART_TRIGGER_RX_HALF | UART_TRIGGER_RX_FULL)) { - MAP_UARTIntClear(self->reg, UART_INT_RX | UART_INT_RT); - MAP_UARTIntEnable(self->reg, UART_INT_RX | UART_INT_RT); - } - self->irq_enabled = true; -} - -STATIC void uart_irq_disable (mp_obj_t self_in) { - pyb_uart_obj_t *self = self_in; - self->irq_enabled = false; -} - -STATIC int uart_irq_flags (mp_obj_t self_in) { - pyb_uart_obj_t *self = self_in; - return self->irq_flags; -} - -/******************************************************************************/ -/* MicroPython bindings */ - -STATIC void pyb_uart_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - pyb_uart_obj_t *self = self_in; - if (self->baudrate > 0) { - mp_printf(print, "UART(%u, baudrate=%u, bits=", self->uart_id, self->baudrate); - switch (self->config & UART_CONFIG_WLEN_MASK) { - case UART_CONFIG_WLEN_5: - mp_print_str(print, "5"); - break; - case UART_CONFIG_WLEN_6: - mp_print_str(print, "6"); - break; - case UART_CONFIG_WLEN_7: - mp_print_str(print, "7"); - break; - case UART_CONFIG_WLEN_8: - mp_print_str(print, "8"); - break; - default: - break; - } - if ((self->config & UART_CONFIG_PAR_MASK) == UART_CONFIG_PAR_NONE) { - mp_print_str(print, ", parity=None"); - } else { - mp_printf(print, ", parity=UART.%q", (self->config & UART_CONFIG_PAR_MASK) == UART_CONFIG_PAR_EVEN ? MP_QSTR_EVEN : MP_QSTR_ODD); - } - mp_printf(print, ", stop=%u)", (self->config & UART_CONFIG_STOP_MASK) == UART_CONFIG_STOP_ONE ? 1 : 2); - } - else { - mp_printf(print, "UART(%u)", self->uart_id); - } -} - -STATIC mp_obj_t pyb_uart_init_helper(pyb_uart_obj_t *self, const mp_arg_val_t *args) { - // get the baudrate - if (args[0].u_int <= 0) { - goto error; - } - uint baudrate = args[0].u_int; - uint config; - switch (args[1].u_int) { - case 5: - config = UART_CONFIG_WLEN_5; - break; - case 6: - config = UART_CONFIG_WLEN_6; - break; - case 7: - config = UART_CONFIG_WLEN_7; - break; - case 8: - config = UART_CONFIG_WLEN_8; - break; - default: - goto error; - break; - } - // parity - if (args[2].u_obj == mp_const_none) { - config |= UART_CONFIG_PAR_NONE; - } else { - uint parity = mp_obj_get_int(args[2].u_obj); - if (parity == 0) { - config |= UART_CONFIG_PAR_EVEN; - } else if (parity == 1) { - config |= UART_CONFIG_PAR_ODD; - } else { - goto error; - } - } - // stop bits - config |= (args[3].u_int == 1 ? UART_CONFIG_STOP_ONE : UART_CONFIG_STOP_TWO); - - // assign the pins - mp_obj_t pins_o = args[4].u_obj; - uint flowcontrol = UART_FLOWCONTROL_NONE; - if (pins_o != mp_const_none) { - mp_obj_t *pins; - size_t n_pins = 2; - if (pins_o == MP_OBJ_NULL) { - // use the default pins - pins = (mp_obj_t *)pyb_uart_def_pin[self->uart_id]; - } else { - mp_obj_get_array(pins_o, &n_pins, &pins); - if (n_pins != 2 && n_pins != 4) { - goto error; - } - if (n_pins == 4) { - if (pins[PIN_TYPE_UART_RTS] != mp_const_none && pins[PIN_TYPE_UART_RX] == mp_const_none) { - goto error; // RTS pin given in TX only mode - } else if (pins[PIN_TYPE_UART_CTS] != mp_const_none && pins[PIN_TYPE_UART_TX] == mp_const_none) { - goto error; // CTS pin given in RX only mode - } else { - if (pins[PIN_TYPE_UART_RTS] != mp_const_none) { - flowcontrol |= UART_FLOWCONTROL_RX; - } - if (pins[PIN_TYPE_UART_CTS] != mp_const_none) { - flowcontrol |= UART_FLOWCONTROL_TX; - } - } - } - } - pin_assign_pins_af (pins, n_pins, PIN_TYPE_STD_PU, PIN_FN_UART, self->uart_id); - } - - self->baudrate = baudrate; - self->config = config; - self->flowcontrol = flowcontrol; - - // initialize and enable the uart - uart_init (self); - // register it with the sleep module - pyb_sleep_add ((const mp_obj_t)self, (WakeUpCB_t)uart_init); - // enable the callback - uart_irq_new (self, UART_TRIGGER_RX_ANY, INT_PRIORITY_LVL_3, mp_const_none); - // disable the irq (from the user point of view) - uart_irq_disable(self); - - return mp_const_none; - -error: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} - -STATIC const mp_arg_t pyb_uart_init_args[] = { - { MP_QSTR_id, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 9600} }, - { MP_QSTR_bits, MP_ARG_INT, {.u_int = 8} }, - { MP_QSTR_parity, MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_stop, MP_ARG_INT, {.u_int = 1} }, - { MP_QSTR_pins, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, -}; -STATIC mp_obj_t pyb_uart_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // parse args - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_uart_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_uart_init_args, args); - - // work out the uart id - uint uart_id; - if (args[0].u_obj == MP_OBJ_NULL) { - if (args[5].u_obj != MP_OBJ_NULL) { - mp_obj_t *pins; - size_t n_pins = 2; - mp_obj_get_array(args[5].u_obj, &n_pins, &pins); - // check the Tx pin (or the Rx if Tx is None) - if (pins[0] == mp_const_none) { - uart_id = pin_find_peripheral_unit(pins[1], PIN_FN_UART, PIN_TYPE_UART_RX); - } else { - uart_id = pin_find_peripheral_unit(pins[0], PIN_FN_UART, PIN_TYPE_UART_TX); - } - } else { - // default id - uart_id = 0; - } - } else { - uart_id = mp_obj_get_int(args[0].u_obj); - } - - if (uart_id > PYB_UART_1) { - mp_raise_OSError(MP_ENODEV); - } - - // get the correct uart instance - pyb_uart_obj_t *self = &pyb_uart_obj[uart_id]; - self->base.type = &pyb_uart_type; - self->uart_id = uart_id; - - // start the peripheral - pyb_uart_init_helper(self, &args[1]); - - return self; -} - -STATIC mp_obj_t pyb_uart_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - // parse args - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_uart_init_args) - 1]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), &pyb_uart_init_args[1], args); - return pyb_uart_init_helper(pos_args[0], args); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_init_obj, 1, pyb_uart_init); - -STATIC mp_obj_t pyb_uart_deinit(mp_obj_t self_in) { - pyb_uart_obj_t *self = self_in; - - // unregister it with the sleep module - pyb_sleep_remove (self); - // invalidate the baudrate - self->baudrate = 0; - // free the read buffer - m_del(byte, self->read_buf, PYBUART_RX_BUFFER_LEN); - MAP_UARTIntDisable(self->reg, UART_INT_RX | UART_INT_RT); - MAP_UARTDisable(self->reg); - MAP_PRCMPeripheralClkDisable(self->peripheral, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_deinit_obj, pyb_uart_deinit); - -STATIC mp_obj_t pyb_uart_any(mp_obj_t self_in) { - pyb_uart_obj_t *self = self_in; - uart_check_init(self); - return mp_obj_new_int(uart_rx_any(self)); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_any_obj, pyb_uart_any); - -STATIC mp_obj_t pyb_uart_sendbreak(mp_obj_t self_in) { - pyb_uart_obj_t *self = self_in; - uart_check_init(self); - // send a break signal for at least 2 complete frames - MAP_UARTBreakCtl(self->reg, true); - UtilsDelay(UTILS_DELAY_US_TO_COUNT(PYBUART_2_FRAMES_TIME_US(self->baudrate))); - MAP_UARTBreakCtl(self->reg, false); - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_uart_sendbreak_obj, pyb_uart_sendbreak); - -/// \method irq(trigger, priority, handler, wake) -STATIC mp_obj_t pyb_uart_irq(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[mp_irq_INIT_NUM_ARGS]; - mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, mp_irq_INIT_NUM_ARGS, mp_irq_init_args, args); - - // check if any parameters were passed - pyb_uart_obj_t *self = pos_args[0]; - uart_check_init(self); - - // convert the priority to the correct value - uint priority = mp_irq_translate_priority (args[1].u_int); - - // check the power mode - uint8_t pwrmode = (args[3].u_obj == mp_const_none) ? PYB_PWR_MODE_ACTIVE : mp_obj_get_int(args[3].u_obj); - if (PYB_PWR_MODE_ACTIVE != pwrmode) { - goto invalid_args; - } - - // check the trigger - uint trigger = mp_obj_get_int(args[0].u_obj); - if (!trigger || trigger > (UART_TRIGGER_RX_ANY | UART_TRIGGER_RX_HALF | UART_TRIGGER_RX_FULL | UART_TRIGGER_TX_DONE)) { - goto invalid_args; - } - - // register a new callback - return uart_irq_new (self, trigger, priority, args[2].u_obj); - -invalid_args: - mp_raise_ValueError(mpexception_value_invalid_arguments); -} -STATIC MP_DEFINE_CONST_FUN_OBJ_KW(pyb_uart_irq_obj, 1, pyb_uart_irq); - -STATIC const mp_rom_map_elem_t pyb_uart_locals_dict_table[] = { - // instance methods - { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&pyb_uart_init_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pyb_uart_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(&pyb_uart_any_obj) }, - { MP_ROM_QSTR(MP_QSTR_sendbreak), MP_ROM_PTR(&pyb_uart_sendbreak_obj) }, - { MP_ROM_QSTR(MP_QSTR_irq), MP_ROM_PTR(&pyb_uart_irq_obj) }, - - /// \method read([nbytes]) - { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, - /// \method readline() - { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, - /// \method readinto(buf[, nbytes]) - { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, - /// \method write(buf) - { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, - - // class constants - { MP_ROM_QSTR(MP_QSTR_RX_ANY), MP_ROM_INT(UART_TRIGGER_RX_ANY) }, -}; - -STATIC MP_DEFINE_CONST_DICT(pyb_uart_locals_dict, pyb_uart_locals_dict_table); - -STATIC mp_uint_t pyb_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) { - pyb_uart_obj_t *self = self_in; - byte *buf = buf_in; - uart_check_init(self); - - // make sure we want at least 1 char - if (size == 0) { - return 0; - } - - // wait for first char to become available - if (!uart_rx_wait(self)) { - // return MP_EAGAIN error to indicate non-blocking (then read() method returns None) - *errcode = MP_EAGAIN; - return MP_STREAM_ERROR; - } - - // read the data - byte *orig_buf = buf; - for ( ; ; ) { - *buf++ = uart_rx_char(self); - if (--size == 0 || !uart_rx_wait(self)) { - // return number of bytes read - return buf - orig_buf; - } - } -} - -STATIC mp_uint_t pyb_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) { - pyb_uart_obj_t *self = self_in; - const char *buf = buf_in; - uart_check_init(self); - - // write the data - if (!uart_tx_strn(self, buf, size)) { - mp_raise_OSError(MP_EIO); - } - return size; -} - -STATIC mp_uint_t pyb_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { - pyb_uart_obj_t *self = self_in; - mp_uint_t ret; - uart_check_init(self); - - if (request == MP_STREAM_POLL) { - mp_uint_t flags = arg; - ret = 0; - if ((flags & MP_STREAM_POLL_RD) && uart_rx_any(self)) { - ret |= MP_STREAM_POLL_RD; - } - if ((flags & MP_STREAM_POLL_WR) && MAP_UARTSpaceAvail(self->reg)) { - 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 = pyb_uart_read, - .write = pyb_uart_write, - .ioctl = pyb_uart_ioctl, - .is_text = false, -}; - -STATIC const mp_irq_methods_t uart_irq_methods = { - .init = pyb_uart_irq, - .enable = uart_irq_enable, - .disable = uart_irq_disable, - .flags = uart_irq_flags -}; - -const mp_obj_type_t pyb_uart_type = { - { &mp_type_type }, - .name = MP_QSTR_UART, - .print = pyb_uart_print, - .make_new = pyb_uart_make_new, - .getiter = mp_identity_getiter, - .iternext = mp_stream_unbuffered_iter, - .protocol = &uart_stream_p, - .locals_dict = (mp_obj_t)&pyb_uart_locals_dict, -}; diff --git a/cc3200/mods/pybuart.h b/cc3200/mods/pybuart.h deleted file mode 100644 index d481242f1..000000000 --- a/cc3200/mods/pybuart.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2013, 2014 Damien P. George - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBUART_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBUART_H - -typedef enum { - PYB_UART_0 = 0, - PYB_UART_1 = 1, - PYB_NUM_UARTS -} pyb_uart_id_t; - -typedef struct _pyb_uart_obj_t pyb_uart_obj_t; -extern const mp_obj_type_t pyb_uart_type; - -void uart_init0(void); -uint32_t uart_rx_any(pyb_uart_obj_t *uart_obj); -int uart_rx_char(pyb_uart_obj_t *uart_obj); -bool uart_tx_char(pyb_uart_obj_t *self, int c); -bool uart_tx_strn(pyb_uart_obj_t *uart_obj, const char *str, uint len); - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBUART_H diff --git a/cc3200/mods/pybwdt.c b/cc3200/mods/pybwdt.c deleted file mode 100644 index 4a9fafc4a..000000000 --- a/cc3200/mods/pybwdt.c +++ /dev/null @@ -1,160 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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 "py/mpconfig.h" -#include "py/obj.h" -#include "py/runtime.h" -#include "py/mperrno.h" -#include "py/mphal.h" -#include "inc/hw_types.h" -#include "inc/hw_gpio.h" -#include "inc/hw_ints.h" -#include "inc/hw_memmap.h" -#include "rom_map.h" -#include "wdt.h" -#include "prcm.h" -#include "utils.h" -#include "pybwdt.h" -#include "mpexception.h" -#include "mperror.h" - - -/****************************************************************************** - DECLARE CONSTANTS - ******************************************************************************/ -#define PYBWDT_MILLISECONDS_TO_TICKS(ms) ((80000000 / 1000) * (ms)) -#define PYBWDT_MIN_TIMEOUT_MS (1000) - -/****************************************************************************** - DECLARE TYPES - ******************************************************************************/ -typedef struct { - mp_obj_base_t base; - bool servers; - bool servers_sleeping; - bool simplelink; - bool running; -} pyb_wdt_obj_t; - -/****************************************************************************** - DECLARE PRIVATE DATA - ******************************************************************************/ -STATIC pyb_wdt_obj_t pyb_wdt_obj = {.servers = false, .servers_sleeping = false, .simplelink = false, .running = false}; - -/****************************************************************************** - DEFINE PUBLIC FUNCTIONS - ******************************************************************************/ -// must be called in main.c just after initializing the hal -__attribute__ ((section (".boot"))) -void pybwdt_init0 (void) { -} - -void pybwdt_srv_alive (void) { - pyb_wdt_obj.servers = true; -} - -void pybwdt_srv_sleeping (bool state) { - pyb_wdt_obj.servers_sleeping = state; -} - -void pybwdt_sl_alive (void) { - pyb_wdt_obj.simplelink = true; -} - -/******************************************************************************/ -// MicroPython bindings - -STATIC const mp_arg_t pyb_wdt_init_args[] = { - { MP_QSTR_id, MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_timeout, MP_ARG_INT, {.u_int = 5000} }, // 5 s -}; -STATIC mp_obj_t pyb_wdt_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // check the arguments - mp_map_t kw_args; - mp_map_init_fixed_table(&kw_args, n_kw, all_args + n_args); - mp_arg_val_t args[MP_ARRAY_SIZE(pyb_wdt_init_args)]; - mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), pyb_wdt_init_args, args); - - if (args[0].u_obj != mp_const_none && mp_obj_get_int(args[0].u_obj) > 0) { - mp_raise_OSError(MP_ENODEV); - } - uint timeout_ms = args[1].u_int; - if (timeout_ms < PYBWDT_MIN_TIMEOUT_MS) { - mp_raise_ValueError(mpexception_value_invalid_arguments); - } - if (pyb_wdt_obj.running) { - mp_raise_OSError(MP_EPERM); - } - - // Enable the WDT peripheral clock - MAP_PRCMPeripheralClkEnable(PRCM_WDT, PRCM_RUN_MODE_CLK | PRCM_SLP_MODE_CLK); - - // Unlock to be able to configure the registers - MAP_WatchdogUnlock(WDT_BASE); - -#ifdef DEBUG - // make the WDT stall when the debugger stops on a breakpoint - MAP_WatchdogStallEnable (WDT_BASE); -#endif - - // set the watchdog timer reload value - // the WDT trigger a system reset after the second timeout - // so, divide by 2 the timeout value received - MAP_WatchdogReloadSet(WDT_BASE, PYBWDT_MILLISECONDS_TO_TICKS(timeout_ms / 2)); - - // start the timer. Once it's started, it cannot be disabled. - MAP_WatchdogEnable(WDT_BASE); - pyb_wdt_obj.base.type = &pyb_wdt_type; - pyb_wdt_obj.running = true; - - return (mp_obj_t)&pyb_wdt_obj; -} - -STATIC mp_obj_t pyb_wdt_feed(mp_obj_t self_in) { - pyb_wdt_obj_t *self = self_in; - if ((self->servers || self->servers_sleeping) && self->simplelink && self->running) { - self->servers = false; - self->simplelink = false; - MAP_WatchdogIntClear(WDT_BASE); - } - return mp_const_none; -} -STATIC MP_DEFINE_CONST_FUN_OBJ_1(pyb_wdt_feed_obj, pyb_wdt_feed); - -STATIC const mp_rom_map_elem_t pybwdt_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_feed), MP_ROM_PTR(&pyb_wdt_feed_obj) }, -}; -STATIC MP_DEFINE_CONST_DICT(pybwdt_locals_dict, pybwdt_locals_dict_table); - -const mp_obj_type_t pyb_wdt_type = { - { &mp_type_type }, - .name = MP_QSTR_WDT, - .make_new = pyb_wdt_make_new, - .locals_dict = (mp_obj_t)&pybwdt_locals_dict, -}; - diff --git a/cc3200/mods/pybwdt.h b/cc3200/mods/pybwdt.h deleted file mode 100644 index 275c49435..000000000 --- a/cc3200/mods/pybwdt.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2015 Daniel Campora - * - * 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_CC3200_MODS_PYBWDT_H -#define MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H - -#include "py/obj.h" - -extern const mp_obj_type_t pyb_wdt_type; - -void pybwdt_init0 (void); -void pybwdt_srv_alive (void); -void pybwdt_srv_sleeping (bool state); -void pybwdt_sl_alive (void); - -#endif // MICROPY_INCLUDED_CC3200_MODS_PYBWDT_H |
