diff --git a/.gitignore b/.gitignore index e3cfd1232c..7e9a915f53 100644 --- a/.gitignore +++ b/.gitignore @@ -36,6 +36,7 @@ user.props .pydevproject .settings .launch +.vscode # Key files (for Flash Encryption and Secure Boot) secure_boot_signing_key.pem diff --git a/Jenkinsfile b/Jenkinsfile index f2d40d5f06..260e94ce60 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -9,9 +9,14 @@ node { stage('Checkout') { checkout scm sh 'rm -rf esp-idf' - sh 'git clone --depth=1 --recursive -b idf_v3.2 https://github.com/pycom/pycom-esp-idf.git esp-idf' + sh 'git clone --recursive -b idf_v3.3.1 https://github.com/pycom/pycom-esp-idf.git esp-idf' + IDF_HASH=get_idf_hash() + dir('esp-idf'){ + sh 'git checkout ' + IDF_HASH + sh 'git submodule update --init --recursive' + } } - + stage('git-tag') { PYCOM_VERSION=get_version() GIT_TAG = sh (script: 'git rev-parse --short HEAD', returnStdout: true).trim() @@ -85,7 +90,8 @@ def flashBuild(short_name, version, variant) { unstash 'esp32Tools' unstash 'tests' unstash 'tools' - sh 'python esp32/tools/fw_updater/updater.py --port ' + device_name +' flash -t esp32/build-' + variant + '/' + board_name + '-' + version + '.tar.gz' + sh 'python esp32/tools/fw_updater/updater.py --noexit --port ' + device_name +' flash -t esp32/build-' + variant + '/' + board_name + '-' + version + '.tar.gz' + sh 'python esp32/tools/fw_updater/updater.py --port ' + device_name +' pybytes --auto_start False' } } } @@ -114,6 +120,11 @@ def get_version() { matcher ? matcher[0][1].trim().replace('"','') : null } +def get_idf_hash() { + def matcher = readFile('esp32/Makefile') =~ 'IDF_HASH=(.+)' + matcher ? matcher[0][1].trim().replace('"','') : null +} + def get_firmware_name(short_name) { node { def node_info = sh (script: 'cat ${JENKINS_HOME}/pycom-ic.conf || exit 0', returnStdout: true).trim() diff --git a/README.md b/README.md index c440a719da..13446f79da 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ board (PyBoard), the officially supported reference electronic circuit board. The following components are actively maintained by Pycom: - py/ -- the core Python implementation, including compiler, runtime, and core library. -- exp32/ -- a version of MicroPython that runs on the ESP32 based boards from Pycom. +- esp32/ -- a version of MicroPython that runs on the ESP32 based boards from Pycom. - tests/ -- test framework and test scripts. Additional components: @@ -74,7 +74,7 @@ Then when you need the toolchain you can type ``get_esp32`` on the command line You also need the ESP IDF along side this repository in order to build the ESP32 port. To get it: - $ git clone --recursive -b idf_v3.2 https://github.com/pycom/pycom-esp-idf.git + $ git clone --recursive -b idf_v3.3.1 https://github.com/pycom/pycom-esp-idf.git After cloning, if you did not specify the --recursive option, make sure to checkout all the submodules: diff --git a/docs/library/ussl.rst b/docs/library/ussl.rst index a37ac6adbf..6bdaf0187f 100644 --- a/docs/library/ussl.rst +++ b/docs/library/ussl.rst @@ -114,6 +114,21 @@ network sockets, both client-side and server-side. SSL sockets inherit all methods and from the standard sockets, see the :mod:`usocket` module. + .. function:: ssl.save_session(sock) + + Takes an instance sock of ssl.SSLSocket, and returns an instance of ssl.SSLSession representing saved session data from the socket, which can be used to resume a SSL session later. Example:: + + import socket + import ssl + addr = socket.getaddrinfo('www.google.com', 443)[0][-1] + sock_one = ssl.wrap_socket(socket.socket()) + sock_one.connect(addr) # performs a full ssl handshake + session = ssl.save_session(sock_one) + sock_one.close() + sock_one = None + sock_two = ssl.wrap_socket(socket.socket(), saved_session=session) + sock_two.connect(addr) # resumes using saved session, resulting in a faster handshake + Exceptions ---------- diff --git a/docs/license.rst b/docs/license.rst index 6fedebf73a..4b6041396b 100644 --- a/docs/license.rst +++ b/docs/license.rst @@ -23,7 +23,7 @@ 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. -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information diff --git a/drivers/sx127x/sx1272/sx1272.c b/drivers/sx127x/sx1272/sx1272.c index 29e12dfa8f..b78bae1465 100644 --- a/drivers/sx127x/sx1272/sx1272.c +++ b/drivers/sx127x/sx1272/sx1272.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/drivers/sx127x/sx1276/sx1276.c b/drivers/sx127x/sx1276/sx1276.c index 30408ca55a..870c4abae1 100755 --- a/drivers/sx127x/sx1276/sx1276.c +++ b/drivers/sx127x/sx1276/sx1276.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/Makefile b/esp32/Makefile index c0feff5a44..742dae3c04 100644 --- a/esp32/Makefile +++ b/esp32/Makefile @@ -1,5 +1,5 @@ # -# Copyright © 2019, Pycom Limited. +# Copyright © 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information @@ -14,7 +14,7 @@ ifeq ($(wildcard boards/$(BOARD)/.),) $(error Invalid BOARD specified) endif -IDF_VERSION=3.2 +IDF_HASH=6ec081c TARGET ?= boot_app @@ -103,17 +103,10 @@ LIBS = -L$(ESP_IDF_COMP_PATH)/esp32/lib -L$(ESP_IDF_COMP_PATH)/esp32/ld -L$(ESP_ $(ESP_IDF_COMP_PATH)/newlib/lib/libc-psram-workaround.a \ -lfreertos -ljson -ljsmn -llwip -lnewlib -lvfs -lopenssl -lmbedtls -lwpa_supplicant \ -lxtensa-debug-module -lbt -lsdmmc -lsoc -lheap -lbootloader_support -lmicro-ecc \ - -u ld_include_panic_highint_hdl -lsmartconfig_ack -lmesh -lesp_ringbuf -lcoap -lmdns -ifeq ($(BOARD), $(filter $(BOARD), FIPY)) - LIBS += sigfox/modsigfox_fipy.a -endif - -ifeq ($(BOARD), $(filter $(BOARD), LOPY4)) - LIBS += sigfox/modsigfox_lopy4.a -endif - -ifeq ($(BOARD), $(filter $(BOARD), SIPY)) - LIBS += sigfox/modsigfox_sipy.a + -u ld_include_panic_highint_hdl -lsmartconfig_ack -lmesh -lesp_ringbuf -lcoap -lmdns -lefuse -lespcoredump -lapp_update +ifeq ($(BOARD), $(filter $(BOARD), SIPY LOPY4 FIPY)) + LIBS += sigfox/modsigfox_$(BOARD).a +$(BUILD)/application.elf: sigfox/modsigfox_$(BOARD).a endif ifeq ($(OPENTHREAD), on) @@ -134,7 +127,7 @@ endif #ifeq ($(LTE_LOG_BUFF),1) B_LIBS = -Lbootloader/lib -Lbootloader -L$(BUILD)/bootloader -L$(ESP_IDF_COMP_PATH)/esp32/ld \ -L$(ESP_IDF_COMP_PATH)/esp32/lib -llog -lcore -lbootloader_support \ - -lspi_flash -lsoc -lmicro-ecc -lgcc -lstdc++ -lgcov + -lspi_flash -lsoc -lmicro-ecc -lgcc -lstdc++ -lgcov -lefuse # objcopy paramters, to transform a binary file into an object file OBJCOPY_EMBED_ARGS = --input-target binary --output-target elf32-xtensa-le --binary-architecture xtensa --rename-section .data=.rodata.embedded diff --git a/esp32/PyJTAG/Readme.md b/esp32/PyJTAG/Readme.md new file mode 100644 index 0000000000..415fd342eb --- /dev/null +++ b/esp32/PyJTAG/Readme.md @@ -0,0 +1,96 @@ +# Short readme for how to use the PyJTAG + +## Setup +Generally follow these rules to setup JTAG debugging on your OS: https://docs.espressif.com/projects/esp-idf/en/latest/api-guides/jtag-debugging/index.html + +Download link for OpenOCD for ESP32 from Espressif: https://github.com/espressif/openocd-esp32/releases + + +## Build the firmware +Create the firmware with `BTYPE=debug` flag. + +Note: Do not use the default pins assigned to UART, SPI, CAN because they are used by the JTAG. Pins not to be used: P4, P9, P10, P23. + +## Setup the PyJTAG board + +PyJTAG's switches: + * ESP32 JTAG: all turned ON + * ESP32 B.LOADER: all turned ON except SAFE_BOOT_SW which is OFF + * TO LTE UART 1/2: does not matter + * CURRENT SHUNTS: connected + +Place the Pycom board with the reset button towards the Current Shunts. Now connect the PyJTAG via usb. You will see four new USB devices. On Linux this will look like this: +``` +$ lsusb -d 0403: +Bus 001 Device 010: ID 0403:6011 Future Technology Devices International, Ltd FT4232H Quad HS USB-UART/FIFO IC +$ ls /dev/ttyUSB? +/dev/ttyUSB0 /dev/ttyUSB1 /dev/ttyUSB2 /dev/ttyUSB3 +``` + +## Start OCD + +Go to `esp32` folder in Firmware-Development repository and run: +``` +PATH_TO_OPENOCD/bin/openocd -s PATH_TO_OPENOCD/share/openocd/scripts -s PyJTAG -f PyJTAG/interface/ftdi/esp32-pycom.cfg -f PyJTAG/board/esp32-pycom.cfg +``` + +Output should be like: +``` +Open On-Chip Debugger v0.10.0-esp32-20191114 (2019-11-14-14:15) +Licensed under GNU GPL v2 +For bug reports, read + http://openocd.org/doc/doxygen/bugs.html +none separate +adapter speed: 20000 kHz +Info : Configured 2 cores +Info : Listening on port 6666 for tcl connections +Info : Listening on port 4444 for telnet connections +Error: type 'esp32' is missing virt2phys +Info : ftdi: if you experience problems at higher adapter clocks, try the command "ftdi_tdo_sample_edge falling" +Info : clock speed 20000 kHz +Info : JTAG tap: esp32.cpu0 tap/device found: 0x120034e5 (mfg: 0x272 (Tensilica), part: 0x2003, ver: 0x1) +Info : JTAG tap: esp32.cpu1 tap/device found: 0x120034e5 (mfg: 0x272 (Tensilica), part: 0x2003, ver: 0x1) +Info : Listening on port 3333 for gdb connections +``` + +## Start GDB + +When OpenOCD is running, start GDB from `esp32` folder. Assuming you have a FIPY: +``` +xtensa-esp32-elf-gdb -x PyJTAG/gdbinit build/FIPY/debug/application.elf +``` + +In `PyJTAG/gdbinit` a breakpoint is configured at `TASK_Micropython`, so execution should stop there first: + +``` +Thread 1 hit Temporary breakpoint 1, TASK_Micropython (pvParameters=0x0) at mptask.c:136 +``` + + +## REPL + +Connect to `/dev/ttyUSB2` to reach the REPL terminal over usb serial. E.g. using pymakr in Atom. + +## Troubleshooting +If openocd says "Error: Connect failed", try to close gdb and openocd and start over. + +If `/dev/ttyUSB0` doesn't show up or disappears, disconnect the PyJTAG board, reconnect and start over. + +It can be advisable to use the `gdb` from the latest xtensa toolchain, even if an earlier version is used to build the firmware. + +If `gdb` does not reach the `Thread 1 hit Temporary breakpoint ...` line, close and reopen `gdb`. + + +## Versions +There are two generations of PyJTAG boards: + +1) First generation with green PCB has three blocks of switches. (Make sure SAFE_BOOT_SW is off.) +2) Second generation with black PCB and two blocks of switches. + +Both generation boards can be equipped with pogo pins that connect to the bottom of the development board and allow LTE debugging. There can either be pins that connect to a GPy or pins that conenct to a FiPy. + +To reach the modem UART connect to `/dev/ttyUSB1`. + +## Extra +A few more details are here: https://pycomiot.atlassian.net/wiki/spaces/FIR/pages/966295564/Usage+of+PyJTAG + diff --git a/esp32/PyJTAG/board/esp32-pycom.cfg b/esp32/PyJTAG/board/esp32-pycom.cfg new file mode 100644 index 0000000000..c294242718 --- /dev/null +++ b/esp32/PyJTAG/board/esp32-pycom.cfg @@ -0,0 +1,2 @@ +set ESP32_FLASH_VOLTAGE 3.3 +source [find target/esp32-pycom.cfg] \ No newline at end of file diff --git a/esp32/PyJTAG/gdbinit b/esp32/PyJTAG/gdbinit new file mode 100644 index 0000000000..00351df9ae --- /dev/null +++ b/esp32/PyJTAG/gdbinit @@ -0,0 +1,5 @@ +target remote :3333 +mon reset halt +flushregs +thb TASK_Micropython +c diff --git a/esp32/PyJTAG/interface/ftdi/esp32-pycom.cfg b/esp32/PyJTAG/interface/ftdi/esp32-pycom.cfg new file mode 100644 index 0000000000..ebc6a2d22a --- /dev/null +++ b/esp32/PyJTAG/interface/ftdi/esp32-pycom.cfg @@ -0,0 +1,35 @@ +# +# Driver for the FT4232HL JTAG chip on the Pycom's PyJTAG board +# + + +interface ftdi +ftdi_vid_pid 0x0403 0x6011 + +# interface 1 is the uart +ftdi_channel 0 + +# TCK, TDI, TDO, TMS: ADBUS0-3 +# LEDs: ACBUS4-7 + +ftdi_layout_init 0x0008 0xf00b +#ftdi_layout_signal LED -data 0x1000 +#ftdi_layout_signal LED2 -data 0x2000 +#ftdi_layout_signal LED3 -data 0x4000 +#ftdi_layout_signal LED4 -data 0x8000 + +# ESP32 series chips do not have a TRST input, and the SRST line is connected +# to the EN pin. +# The target code doesn't handle SRST reset properly yet, so this is +# commented out: +# ftdi_layout_signal nSRST -oe 0x0020 + +reset_config none + +# The speed of the JTAG interface, in KHz. If you get DSR/DIR errors (and they +# do not relate to OpenOCD trying to read from a memory range without physical +# memory being present there), you can try lowering this. +# +# On DevKit-J, this can go as high as 20MHz if CPU frequency is 80MHz, or 26MHz +# if CPU frequency is 160MHz or 240MHz. +adapter_khz 20000 diff --git a/esp32/PyJTAG/target/esp32-pycom.cfg b/esp32/PyJTAG/target/esp32-pycom.cfg new file mode 100644 index 0000000000..35fd8c0e3b --- /dev/null +++ b/esp32/PyJTAG/target/esp32-pycom.cfg @@ -0,0 +1,69 @@ +# The ESP32 only supports JTAG. +transport select jtag + +# Source the ESP common configuration file +source [find target/esp_common.cfg] + +if { [info exists CHIPNAME] } { + set _CHIPNAME $CHIPNAME +} else { + set _CHIPNAME esp32 +} + +if { [info exists CPUTAPID] } { + set _CPUTAPID $CPUTAPID +} else { + set _CPUTAPID 0x120034e5 +} + +if { [info exists ESP32_ONLYCPU] } { + set _ONLYCPU $ESP32_ONLYCPU +} else { + set _ONLYCPU 3 +} + +if { [info exists ESP32_FLASH_VOLTAGE] } { + set _FLASH_VOLTAGE $ESP32_FLASH_VOLTAGE +} else { + set _FLASH_VOLTAGE 3.3 +} + +set _TARGETNAME $_CHIPNAME +set _CPU0NAME cpu0 +set _CPU1NAME cpu1 +set _TAPNAME $_CHIPNAME.$_CPU0NAME + +jtag newtap $_CHIPNAME $_CPU0NAME -irlen 5 -expected-id $_CPUTAPID +if { $_ONLYCPU != 1 } { + jtag newtap $_CHIPNAME $_CPU1NAME -irlen 5 -expected-id $_CPUTAPID +} else { + jtag newtap $_CHIPNAME $_CPU1NAME -irlen 5 -disable -expected-id $_CPUTAPID +} + +if { $_RTOS == "none" } { + target create $_TARGETNAME esp32 -endian little -chain-position $_TAPNAME +} else { + target create $_TARGETNAME esp32 -endian little -chain-position $_TAPNAME -rtos $_RTOS +} + +configure_esp_workarea $_TARGETNAME 0x40090000 0x3400 0x3FFC0000 0x6000 +configure_esp_flash_bank $_TARGETNAME $_TARGETNAME $_FLASH_SIZE + +esp32 flashbootstrap $_FLASH_VOLTAGE +esp32 maskisr on +if { $_SEMIHOST_BASEDIR != "" } { + esp32 semihost_basedir $_SEMIHOST_BASEDIR +} +if { $_FLASH_SIZE == 0 } { + gdb_breakpoint_override hard +} + +# special function to program ESP32, it differs from the original 'program' that +# it verifies written image by reading flash directly, instead of reading memory mapped flash regions +proc program_esp32 {filename args} { + program_esp $filename $args +} + +add_help_text program_esp32 "write an image to flash, address is only required for binary images. verify, reset, exit are optional" +add_usage_text program_esp32 " \[address\] \[verify\] \[reset\] \[exit\]" + diff --git a/esp32/application.mk b/esp32/application.mk index 80027b16e2..1533930a2a 100644 --- a/esp32/application.mk +++ b/esp32/application.mk @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information @@ -185,6 +185,8 @@ APP_UTIL_SRC_C = $(addprefix util/,\ mpsleep.c \ timeutils.c \ esp32chipinfo.c \ + pycom_general_util.c \ + str_utils.c \ ) APP_FATFS_SRC_C = $(addprefix fatfs/src/,\ @@ -231,6 +233,7 @@ APP_LIB_LORA_SRC_C = $(addprefix lib/lora/,\ mac/region/RegionEU868.c \ mac/region/RegionUS915.c \ mac/region/RegionCN470.c \ + mac/region/RegionEU433.c \ mac/region/RegionIN865.c \ system/delay.c \ system/gpio.c \ @@ -247,7 +250,7 @@ APP_SX1276_SRC_C = $(addprefix drivers/sx127x/,\ sx1276/sx1276.c \ ) -APP_SIGFOX_SRC_SIPY_C = $(addprefix sigfox/,\ +APP_SIGFOX_SRC_SIPY_C = $(addprefix sigfox/src/,\ manufacturer_api.c \ radio.c \ ti_aes_128.c \ @@ -256,7 +259,7 @@ APP_SIGFOX_SRC_SIPY_C = $(addprefix sigfox/,\ modsigfox.c \ ) -APP_SIGFOX_SRC_FIPY_LOPY4_C = $(addprefix sigfox/,\ +APP_SIGFOX_SRC_FIPY_LOPY4_C = $(addprefix sigfox/src/,\ manufacturer_api.c \ radio_sx127x.c \ ti_aes_128.c \ @@ -269,7 +272,7 @@ APP_SIGFOX_MOD_SRC_C = $(addprefix mods/,\ modsigfox_api.c \ ) -APP_SIGFOX_TARGET_SRC_C = $(addprefix sigfox/targets/,\ +APP_SIGFOX_TARGET_SRC_C = $(addprefix sigfox/src/targets/,\ cc112x_spi.c \ hal_int.c \ hal_spi_rf_trxeb.c \ @@ -368,12 +371,12 @@ SRC_QSTR_AUTO_DEPS += BOOT_LDFLAGS = $(LDFLAGS) -T esp32.bootloader.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.bootloader.rom.ld -T esp32.rom.spiram_incompatible_fns.ld # add the application linker script(s) -APP_LDFLAGS += $(LDFLAGS) -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T wifi_iram.ld +APP_LDFLAGS += $(LDFLAGS) -T esp32_out.ld -T esp32.project.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.libgcc.ld # add the application specific CFLAGS CFLAGS += $(APP_INC) -DMICROPY_NLR_SETJMP=1 -DMBEDTLS_CONFIG_FILE='"mbedtls/esp_config.h"' -DHAVE_CONFIG_H -DESP_PLATFORM -DFFCONF_H=\"lib/oofatfs/ffconf.h\" -DWITH_POSIX CFLAGS_SIGFOX += $(APP_INC) -DMICROPY_NLR_SETJMP=1 -DMBEDTLS_CONFIG_FILE='"mbedtls/esp_config.h"' -DHAVE_CONFIG_H -DESP_PLATFORM -CFLAGS += -DREGION_AS923 -DREGION_AU915 -DREGION_EU868 -DREGION_US915 -DREGION_CN470 -DREGION_IN865 -DBASE=0 -DPYBYTES=1 +CFLAGS += -DREGION_AS923 -DREGION_AU915 -DREGION_EU868 -DREGION_US915 -DREGION_CN470 -DREGION_EU433 -DREGION_IN865 -DBASE=0 -DPYBYTES=1 # Specify if this is base or Pybytes Firmware ifeq ($(VARIANT),BASE) CFLAGS += -DVARIANT=0 @@ -514,6 +517,9 @@ endif ifeq ($(TARGET), boot_app) all: $(BOOT_BIN) $(APP_BIN) endif +ifeq ($(TARGET), sigfox) +include sigfox.mk +endif .PHONY: all CHECK_DEP $(info $(VARIANT) Variant) @@ -527,6 +533,14 @@ CFLAGS += -DCONFIG_FLASH_ENCRYPTION_ENABLED=1 # it can also be added permanently in sdkconfig.h CFLAGS += -DCONFIG_SECURE_BOOT_ENABLED=1 +define resolvepath +$(abspath $(foreach dir,$(1),$(if $(filter /%,$(dir)),$(dir),$(subst //,/,$(2)/$(dir))))) +endef + +define dequote +$(subst ",,$(1)) +endef + # find the configured private key file ORIG_SECURE_KEY := $(call resolvepath,$(call dequote,$(SECURE_KEY)),$(PROJECT_PATH)) @@ -641,7 +655,7 @@ $(BUILD)/application.a: $(OBJ) $(ECHO) "AR $@" $(Q) rm -f $@ $(Q) $(AR) cru $@ $^ -$(BUILD)/application.elf: $(BUILD)/application.a $(BUILD)/esp32_out.ld $(SECURE_BOOT_VERIFICATION_KEY) +$(BUILD)/application.elf: $(BUILD)/application.a $(BUILD)/esp32_out.ld esp32.project.ld $(SECURE_BOOT_VERIFICATION_KEY) ifeq ($(SECURE), on) # unpack libbootloader_support.a, and archive again using the right key for verifying signatures $(ECHO) "Inserting verification key $(SECURE_BOOT_VERIFICATION_KEY) in $@" @@ -807,8 +821,9 @@ $(OBJ): | $(GEN_PINS_HDR) # Check Dependencies (IDF version, Frozen code and IDF LIBS) CHECK_DEP: - $(Q) bash tools/idfVerCheck.sh $(IDF_PATH) "$(IDF_VERSION)" + $(Q) bash tools/idfVerCheck.sh $(IDF_PATH) "$(IDF_HASH)" $(Q) bash tools/mpy-build-check.sh $(BOARD) $(BTYPE) $(VARIANT) + $(Q) $(PYTHON) check_secure_boot.py --SECURE $(SECURE) ifeq ($(COPY_IDF_LIB), 1) $(ECHO) "COPY IDF LIBRARIES" $(Q) $(PYTHON) get_idf_libs.py --idflibs $(IDF_PATH)/examples/wifi/scan/build diff --git a/esp32/boards/FIPY/mpconfigboard.h b/esp32/boards/FIPY/mpconfigboard.h index 2dcc78f822..13cd4b120f 100644 --- a/esp32/boards/FIPY/mpconfigboard.h +++ b/esp32/boards/FIPY/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/boards/GPY/mpconfigboard.h b/esp32/boards/GPY/mpconfigboard.h index f67e75fa5c..b53c2c8e89 100644 --- a/esp32/boards/GPY/mpconfigboard.h +++ b/esp32/boards/GPY/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/boards/LOPY/mpconfigboard.h b/esp32/boards/LOPY/mpconfigboard.h index fda58d3f25..e07d3d658d 100644 --- a/esp32/boards/LOPY/mpconfigboard.h +++ b/esp32/boards/LOPY/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/boards/LOPY4/mpconfigboard.h b/esp32/boards/LOPY4/mpconfigboard.h index 414ff69936..95b835feda 100644 --- a/esp32/boards/LOPY4/mpconfigboard.h +++ b/esp32/boards/LOPY4/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/boards/SIPY/mpconfigboard.h b/esp32/boards/SIPY/mpconfigboard.h index 1f8fd79380..229ea22d4b 100644 --- a/esp32/boards/SIPY/mpconfigboard.h +++ b/esp32/boards/SIPY/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/boards/WIPY/mpconfigboard.h b/esp32/boards/WIPY/mpconfigboard.h index fb5b0b65ef..5a37216506 100644 --- a/esp32/boards/WIPY/mpconfigboard.h +++ b/esp32/boards/WIPY/mpconfigboard.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/boards/esp32_prefix.c b/esp32/boards/esp32_prefix.c index 4b5c80bf74..206dd7b701 100644 --- a/esp32/boards/esp32_prefix.c +++ b/esp32/boards/esp32_prefix.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/boards/make-pins.py b/esp32/boards/make-pins.py index a0e4a32722..df11593d31 100644 --- a/esp32/boards/make-pins.py +++ b/esp32/boards/make-pins.py @@ -2,7 +2,7 @@ # This file is derived from the MicroPython project, http://micropython.org/ # -# Copyright (c) 2019, Pycom Limited and its licensors. +# Copyright (c) 2020, Pycom Limited and its licensors. # # This software is licensed under the GNU GPL version 3 or any later version, # with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/bootloader/bootmgr.c b/esp32/bootloader/bootmgr.c index 2f94b54d8a..2db85adddd 100644 --- a/esp32/bootloader/bootmgr.c +++ b/esp32/bootloader/bootmgr.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/bootloader/bootmgr.h b/esp32/bootloader/bootmgr.h index b974c4fbb1..6b1877688d 100644 --- a/esp32/bootloader/bootmgr.h +++ b/esp32/bootloader/bootmgr.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/bootloader/lib/libbootloader_support.a b/esp32/bootloader/lib/libbootloader_support.a index df62723f04..0bbcdedda4 100644 Binary files a/esp32/bootloader/lib/libbootloader_support.a and b/esp32/bootloader/lib/libbootloader_support.a differ diff --git a/esp32/bootloader/lib/libefuse.a b/esp32/bootloader/lib/libefuse.a new file mode 100644 index 0000000000..00abdd7165 Binary files /dev/null and b/esp32/bootloader/lib/libefuse.a differ diff --git a/esp32/bootloader/lib/liblog.a b/esp32/bootloader/lib/liblog.a index 3abb4163f3..5c446945f7 100644 Binary files a/esp32/bootloader/lib/liblog.a and b/esp32/bootloader/lib/liblog.a differ diff --git a/esp32/bootloader/lib/libmicro-ecc.a b/esp32/bootloader/lib/libmicro-ecc.a index f2bcb6bbb1..a11ea02bff 100644 Binary files a/esp32/bootloader/lib/libmicro-ecc.a and b/esp32/bootloader/lib/libmicro-ecc.a differ diff --git a/esp32/bootloader/lib/libsoc.a b/esp32/bootloader/lib/libsoc.a index 5e1d9d8c61..93dfd8156d 100644 Binary files a/esp32/bootloader/lib/libsoc.a and b/esp32/bootloader/lib/libsoc.a differ diff --git a/esp32/bootloader/lib/libspi_flash.a b/esp32/bootloader/lib/libspi_flash.a index 1d353388d1..29e8be5cb2 100644 Binary files a/esp32/bootloader/lib/libspi_flash.a and b/esp32/bootloader/lib/libspi_flash.a differ diff --git a/esp32/bootloader/mperror.c b/esp32/bootloader/mperror.c index 07577b49c8..d11795cf6d 100644 --- a/esp32/bootloader/mperror.c +++ b/esp32/bootloader/mperror.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/check_secure_boot.py b/esp32/check_secure_boot.py new file mode 100644 index 0000000000..f8dd2b4728 --- /dev/null +++ b/esp32/check_secure_boot.py @@ -0,0 +1,18 @@ +import argparse + + +def main(): + cmd_parser = argparse.ArgumentParser() + cmd_parser.add_argument('--SECURE', default=None) + cmd_args = cmd_parser.parse_args() + + secure = cmd_args.SECURE + with open("sdkconfig.h") as sdkconfig: + if any("CONFIG_SECURE_BOOT_ENABLED" in l for l in sdkconfig.readlines()): + if(secure != "on"): + print("If CONFIG_SECURE_BOOT_ENABLED is defined in sdkconfig.h, the SECURE=on must be used when building the Firmware!") + # Non zero exit code means error + exit(1) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/esp32/esp32.project.ld b/esp32/esp32.project.ld new file mode 100644 index 0000000000..ab86633b9a --- /dev/null +++ b/esp32/esp32.project.ld @@ -0,0 +1,618 @@ +/* Automatically generated file; DO NOT EDIT */ +/* Espressif IoT Development Framework Linker Script */ +/* Generated from: /Users/ehlers/pycom/pycom-esp-idf/components/esp32/ld/esp32.project.ld.in */ + +/* Default entry point: */ +ENTRY(call_start_cpu0); + +SECTIONS +{ + /* RTC fast memory holds RTC wake stub code, + including from any source file named rtc_wake_stub*.c + */ + .rtc.text : + { + . = ALIGN(4); + + *( .rtc.literal .rtc.text .rtc.text.*) + + *rtc_wake_stub*.*(.literal .text .literal.* .text.*) + _rtc_text_end = ABSOLUTE(.); + } > rtc_iram_seg + + /* + This section is required to skip rtc.text area because rtc_iram_seg and + rtc_data_seg are reflect the same address space on different buses. + */ + .rtc.dummy : + { + _rtc_dummy_start = ABSOLUTE(.); + _rtc_fast_start = ABSOLUTE(.); + . = SIZEOF(.rtc.text); + _rtc_dummy_end = ABSOLUTE(.); + } > rtc_data_seg + + /* This section located in RTC FAST Memory area. + It holds data marked with RTC_FAST_ATTR attribute. + See the file "esp_attr.h" for more information. + */ + .rtc.force_fast : + { + . = ALIGN(4); + _rtc_force_fast_start = ABSOLUTE(.); + *(.rtc.force_fast .rtc.force_fast.*) + . = ALIGN(4) ; + _rtc_force_fast_end = ABSOLUTE(.); + } > rtc_data_seg + + /* RTC data section holds RTC wake stub + data/rodata, including from any source file + named rtc_wake_stub*.c and the data marked with + RTC_DATA_ATTR, RTC_RODATA_ATTR attributes. + The memory location of the data is dependent on + CONFIG_ESP32_RTCDATA_IN_FAST_MEM option. + */ + .rtc.data : + { + _rtc_data_start = ABSOLUTE(.); + + *( .rtc.data .rtc.data.* .rtc.rodata .rtc.rodata.*) + + *rtc_wake_stub*.*(.data .rodata .data.* .rodata.* .bss .bss.*) + _rtc_data_end = ABSOLUTE(.); + } > rtc_data_location + + /* RTC bss, from any source file named rtc_wake_stub*.c */ + .rtc.bss (NOLOAD) : + { + _rtc_bss_start = ABSOLUTE(.); + *rtc_wake_stub*.*(.bss .bss.*) + *rtc_wake_stub*.*(COMMON) + + *( .rtc.bss) + + _rtc_bss_end = ABSOLUTE(.); + } > rtc_data_location + + /* This section holds data that should not be initialized at power up + and will be retained during deep sleep. + User data marked with RTC_NOINIT_ATTR will be placed + into this section. See the file "esp_attr.h" for more information. + The memory location of the data is dependent on + CONFIG_ESP32_RTCDATA_IN_FAST_MEM option. + */ + .rtc_noinit (NOLOAD): + { + . = ALIGN(4); + _rtc_noinit_start = ABSOLUTE(.); + *(.rtc_noinit .rtc_noinit.*) + . = ALIGN(4) ; + _rtc_noinit_end = ABSOLUTE(.); + } > rtc_data_location + + /* This section located in RTC SLOW Memory area. + It holds data marked with RTC_SLOW_ATTR attribute. + See the file "esp_attr.h" for more information. + */ + .rtc.force_slow : + { + . = ALIGN(4); + _rtc_force_slow_start = ABSOLUTE(.); + *(.rtc.force_slow .rtc.force_slow.*) + . = ALIGN(4) ; + _rtc_force_slow_end = ABSOLUTE(.); + } > rtc_slow_seg + + /* Get size of rtc slow data based on rtc_data_location alias */ + _rtc_slow_length = (ORIGIN(rtc_slow_seg) == ORIGIN(rtc_data_location)) + ? (_rtc_force_slow_end - _rtc_data_start) + : (_rtc_force_slow_end - _rtc_force_slow_start); + + _rtc_fast_length = (ORIGIN(rtc_slow_seg) == ORIGIN(rtc_data_location)) + ? (_rtc_force_fast_end - _rtc_fast_start) + : (_rtc_noinit_end - _rtc_fast_start); + + ASSERT((_rtc_slow_length <= LENGTH(rtc_slow_seg)), + "RTC_SLOW segment data does not fit.") + + ASSERT((_rtc_fast_length <= LENGTH(rtc_data_seg)), + "RTC_FAST segment data does not fit.") + + /* Send .iram0 code to iram */ + .iram0.vectors : + { + _iram_start = ABSOLUTE(.); + /* Vectors go to IRAM */ + _init_start = ABSOLUTE(.); + /* Vectors according to builds/RF-2015.2-win32/esp108_v1_2_s5_512int_2/config.html */ + . = 0x0; + KEEP(*(.WindowVectors.text)); + . = 0x180; + KEEP(*(.Level2InterruptVector.text)); + . = 0x1c0; + KEEP(*(.Level3InterruptVector.text)); + . = 0x200; + KEEP(*(.Level4InterruptVector.text)); + . = 0x240; + KEEP(*(.Level5InterruptVector.text)); + . = 0x280; + KEEP(*(.DebugExceptionVector.text)); + . = 0x2c0; + KEEP(*(.NMIExceptionVector.text)); + . = 0x300; + KEEP(*(.KernelExceptionVector.text)); + . = 0x340; + KEEP(*(.UserExceptionVector.text)); + . = 0x3C0; + KEEP(*(.DoubleExceptionVector.text)); + . = 0x400; + *(.*Vector.literal) + + *(.UserEnter.literal); + *(.UserEnter.text); + . = ALIGN (16); + *(.entry.text) + *(.init.literal) + *(.init) + _init_end = ABSOLUTE(.); + } > iram0_0_seg + + .iram0.text : + { + /* Code marked as runnning out of IRAM */ + _iram_text_start = ABSOLUTE(.); + + *( .iram1 .iram1.*) + *libspi_flash.a:spi_flash_rom_patch.*( .literal .literal.* .text .text.*) + *libesp_ringbuf.a:( .literal .literal.* .text .text.*) + *libhal.a:( .literal .literal.* .text .text.*) + *libapp_trace.a:( .literal .literal.* .text .text.*) + *libesp32.a:panic.*( .literal .literal.* .text .text.*) + *libespcoredump.a:core_dump_uart.*( .literal .literal.* .text .text.*) + *libespcoredump.a:core_dump_flash.*( .literal .literal.* .text .text.*) + *libespcoredump.a:core_dump_common.*( .literal .literal.* .text .text.*) + *libespcoredump.a:core_dump_port.*( .literal .literal.* .text .text.*) + *librtc.a:( .literal .literal.* .text .text.*) + *libgcc.a:lib2funcs.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_clk.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_init.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_sleep.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_time.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_periph.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_wdt.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_pm.*( .literal .literal.* .text .text.*) + *libsoc.a:cpu_util.*( .literal .literal.* .text .text.*) + *libsoc.a:rtc_clk_init.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-findfp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memcpy.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strchr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strptime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-creat.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strncmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strftime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-itoa.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:isatty.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-ctime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-gmtime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-div.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-sbrk.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-setjmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-fputwc.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-system.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isascii.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-atoi.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-open.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-close.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-wbuf.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-sysopen.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strstr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-rand_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-timelocal.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strtok_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-wctomb_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-toascii.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strnlen.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-wsetup.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strncat.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-labs.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-tzcalc_limits.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lock.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-utoa.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memrchr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-mktime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strndup.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-bzero.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memset.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-sccl.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-s_fpclassify.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strlen.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-ldiv.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-lcltime_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-gmtime_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-srand.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-fvwrite.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-envlock.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-wcrtomb.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-asctime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-sf_nan.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-asctime_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-refill.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcoll.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcasestr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-fwalk.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memchr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strndup_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:creat.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-ctype_.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-tzvars.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strlcpy.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strspn.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memcmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcat.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strdup.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isblank.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isupper.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memmove.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-makebuf.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-longjmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strtoul.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-toupper.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strncasecmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-rand.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strdup_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcpy.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcasecmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isgraph.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-ungetc.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strlwr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strupr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strsep.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-fflush.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isspace.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-memccpy.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-sysread.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-quorem.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-getenv_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-read.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-lcltime.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-tzset_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strncpy.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-ctime_r.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isalnum.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-sysclose.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strlcat.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-gettzinfo.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-iscntrl.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-tolower.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-rshift.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-time.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-ispunct.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-tzset.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-raise.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-systimes.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-islower.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isdigit.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-stdio.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-environ.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcmp.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-tzlock.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strcspn.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-syswrite.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-abs.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-syssbrk.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strtol.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-fclose.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-month_lengths.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-atol.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-strrchr.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-impure.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isprint.*( .literal .literal.* .text .text.*) + *libc-psram-workaround.a:lib_a-isalpha.*( .literal .literal.* .text .text.*) + *libfreertos.a:( .literal .literal.* .text .text.*) + *libgcov.a:( .literal .literal.* .text .text.*) + *libxtensa-debug-module.a:eri.*( .literal .literal.* .text .text.*) + *libheap.a:multi_heap_poisoning.*( .literal .literal.* .text .text.*) + *libheap.a:multi_heap.*( .literal .literal.* .text .text.*) + + _iram_text_end = ABSOLUTE(.); + _iram_end = ABSOLUTE(.); + } > iram0_0_seg + + ASSERT(((_iram_text_end - ORIGIN(iram0_0_seg)) <= LENGTH(iram0_0_seg)), + "IRAM0 segment data does not fit.") + + .dram0.data : + { + _data_start = ABSOLUTE(.); + _bt_data_start = ABSOLUTE(.); + *libbt.a:(.data .data.*) + . = ALIGN (4); + _bt_data_end = ABSOLUTE(.); + _btdm_data_start = ABSOLUTE(.); + *libbtdm_app.a:(.data .data.*) + . = ALIGN (4); + _btdm_data_end = ABSOLUTE(.); + *(.gnu.linkonce.d.*) + *(.data1) + *(.sdata) + *(.sdata.*) + *(.gnu.linkonce.s.*) + *(.sdata2) + *(.sdata2.*) + *(.gnu.linkonce.s2.*) + *(.jcr) + + *( .data .data.* .dram1 .dram1.*) + *libapp_trace.a:( .rodata .rodata.*) + *libesp32.a:panic.*( .rodata .rodata.*) + *libphy.a:( .rodata .rodata.*) + *libsoc.a:rtc_clk.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-findfp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memcpy.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strchr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strptime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-creat.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strncmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strftime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-itoa.*( .rodata .rodata.*) + *libc-psram-workaround.a:isatty.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-ctime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-gmtime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-div.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-sbrk.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-setjmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-fputwc.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-system.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isascii.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-atoi.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-open.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-close.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-wbuf.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-sysopen.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strstr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-rand_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-timelocal.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strtok_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-wctomb_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-toascii.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strnlen.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-wsetup.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strncat.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-labs.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-tzcalc_limits.*( .rodata .rodata.*) + *libc-psram-workaround.a:lock.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-utoa.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memrchr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-mktime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strndup.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-bzero.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memset.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-sccl.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-s_fpclassify.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strlen.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-ldiv.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-lcltime_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-gmtime_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-srand.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-fvwrite.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-envlock.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-wcrtomb.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-asctime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-sf_nan.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-asctime_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-refill.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcoll.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcasestr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-fwalk.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memchr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strndup_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:creat.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-ctype_.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-tzvars.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strlcpy.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strspn.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memcmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcat.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strdup.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isblank.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isupper.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memmove.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-makebuf.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-longjmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strtoul.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-toupper.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strncasecmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-rand.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strdup_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcpy.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcasecmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isgraph.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-ungetc.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strlwr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strupr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strsep.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-fflush.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isspace.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-memccpy.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-sysread.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-quorem.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-getenv_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-read.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-lcltime.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-tzset_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strncpy.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-ctime_r.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isalnum.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-sysclose.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strlcat.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-gettzinfo.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-iscntrl.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-tolower.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-rshift.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-time.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-ispunct.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-tzset.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-raise.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-systimes.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-islower.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isdigit.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-stdio.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-environ.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcmp.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-tzlock.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strcspn.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-syswrite.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-abs.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-syssbrk.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strtol.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-fclose.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-month_lengths.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-atol.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-strrchr.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-impure.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isprint.*( .rodata .rodata.*) + *libc-psram-workaround.a:lib_a-isalpha.*( .rodata .rodata.*) + *libgcov.a:( .rodata .rodata.*) + *libheap.a:multi_heap_poisoning.*( .rodata .rodata.*) + *libheap.a:multi_heap.*( .rodata .rodata.*) + + _data_end = ABSOLUTE(.); + . = ALIGN(4); + } > dram0_0_seg + + /*This section holds data that should not be initialized at power up. + The section located in Internal SRAM memory region. The macro _NOINIT + can be used as attribute to place data into this section. + See the esp_attr.h file for more information. + */ + .noinit (NOLOAD): + { + . = ALIGN(4); + _noinit_start = ABSOLUTE(.); + *(.noinit .noinit.*) + . = ALIGN(4) ; + _noinit_end = ABSOLUTE(.); + } > dram0_0_seg + + /* Shared RAM */ + .dram0.bss (NOLOAD) : + { + . = ALIGN (8); + _bss_start = ABSOLUTE(.); + *(.ext_ram.bss*) + _bt_bss_start = ABSOLUTE(.); + *libbt.a:(.bss .bss.* COMMON) + . = ALIGN (4); + _bt_bss_end = ABSOLUTE(.); + _btdm_bss_start = ABSOLUTE(.); + *libbtdm_app.a:(.bss .bss.* COMMON) + . = ALIGN (4); + _btdm_bss_end = ABSOLUTE(.); + + *( .bss .bss.* COMMON) + + *(.dynsbss) + *(.sbss) + *(.sbss.*) + *(.gnu.linkonce.sb.*) + *(.scommon) + *(.sbss2) + *(.sbss2.*) + *(.gnu.linkonce.sb2.*) + *(.dynbss) + *(.share.mem) + *(.gnu.linkonce.b.*) + + . = ALIGN (8); + _bss_end = ABSOLUTE(.); + /* The heap starts right after end of this section */ + _heap_start = ABSOLUTE(.); + } > dram0_0_seg + + ASSERT(((_bss_end - ORIGIN(dram0_0_seg)) <= LENGTH(dram0_0_seg)), + "DRAM segment data does not fit.") + + .flash.rodata : + { + _rodata_start = ABSOLUTE(.); + + *(.rodata_desc .rodata_desc.*) /* Should be the first. App version info. DO NOT PUT ANYTHING BEFORE IT! */ + *(.rodata_custom_desc .rodata_custom_desc.*) /* Should be the second. Custom app version info. DO NOT PUT ANYTHING BEFORE IT! */ + + *(EXCLUDE_FILE(*libapp_trace.a *libesp32.a:panic.* *libphy.a *libsoc.a:rtc_clk.* *libc-psram-workaround.a:lib_a-isalpha.* *libc-psram-workaround.a:lib_a-isprint.* *libc-psram-workaround.a:lib_a-impure.* *libc-psram-workaround.a:lib_a-strrchr.* *libc-psram-workaround.a:lib_a-atol.* *libc-psram-workaround.a:lib_a-month_lengths.* *libc-psram-workaround.a:lib_a-fclose.* *libc-psram-workaround.a:lib_a-strtol.* *libc-psram-workaround.a:lib_a-syssbrk.* *libc-psram-workaround.a:lib_a-abs.* *libc-psram-workaround.a:lib_a-syswrite.* *libc-psram-workaround.a:lib_a-strcspn.* *libc-psram-workaround.a:lib_a-tzlock.* *libc-psram-workaround.a:lib_a-strcmp.* *libc-psram-workaround.a:lib_a-environ.* *libc-psram-workaround.a:lib_a-stdio.* *libc-psram-workaround.a:lib_a-isdigit.* *libc-psram-workaround.a:lib_a-islower.* *libc-psram-workaround.a:lib_a-systimes.* *libc-psram-workaround.a:lib_a-raise.* *libc-psram-workaround.a:lib_a-tzset.* *libc-psram-workaround.a:lib_a-ispunct.* *libc-psram-workaround.a:lib_a-time.* *libc-psram-workaround.a:lib_a-rshift.* *libc-psram-workaround.a:lib_a-tolower.* *libc-psram-workaround.a:lib_a-iscntrl.* *libc-psram-workaround.a:lib_a-gettzinfo.* *libc-psram-workaround.a:lib_a-strlcat.* *libc-psram-workaround.a:lib_a-sysclose.* *libc-psram-workaround.a:lib_a-isalnum.* *libc-psram-workaround.a:lib_a-ctime_r.* *libc-psram-workaround.a:lib_a-strncpy.* *libc-psram-workaround.a:lib_a-tzset_r.* *libc-psram-workaround.a:lib_a-lcltime.* *libc-psram-workaround.a:lib_a-read.* *libc-psram-workaround.a:lib_a-getenv_r.* *libc-psram-workaround.a:lib_a-quorem.* *libc-psram-workaround.a:lib_a-sysread.* *libc-psram-workaround.a:lib_a-memccpy.* *libc-psram-workaround.a:lib_a-isspace.* *libc-psram-workaround.a:lib_a-fflush.* *libc-psram-workaround.a:lib_a-strsep.* *libc-psram-workaround.a:lib_a-strupr.* *libc-psram-workaround.a:lib_a-strlwr.* *libc-psram-workaround.a:lib_a-ungetc.* *libc-psram-workaround.a:lib_a-isgraph.* *libc-psram-workaround.a:lib_a-strcasecmp.* *libc-psram-workaround.a:lib_a-strcpy.* *libc-psram-workaround.a:lib_a-strdup_r.* *libc-psram-workaround.a:lib_a-rand.* *libc-psram-workaround.a:lib_a-strncasecmp.* *libc-psram-workaround.a:lib_a-toupper.* *libc-psram-workaround.a:lib_a-strtoul.* *libc-psram-workaround.a:lib_a-longjmp.* *libc-psram-workaround.a:lib_a-makebuf.* *libc-psram-workaround.a:lib_a-memmove.* *libc-psram-workaround.a:lib_a-isupper.* *libc-psram-workaround.a:lib_a-isblank.* *libc-psram-workaround.a:lib_a-strdup.* *libc-psram-workaround.a:lib_a-strcat.* *libc-psram-workaround.a:lib_a-memcmp.* *libc-psram-workaround.a:lib_a-strspn.* *libc-psram-workaround.a:lib_a-strlcpy.* *libc-psram-workaround.a:lib_a-tzvars.* *libc-psram-workaround.a:lib_a-ctype_.* *libc-psram-workaround.a:creat.* *libc-psram-workaround.a:lib_a-strndup_r.* *libc-psram-workaround.a:lib_a-memchr.* *libc-psram-workaround.a:lib_a-fwalk.* *libc-psram-workaround.a:lib_a-strcasestr.* *libc-psram-workaround.a:lib_a-strcoll.* *libc-psram-workaround.a:lib_a-refill.* *libc-psram-workaround.a:lib_a-asctime_r.* *libc-psram-workaround.a:lib_a-sf_nan.* *libc-psram-workaround.a:lib_a-asctime.* *libc-psram-workaround.a:lib_a-wcrtomb.* *libc-psram-workaround.a:lib_a-envlock.* *libc-psram-workaround.a:lib_a-fvwrite.* *libc-psram-workaround.a:lib_a-srand.* *libc-psram-workaround.a:lib_a-gmtime_r.* *libc-psram-workaround.a:lib_a-lcltime_r.* *libc-psram-workaround.a:lib_a-ldiv.* *libc-psram-workaround.a:lib_a-strlen.* *libc-psram-workaround.a:lib_a-s_fpclassify.* *libc-psram-workaround.a:lib_a-sccl.* *libc-psram-workaround.a:lib_a-memset.* *libc-psram-workaround.a:lib_a-bzero.* *libc-psram-workaround.a:lib_a-strndup.* *libc-psram-workaround.a:lib_a-mktime.* *libc-psram-workaround.a:lib_a-memrchr.* *libc-psram-workaround.a:lib_a-utoa.* *libc-psram-workaround.a:lock.* *libc-psram-workaround.a:lib_a-tzcalc_limits.* *libc-psram-workaround.a:lib_a-labs.* *libc-psram-workaround.a:lib_a-strncat.* *libc-psram-workaround.a:lib_a-wsetup.* *libc-psram-workaround.a:lib_a-strnlen.* *libc-psram-workaround.a:lib_a-toascii.* *libc-psram-workaround.a:lib_a-wctomb_r.* *libc-psram-workaround.a:lib_a-strtok_r.* *libc-psram-workaround.a:lib_a-timelocal.* *libc-psram-workaround.a:lib_a-rand_r.* *libc-psram-workaround.a:lib_a-strstr.* *libc-psram-workaround.a:lib_a-sysopen.* *libc-psram-workaround.a:lib_a-wbuf.* *libc-psram-workaround.a:lib_a-close.* *libc-psram-workaround.a:lib_a-open.* *libc-psram-workaround.a:lib_a-atoi.* *libc-psram-workaround.a:lib_a-isascii.* *libc-psram-workaround.a:lib_a-system.* *libc-psram-workaround.a:lib_a-fputwc.* *libc-psram-workaround.a:lib_a-setjmp.* *libc-psram-workaround.a:lib_a-sbrk.* *libc-psram-workaround.a:lib_a-div.* *libc-psram-workaround.a:lib_a-gmtime.* *libc-psram-workaround.a:lib_a-ctime.* *libc-psram-workaround.a:isatty.* *libc-psram-workaround.a:lib_a-itoa.* *libc-psram-workaround.a:lib_a-strftime.* *libc-psram-workaround.a:lib_a-strncmp.* *libc-psram-workaround.a:lib_a-creat.* *libc-psram-workaround.a:lib_a-strptime.* *libc-psram-workaround.a:lib_a-strchr.* *libc-psram-workaround.a:lib_a-memcpy.* *libc-psram-workaround.a:lib_a-findfp.* *libgcov.a *libheap.a:multi_heap.* *libheap.a:multi_heap_poisoning.*) .rodata EXCLUDE_FILE(*libapp_trace.a *libesp32.a:panic.* *libphy.a *libsoc.a:rtc_clk.* *libc-psram-workaround.a:lib_a-isalpha.* *libc-psram-workaround.a:lib_a-isprint.* *libc-psram-workaround.a:lib_a-impure.* *libc-psram-workaround.a:lib_a-strrchr.* *libc-psram-workaround.a:lib_a-atol.* *libc-psram-workaround.a:lib_a-month_lengths.* *libc-psram-workaround.a:lib_a-fclose.* *libc-psram-workaround.a:lib_a-strtol.* *libc-psram-workaround.a:lib_a-syssbrk.* *libc-psram-workaround.a:lib_a-abs.* *libc-psram-workaround.a:lib_a-syswrite.* *libc-psram-workaround.a:lib_a-strcspn.* *libc-psram-workaround.a:lib_a-tzlock.* *libc-psram-workaround.a:lib_a-strcmp.* *libc-psram-workaround.a:lib_a-environ.* *libc-psram-workaround.a:lib_a-stdio.* *libc-psram-workaround.a:lib_a-isdigit.* *libc-psram-workaround.a:lib_a-islower.* *libc-psram-workaround.a:lib_a-systimes.* *libc-psram-workaround.a:lib_a-raise.* *libc-psram-workaround.a:lib_a-tzset.* *libc-psram-workaround.a:lib_a-ispunct.* *libc-psram-workaround.a:lib_a-time.* *libc-psram-workaround.a:lib_a-rshift.* *libc-psram-workaround.a:lib_a-tolower.* *libc-psram-workaround.a:lib_a-iscntrl.* *libc-psram-workaround.a:lib_a-gettzinfo.* *libc-psram-workaround.a:lib_a-strlcat.* *libc-psram-workaround.a:lib_a-sysclose.* *libc-psram-workaround.a:lib_a-isalnum.* *libc-psram-workaround.a:lib_a-ctime_r.* *libc-psram-workaround.a:lib_a-strncpy.* *libc-psram-workaround.a:lib_a-tzset_r.* *libc-psram-workaround.a:lib_a-lcltime.* *libc-psram-workaround.a:lib_a-read.* *libc-psram-workaround.a:lib_a-getenv_r.* *libc-psram-workaround.a:lib_a-quorem.* *libc-psram-workaround.a:lib_a-sysread.* *libc-psram-workaround.a:lib_a-memccpy.* *libc-psram-workaround.a:lib_a-isspace.* *libc-psram-workaround.a:lib_a-fflush.* *libc-psram-workaround.a:lib_a-strsep.* *libc-psram-workaround.a:lib_a-strupr.* *libc-psram-workaround.a:lib_a-strlwr.* *libc-psram-workaround.a:lib_a-ungetc.* *libc-psram-workaround.a:lib_a-isgraph.* *libc-psram-workaround.a:lib_a-strcasecmp.* *libc-psram-workaround.a:lib_a-strcpy.* *libc-psram-workaround.a:lib_a-strdup_r.* *libc-psram-workaround.a:lib_a-rand.* *libc-psram-workaround.a:lib_a-strncasecmp.* *libc-psram-workaround.a:lib_a-toupper.* *libc-psram-workaround.a:lib_a-strtoul.* *libc-psram-workaround.a:lib_a-longjmp.* *libc-psram-workaround.a:lib_a-makebuf.* *libc-psram-workaround.a:lib_a-memmove.* *libc-psram-workaround.a:lib_a-isupper.* *libc-psram-workaround.a:lib_a-isblank.* *libc-psram-workaround.a:lib_a-strdup.* *libc-psram-workaround.a:lib_a-strcat.* *libc-psram-workaround.a:lib_a-memcmp.* *libc-psram-workaround.a:lib_a-strspn.* *libc-psram-workaround.a:lib_a-strlcpy.* *libc-psram-workaround.a:lib_a-tzvars.* *libc-psram-workaround.a:lib_a-ctype_.* *libc-psram-workaround.a:creat.* *libc-psram-workaround.a:lib_a-strndup_r.* *libc-psram-workaround.a:lib_a-memchr.* *libc-psram-workaround.a:lib_a-fwalk.* *libc-psram-workaround.a:lib_a-strcasestr.* *libc-psram-workaround.a:lib_a-strcoll.* *libc-psram-workaround.a:lib_a-refill.* *libc-psram-workaround.a:lib_a-asctime_r.* *libc-psram-workaround.a:lib_a-sf_nan.* *libc-psram-workaround.a:lib_a-asctime.* *libc-psram-workaround.a:lib_a-wcrtomb.* *libc-psram-workaround.a:lib_a-envlock.* *libc-psram-workaround.a:lib_a-fvwrite.* *libc-psram-workaround.a:lib_a-srand.* *libc-psram-workaround.a:lib_a-gmtime_r.* *libc-psram-workaround.a:lib_a-lcltime_r.* *libc-psram-workaround.a:lib_a-ldiv.* *libc-psram-workaround.a:lib_a-strlen.* *libc-psram-workaround.a:lib_a-s_fpclassify.* *libc-psram-workaround.a:lib_a-sccl.* *libc-psram-workaround.a:lib_a-memset.* *libc-psram-workaround.a:lib_a-bzero.* *libc-psram-workaround.a:lib_a-strndup.* *libc-psram-workaround.a:lib_a-mktime.* *libc-psram-workaround.a:lib_a-memrchr.* *libc-psram-workaround.a:lib_a-utoa.* *libc-psram-workaround.a:lock.* *libc-psram-workaround.a:lib_a-tzcalc_limits.* *libc-psram-workaround.a:lib_a-labs.* *libc-psram-workaround.a:lib_a-strncat.* *libc-psram-workaround.a:lib_a-wsetup.* *libc-psram-workaround.a:lib_a-strnlen.* *libc-psram-workaround.a:lib_a-toascii.* *libc-psram-workaround.a:lib_a-wctomb_r.* *libc-psram-workaround.a:lib_a-strtok_r.* *libc-psram-workaround.a:lib_a-timelocal.* *libc-psram-workaround.a:lib_a-rand_r.* *libc-psram-workaround.a:lib_a-strstr.* *libc-psram-workaround.a:lib_a-sysopen.* *libc-psram-workaround.a:lib_a-wbuf.* *libc-psram-workaround.a:lib_a-close.* *libc-psram-workaround.a:lib_a-open.* *libc-psram-workaround.a:lib_a-atoi.* *libc-psram-workaround.a:lib_a-isascii.* *libc-psram-workaround.a:lib_a-system.* *libc-psram-workaround.a:lib_a-fputwc.* *libc-psram-workaround.a:lib_a-setjmp.* *libc-psram-workaround.a:lib_a-sbrk.* *libc-psram-workaround.a:lib_a-div.* *libc-psram-workaround.a:lib_a-gmtime.* *libc-psram-workaround.a:lib_a-ctime.* *libc-psram-workaround.a:isatty.* *libc-psram-workaround.a:lib_a-itoa.* *libc-psram-workaround.a:lib_a-strftime.* *libc-psram-workaround.a:lib_a-strncmp.* *libc-psram-workaround.a:lib_a-creat.* *libc-psram-workaround.a:lib_a-strptime.* *libc-psram-workaround.a:lib_a-strchr.* *libc-psram-workaround.a:lib_a-memcpy.* *libc-psram-workaround.a:lib_a-findfp.* *libgcov.a *libheap.a:multi_heap.* *libheap.a:multi_heap_poisoning.*) .rodata.*) + + *(.irom1.text) /* catch stray ICACHE_RODATA_ATTR */ + *(.gnu.linkonce.r.*) + *(.rodata1) + __XT_EXCEPTION_TABLE_ = ABSOLUTE(.); + *(.xt_except_table) + *(.gcc_except_table .gcc_except_table.*) + *(.gnu.linkonce.e.*) + *(.gnu.version_r) + . = (. + 3) & ~ 3; + __eh_frame = ABSOLUTE(.); + KEEP(*(.eh_frame)) + . = (. + 7) & ~ 3; + /* C++ constructor and destructor tables, properly ordered: */ + __init_array_start = ABSOLUTE(.); + KEEP (*crtbegin.*(.ctors)) + KEEP (*(EXCLUDE_FILE (*crtend.*) .ctors)) + KEEP (*(SORT(.ctors.*))) + KEEP (*(.ctors)) + __init_array_end = ABSOLUTE(.); + KEEP (*crtbegin.*(.dtors)) + KEEP (*(EXCLUDE_FILE (*crtend.*) .dtors)) + KEEP (*(SORT(.dtors.*))) + KEEP (*(.dtors)) + /* C++ exception handlers table: */ + __XT_EXCEPTION_DESCS_ = ABSOLUTE(.); + *(.xt_except_desc) + *(.gnu.linkonce.h.*) + __XT_EXCEPTION_DESCS_END__ = ABSOLUTE(.); + *(.xt_except_desc_end) + *(.dynamic) + *(.gnu.version_d) + /* Addresses of memory regions reserved via + SOC_RESERVE_MEMORY_REGION() */ + soc_reserved_memory_region_start = ABSOLUTE(.); + KEEP (*(.reserved_memory_address)) + soc_reserved_memory_region_end = ABSOLUTE(.); + _rodata_end = ABSOLUTE(.); + /* Literals are also RO data. */ + _lit4_start = ABSOLUTE(.); + *(*.lit4) + *(.lit4.*) + *(.gnu.linkonce.lit4.*) + _lit4_end = ABSOLUTE(.); + . = ALIGN(4); + _thread_local_start = ABSOLUTE(.); + *(.tdata) + *(.tdata.*) + *(.tbss) + *(.tbss.*) + _thread_local_end = ABSOLUTE(.); + . = ALIGN(4); + } >drom0_0_seg + + .flash.text : + { + _stext = .; + _text_start = ABSOLUTE(.); + + *(EXCLUDE_FILE(*libspi_flash.a:spi_flash_rom_patch.* *libesp_ringbuf.a *libhal.a *libapp_trace.a *libesp32.a:panic.* *libespcoredump.a:core_dump_port.* *libespcoredump.a:core_dump_common.* *libespcoredump.a:core_dump_flash.* *libespcoredump.a:core_dump_uart.* *librtc.a *libgcc.a:lib2funcs.* *libsoc.a:rtc_clk_init.* *libsoc.a:cpu_util.* *libsoc.a:rtc_pm.* *libsoc.a:rtc_wdt.* *libsoc.a:rtc_periph.* *libsoc.a:rtc_time.* *libsoc.a:rtc_sleep.* *libsoc.a:rtc_init.* *libsoc.a:rtc_clk.* *libc-psram-workaround.a:lib_a-isalpha.* *libc-psram-workaround.a:lib_a-isprint.* *libc-psram-workaround.a:lib_a-impure.* *libc-psram-workaround.a:lib_a-strrchr.* *libc-psram-workaround.a:lib_a-atol.* *libc-psram-workaround.a:lib_a-month_lengths.* *libc-psram-workaround.a:lib_a-fclose.* *libc-psram-workaround.a:lib_a-strtol.* *libc-psram-workaround.a:lib_a-syssbrk.* *libc-psram-workaround.a:lib_a-abs.* *libc-psram-workaround.a:lib_a-syswrite.* *libc-psram-workaround.a:lib_a-strcspn.* *libc-psram-workaround.a:lib_a-tzlock.* *libc-psram-workaround.a:lib_a-strcmp.* *libc-psram-workaround.a:lib_a-environ.* *libc-psram-workaround.a:lib_a-stdio.* *libc-psram-workaround.a:lib_a-isdigit.* *libc-psram-workaround.a:lib_a-islower.* *libc-psram-workaround.a:lib_a-systimes.* *libc-psram-workaround.a:lib_a-raise.* *libc-psram-workaround.a:lib_a-tzset.* *libc-psram-workaround.a:lib_a-ispunct.* *libc-psram-workaround.a:lib_a-time.* *libc-psram-workaround.a:lib_a-rshift.* *libc-psram-workaround.a:lib_a-tolower.* *libc-psram-workaround.a:lib_a-iscntrl.* *libc-psram-workaround.a:lib_a-gettzinfo.* *libc-psram-workaround.a:lib_a-strlcat.* *libc-psram-workaround.a:lib_a-sysclose.* *libc-psram-workaround.a:lib_a-isalnum.* *libc-psram-workaround.a:lib_a-ctime_r.* *libc-psram-workaround.a:lib_a-strncpy.* *libc-psram-workaround.a:lib_a-tzset_r.* *libc-psram-workaround.a:lib_a-lcltime.* *libc-psram-workaround.a:lib_a-read.* *libc-psram-workaround.a:lib_a-getenv_r.* *libc-psram-workaround.a:lib_a-quorem.* *libc-psram-workaround.a:lib_a-sysread.* *libc-psram-workaround.a:lib_a-memccpy.* *libc-psram-workaround.a:lib_a-isspace.* *libc-psram-workaround.a:lib_a-fflush.* *libc-psram-workaround.a:lib_a-strsep.* *libc-psram-workaround.a:lib_a-strupr.* *libc-psram-workaround.a:lib_a-strlwr.* *libc-psram-workaround.a:lib_a-ungetc.* *libc-psram-workaround.a:lib_a-isgraph.* *libc-psram-workaround.a:lib_a-strcasecmp.* *libc-psram-workaround.a:lib_a-strcpy.* *libc-psram-workaround.a:lib_a-strdup_r.* *libc-psram-workaround.a:lib_a-rand.* *libc-psram-workaround.a:lib_a-strncasecmp.* *libc-psram-workaround.a:lib_a-toupper.* *libc-psram-workaround.a:lib_a-strtoul.* *libc-psram-workaround.a:lib_a-longjmp.* *libc-psram-workaround.a:lib_a-makebuf.* *libc-psram-workaround.a:lib_a-memmove.* *libc-psram-workaround.a:lib_a-isupper.* *libc-psram-workaround.a:lib_a-isblank.* *libc-psram-workaround.a:lib_a-strdup.* *libc-psram-workaround.a:lib_a-strcat.* *libc-psram-workaround.a:lib_a-memcmp.* *libc-psram-workaround.a:lib_a-strspn.* *libc-psram-workaround.a:lib_a-strlcpy.* *libc-psram-workaround.a:lib_a-tzvars.* *libc-psram-workaround.a:lib_a-ctype_.* *libc-psram-workaround.a:creat.* *libc-psram-workaround.a:lib_a-strndup_r.* *libc-psram-workaround.a:lib_a-memchr.* *libc-psram-workaround.a:lib_a-fwalk.* *libc-psram-workaround.a:lib_a-strcasestr.* *libc-psram-workaround.a:lib_a-strcoll.* *libc-psram-workaround.a:lib_a-refill.* *libc-psram-workaround.a:lib_a-asctime_r.* *libc-psram-workaround.a:lib_a-sf_nan.* *libc-psram-workaround.a:lib_a-asctime.* *libc-psram-workaround.a:lib_a-wcrtomb.* *libc-psram-workaround.a:lib_a-envlock.* *libc-psram-workaround.a:lib_a-fvwrite.* *libc-psram-workaround.a:lib_a-srand.* *libc-psram-workaround.a:lib_a-gmtime_r.* *libc-psram-workaround.a:lib_a-lcltime_r.* *libc-psram-workaround.a:lib_a-ldiv.* *libc-psram-workaround.a:lib_a-strlen.* *libc-psram-workaround.a:lib_a-s_fpclassify.* *libc-psram-workaround.a:lib_a-sccl.* *libc-psram-workaround.a:lib_a-memset.* *libc-psram-workaround.a:lib_a-bzero.* *libc-psram-workaround.a:lib_a-strndup.* *libc-psram-workaround.a:lib_a-mktime.* *libc-psram-workaround.a:lib_a-memrchr.* *libc-psram-workaround.a:lib_a-utoa.* *libc-psram-workaround.a:lock.* *libc-psram-workaround.a:lib_a-tzcalc_limits.* *libc-psram-workaround.a:lib_a-labs.* *libc-psram-workaround.a:lib_a-strncat.* *libc-psram-workaround.a:lib_a-wsetup.* *libc-psram-workaround.a:lib_a-strnlen.* *libc-psram-workaround.a:lib_a-toascii.* *libc-psram-workaround.a:lib_a-wctomb_r.* *libc-psram-workaround.a:lib_a-strtok_r.* *libc-psram-workaround.a:lib_a-timelocal.* *libc-psram-workaround.a:lib_a-rand_r.* *libc-psram-workaround.a:lib_a-strstr.* *libc-psram-workaround.a:lib_a-sysopen.* *libc-psram-workaround.a:lib_a-wbuf.* *libc-psram-workaround.a:lib_a-close.* *libc-psram-workaround.a:lib_a-open.* *libc-psram-workaround.a:lib_a-atoi.* *libc-psram-workaround.a:lib_a-isascii.* *libc-psram-workaround.a:lib_a-system.* *libc-psram-workaround.a:lib_a-fputwc.* *libc-psram-workaround.a:lib_a-setjmp.* *libc-psram-workaround.a:lib_a-sbrk.* *libc-psram-workaround.a:lib_a-div.* *libc-psram-workaround.a:lib_a-gmtime.* *libc-psram-workaround.a:lib_a-ctime.* *libc-psram-workaround.a:isatty.* *libc-psram-workaround.a:lib_a-itoa.* *libc-psram-workaround.a:lib_a-strftime.* *libc-psram-workaround.a:lib_a-strncmp.* *libc-psram-workaround.a:lib_a-creat.* *libc-psram-workaround.a:lib_a-strptime.* *libc-psram-workaround.a:lib_a-strchr.* *libc-psram-workaround.a:lib_a-memcpy.* *libc-psram-workaround.a:lib_a-findfp.* *libfreertos.a *libgcov.a *libxtensa-debug-module.a:eri.* *libheap.a:multi_heap.* *libheap.a:multi_heap_poisoning.*) .literal EXCLUDE_FILE(*libspi_flash.a:spi_flash_rom_patch.* *libesp_ringbuf.a *libhal.a *libapp_trace.a *libesp32.a:panic.* *libespcoredump.a:core_dump_port.* *libespcoredump.a:core_dump_common.* *libespcoredump.a:core_dump_flash.* *libespcoredump.a:core_dump_uart.* *librtc.a *libgcc.a:lib2funcs.* *libsoc.a:rtc_clk_init.* *libsoc.a:cpu_util.* *libsoc.a:rtc_pm.* *libsoc.a:rtc_wdt.* *libsoc.a:rtc_periph.* *libsoc.a:rtc_time.* *libsoc.a:rtc_sleep.* *libsoc.a:rtc_init.* *libsoc.a:rtc_clk.* *libc-psram-workaround.a:lib_a-isalpha.* *libc-psram-workaround.a:lib_a-isprint.* *libc-psram-workaround.a:lib_a-impure.* *libc-psram-workaround.a:lib_a-strrchr.* *libc-psram-workaround.a:lib_a-atol.* *libc-psram-workaround.a:lib_a-month_lengths.* *libc-psram-workaround.a:lib_a-fclose.* *libc-psram-workaround.a:lib_a-strtol.* *libc-psram-workaround.a:lib_a-syssbrk.* *libc-psram-workaround.a:lib_a-abs.* *libc-psram-workaround.a:lib_a-syswrite.* *libc-psram-workaround.a:lib_a-strcspn.* *libc-psram-workaround.a:lib_a-tzlock.* *libc-psram-workaround.a:lib_a-strcmp.* *libc-psram-workaround.a:lib_a-environ.* *libc-psram-workaround.a:lib_a-stdio.* *libc-psram-workaround.a:lib_a-isdigit.* *libc-psram-workaround.a:lib_a-islower.* *libc-psram-workaround.a:lib_a-systimes.* *libc-psram-workaround.a:lib_a-raise.* *libc-psram-workaround.a:lib_a-tzset.* *libc-psram-workaround.a:lib_a-ispunct.* *libc-psram-workaround.a:lib_a-time.* *libc-psram-workaround.a:lib_a-rshift.* *libc-psram-workaround.a:lib_a-tolower.* *libc-psram-workaround.a:lib_a-iscntrl.* *libc-psram-workaround.a:lib_a-gettzinfo.* *libc-psram-workaround.a:lib_a-strlcat.* *libc-psram-workaround.a:lib_a-sysclose.* *libc-psram-workaround.a:lib_a-isalnum.* *libc-psram-workaround.a:lib_a-ctime_r.* *libc-psram-workaround.a:lib_a-strncpy.* *libc-psram-workaround.a:lib_a-tzset_r.* *libc-psram-workaround.a:lib_a-lcltime.* *libc-psram-workaround.a:lib_a-read.* *libc-psram-workaround.a:lib_a-getenv_r.* *libc-psram-workaround.a:lib_a-quorem.* *libc-psram-workaround.a:lib_a-sysread.* *libc-psram-workaround.a:lib_a-memccpy.* *libc-psram-workaround.a:lib_a-isspace.* *libc-psram-workaround.a:lib_a-fflush.* *libc-psram-workaround.a:lib_a-strsep.* *libc-psram-workaround.a:lib_a-strupr.* *libc-psram-workaround.a:lib_a-strlwr.* *libc-psram-workaround.a:lib_a-ungetc.* *libc-psram-workaround.a:lib_a-isgraph.* *libc-psram-workaround.a:lib_a-strcasecmp.* *libc-psram-workaround.a:lib_a-strcpy.* *libc-psram-workaround.a:lib_a-strdup_r.* *libc-psram-workaround.a:lib_a-rand.* *libc-psram-workaround.a:lib_a-strncasecmp.* *libc-psram-workaround.a:lib_a-toupper.* *libc-psram-workaround.a:lib_a-strtoul.* *libc-psram-workaround.a:lib_a-longjmp.* *libc-psram-workaround.a:lib_a-makebuf.* *libc-psram-workaround.a:lib_a-memmove.* *libc-psram-workaround.a:lib_a-isupper.* *libc-psram-workaround.a:lib_a-isblank.* *libc-psram-workaround.a:lib_a-strdup.* *libc-psram-workaround.a:lib_a-strcat.* *libc-psram-workaround.a:lib_a-memcmp.* *libc-psram-workaround.a:lib_a-strspn.* *libc-psram-workaround.a:lib_a-strlcpy.* *libc-psram-workaround.a:lib_a-tzvars.* *libc-psram-workaround.a:lib_a-ctype_.* *libc-psram-workaround.a:creat.* *libc-psram-workaround.a:lib_a-strndup_r.* *libc-psram-workaround.a:lib_a-memchr.* *libc-psram-workaround.a:lib_a-fwalk.* *libc-psram-workaround.a:lib_a-strcasestr.* *libc-psram-workaround.a:lib_a-strcoll.* *libc-psram-workaround.a:lib_a-refill.* *libc-psram-workaround.a:lib_a-asctime_r.* *libc-psram-workaround.a:lib_a-sf_nan.* *libc-psram-workaround.a:lib_a-asctime.* *libc-psram-workaround.a:lib_a-wcrtomb.* *libc-psram-workaround.a:lib_a-envlock.* *libc-psram-workaround.a:lib_a-fvwrite.* *libc-psram-workaround.a:lib_a-srand.* *libc-psram-workaround.a:lib_a-gmtime_r.* *libc-psram-workaround.a:lib_a-lcltime_r.* *libc-psram-workaround.a:lib_a-ldiv.* *libc-psram-workaround.a:lib_a-strlen.* *libc-psram-workaround.a:lib_a-s_fpclassify.* *libc-psram-workaround.a:lib_a-sccl.* *libc-psram-workaround.a:lib_a-memset.* *libc-psram-workaround.a:lib_a-bzero.* *libc-psram-workaround.a:lib_a-strndup.* *libc-psram-workaround.a:lib_a-mktime.* *libc-psram-workaround.a:lib_a-memrchr.* *libc-psram-workaround.a:lib_a-utoa.* *libc-psram-workaround.a:lock.* *libc-psram-workaround.a:lib_a-tzcalc_limits.* *libc-psram-workaround.a:lib_a-labs.* *libc-psram-workaround.a:lib_a-strncat.* *libc-psram-workaround.a:lib_a-wsetup.* *libc-psram-workaround.a:lib_a-strnlen.* *libc-psram-workaround.a:lib_a-toascii.* *libc-psram-workaround.a:lib_a-wctomb_r.* *libc-psram-workaround.a:lib_a-strtok_r.* *libc-psram-workaround.a:lib_a-timelocal.* *libc-psram-workaround.a:lib_a-rand_r.* *libc-psram-workaround.a:lib_a-strstr.* *libc-psram-workaround.a:lib_a-sysopen.* *libc-psram-workaround.a:lib_a-wbuf.* *libc-psram-workaround.a:lib_a-close.* *libc-psram-workaround.a:lib_a-open.* *libc-psram-workaround.a:lib_a-atoi.* *libc-psram-workaround.a:lib_a-isascii.* *libc-psram-workaround.a:lib_a-system.* *libc-psram-workaround.a:lib_a-fputwc.* *libc-psram-workaround.a:lib_a-setjmp.* *libc-psram-workaround.a:lib_a-sbrk.* *libc-psram-workaround.a:lib_a-div.* *libc-psram-workaround.a:lib_a-gmtime.* *libc-psram-workaround.a:lib_a-ctime.* *libc-psram-workaround.a:isatty.* *libc-psram-workaround.a:lib_a-itoa.* *libc-psram-workaround.a:lib_a-strftime.* *libc-psram-workaround.a:lib_a-strncmp.* *libc-psram-workaround.a:lib_a-creat.* *libc-psram-workaround.a:lib_a-strptime.* *libc-psram-workaround.a:lib_a-strchr.* *libc-psram-workaround.a:lib_a-memcpy.* *libc-psram-workaround.a:lib_a-findfp.* *libfreertos.a *libgcov.a *libxtensa-debug-module.a:eri.* *libheap.a:multi_heap.* *libheap.a:multi_heap_poisoning.*) .literal.* EXCLUDE_FILE(*libspi_flash.a:spi_flash_rom_patch.* *libesp_ringbuf.a *libhal.a *libapp_trace.a *libesp32.a:panic.* *libespcoredump.a:core_dump_port.* *libespcoredump.a:core_dump_common.* *libespcoredump.a:core_dump_flash.* *libespcoredump.a:core_dump_uart.* *librtc.a *libgcc.a:lib2funcs.* *libsoc.a:rtc_clk_init.* *libsoc.a:cpu_util.* *libsoc.a:rtc_pm.* *libsoc.a:rtc_wdt.* *libsoc.a:rtc_periph.* *libsoc.a:rtc_time.* *libsoc.a:rtc_sleep.* *libsoc.a:rtc_init.* *libsoc.a:rtc_clk.* *libc-psram-workaround.a:lib_a-isalpha.* *libc-psram-workaround.a:lib_a-isprint.* *libc-psram-workaround.a:lib_a-impure.* *libc-psram-workaround.a:lib_a-strrchr.* *libc-psram-workaround.a:lib_a-atol.* *libc-psram-workaround.a:lib_a-month_lengths.* *libc-psram-workaround.a:lib_a-fclose.* *libc-psram-workaround.a:lib_a-strtol.* *libc-psram-workaround.a:lib_a-syssbrk.* *libc-psram-workaround.a:lib_a-abs.* *libc-psram-workaround.a:lib_a-syswrite.* *libc-psram-workaround.a:lib_a-strcspn.* *libc-psram-workaround.a:lib_a-tzlock.* *libc-psram-workaround.a:lib_a-strcmp.* *libc-psram-workaround.a:lib_a-environ.* *libc-psram-workaround.a:lib_a-stdio.* *libc-psram-workaround.a:lib_a-isdigit.* *libc-psram-workaround.a:lib_a-islower.* *libc-psram-workaround.a:lib_a-systimes.* *libc-psram-workaround.a:lib_a-raise.* *libc-psram-workaround.a:lib_a-tzset.* *libc-psram-workaround.a:lib_a-ispunct.* *libc-psram-workaround.a:lib_a-time.* *libc-psram-workaround.a:lib_a-rshift.* *libc-psram-workaround.a:lib_a-tolower.* *libc-psram-workaround.a:lib_a-iscntrl.* *libc-psram-workaround.a:lib_a-gettzinfo.* *libc-psram-workaround.a:lib_a-strlcat.* *libc-psram-workaround.a:lib_a-sysclose.* *libc-psram-workaround.a:lib_a-isalnum.* *libc-psram-workaround.a:lib_a-ctime_r.* *libc-psram-workaround.a:lib_a-strncpy.* *libc-psram-workaround.a:lib_a-tzset_r.* *libc-psram-workaround.a:lib_a-lcltime.* *libc-psram-workaround.a:lib_a-read.* *libc-psram-workaround.a:lib_a-getenv_r.* *libc-psram-workaround.a:lib_a-quorem.* *libc-psram-workaround.a:lib_a-sysread.* *libc-psram-workaround.a:lib_a-memccpy.* *libc-psram-workaround.a:lib_a-isspace.* *libc-psram-workaround.a:lib_a-fflush.* *libc-psram-workaround.a:lib_a-strsep.* *libc-psram-workaround.a:lib_a-strupr.* *libc-psram-workaround.a:lib_a-strlwr.* *libc-psram-workaround.a:lib_a-ungetc.* *libc-psram-workaround.a:lib_a-isgraph.* *libc-psram-workaround.a:lib_a-strcasecmp.* *libc-psram-workaround.a:lib_a-strcpy.* *libc-psram-workaround.a:lib_a-strdup_r.* *libc-psram-workaround.a:lib_a-rand.* *libc-psram-workaround.a:lib_a-strncasecmp.* *libc-psram-workaround.a:lib_a-toupper.* *libc-psram-workaround.a:lib_a-strtoul.* *libc-psram-workaround.a:lib_a-longjmp.* *libc-psram-workaround.a:lib_a-makebuf.* *libc-psram-workaround.a:lib_a-memmove.* *libc-psram-workaround.a:lib_a-isupper.* *libc-psram-workaround.a:lib_a-isblank.* *libc-psram-workaround.a:lib_a-strdup.* *libc-psram-workaround.a:lib_a-strcat.* *libc-psram-workaround.a:lib_a-memcmp.* *libc-psram-workaround.a:lib_a-strspn.* *libc-psram-workaround.a:lib_a-strlcpy.* *libc-psram-workaround.a:lib_a-tzvars.* *libc-psram-workaround.a:lib_a-ctype_.* *libc-psram-workaround.a:creat.* *libc-psram-workaround.a:lib_a-strndup_r.* *libc-psram-workaround.a:lib_a-memchr.* *libc-psram-workaround.a:lib_a-fwalk.* *libc-psram-workaround.a:lib_a-strcasestr.* *libc-psram-workaround.a:lib_a-strcoll.* *libc-psram-workaround.a:lib_a-refill.* *libc-psram-workaround.a:lib_a-asctime_r.* *libc-psram-workaround.a:lib_a-sf_nan.* *libc-psram-workaround.a:lib_a-asctime.* *libc-psram-workaround.a:lib_a-wcrtomb.* *libc-psram-workaround.a:lib_a-envlock.* *libc-psram-workaround.a:lib_a-fvwrite.* *libc-psram-workaround.a:lib_a-srand.* *libc-psram-workaround.a:lib_a-gmtime_r.* *libc-psram-workaround.a:lib_a-lcltime_r.* *libc-psram-workaround.a:lib_a-ldiv.* *libc-psram-workaround.a:lib_a-strlen.* *libc-psram-workaround.a:lib_a-s_fpclassify.* *libc-psram-workaround.a:lib_a-sccl.* *libc-psram-workaround.a:lib_a-memset.* *libc-psram-workaround.a:lib_a-bzero.* *libc-psram-workaround.a:lib_a-strndup.* *libc-psram-workaround.a:lib_a-mktime.* *libc-psram-workaround.a:lib_a-memrchr.* *libc-psram-workaround.a:lib_a-utoa.* *libc-psram-workaround.a:lock.* *libc-psram-workaround.a:lib_a-tzcalc_limits.* *libc-psram-workaround.a:lib_a-labs.* *libc-psram-workaround.a:lib_a-strncat.* *libc-psram-workaround.a:lib_a-wsetup.* *libc-psram-workaround.a:lib_a-strnlen.* *libc-psram-workaround.a:lib_a-toascii.* *libc-psram-workaround.a:lib_a-wctomb_r.* *libc-psram-workaround.a:lib_a-strtok_r.* *libc-psram-workaround.a:lib_a-timelocal.* *libc-psram-workaround.a:lib_a-rand_r.* *libc-psram-workaround.a:lib_a-strstr.* *libc-psram-workaround.a:lib_a-sysopen.* *libc-psram-workaround.a:lib_a-wbuf.* *libc-psram-workaround.a:lib_a-close.* *libc-psram-workaround.a:lib_a-open.* *libc-psram-workaround.a:lib_a-atoi.* *libc-psram-workaround.a:lib_a-isascii.* *libc-psram-workaround.a:lib_a-system.* *libc-psram-workaround.a:lib_a-fputwc.* *libc-psram-workaround.a:lib_a-setjmp.* *libc-psram-workaround.a:lib_a-sbrk.* *libc-psram-workaround.a:lib_a-div.* *libc-psram-workaround.a:lib_a-gmtime.* *libc-psram-workaround.a:lib_a-ctime.* *libc-psram-workaround.a:isatty.* *libc-psram-workaround.a:lib_a-itoa.* *libc-psram-workaround.a:lib_a-strftime.* *libc-psram-workaround.a:lib_a-strncmp.* *libc-psram-workaround.a:lib_a-creat.* *libc-psram-workaround.a:lib_a-strptime.* *libc-psram-workaround.a:lib_a-strchr.* *libc-psram-workaround.a:lib_a-memcpy.* *libc-psram-workaround.a:lib_a-findfp.* *libfreertos.a *libgcov.a *libxtensa-debug-module.a:eri.* *libheap.a:multi_heap.* *libheap.a:multi_heap_poisoning.*) .text EXCLUDE_FILE(*libspi_flash.a:spi_flash_rom_patch.* *libesp_ringbuf.a *libhal.a *libapp_trace.a *libesp32.a:panic.* *libespcoredump.a:core_dump_port.* *libespcoredump.a:core_dump_common.* *libespcoredump.a:core_dump_flash.* *libespcoredump.a:core_dump_uart.* *librtc.a *libgcc.a:lib2funcs.* *libsoc.a:rtc_clk_init.* *libsoc.a:cpu_util.* *libsoc.a:rtc_pm.* *libsoc.a:rtc_wdt.* *libsoc.a:rtc_periph.* *libsoc.a:rtc_time.* *libsoc.a:rtc_sleep.* *libsoc.a:rtc_init.* *libsoc.a:rtc_clk.* *libc-psram-workaround.a:lib_a-isalpha.* *libc-psram-workaround.a:lib_a-isprint.* *libc-psram-workaround.a:lib_a-impure.* *libc-psram-workaround.a:lib_a-strrchr.* *libc-psram-workaround.a:lib_a-atol.* *libc-psram-workaround.a:lib_a-month_lengths.* *libc-psram-workaround.a:lib_a-fclose.* *libc-psram-workaround.a:lib_a-strtol.* *libc-psram-workaround.a:lib_a-syssbrk.* *libc-psram-workaround.a:lib_a-abs.* *libc-psram-workaround.a:lib_a-syswrite.* *libc-psram-workaround.a:lib_a-strcspn.* *libc-psram-workaround.a:lib_a-tzlock.* *libc-psram-workaround.a:lib_a-strcmp.* *libc-psram-workaround.a:lib_a-environ.* *libc-psram-workaround.a:lib_a-stdio.* *libc-psram-workaround.a:lib_a-isdigit.* *libc-psram-workaround.a:lib_a-islower.* *libc-psram-workaround.a:lib_a-systimes.* *libc-psram-workaround.a:lib_a-raise.* *libc-psram-workaround.a:lib_a-tzset.* *libc-psram-workaround.a:lib_a-ispunct.* *libc-psram-workaround.a:lib_a-time.* *libc-psram-workaround.a:lib_a-rshift.* *libc-psram-workaround.a:lib_a-tolower.* *libc-psram-workaround.a:lib_a-iscntrl.* *libc-psram-workaround.a:lib_a-gettzinfo.* *libc-psram-workaround.a:lib_a-strlcat.* *libc-psram-workaround.a:lib_a-sysclose.* *libc-psram-workaround.a:lib_a-isalnum.* *libc-psram-workaround.a:lib_a-ctime_r.* *libc-psram-workaround.a:lib_a-strncpy.* *libc-psram-workaround.a:lib_a-tzset_r.* *libc-psram-workaround.a:lib_a-lcltime.* *libc-psram-workaround.a:lib_a-read.* *libc-psram-workaround.a:lib_a-getenv_r.* *libc-psram-workaround.a:lib_a-quorem.* *libc-psram-workaround.a:lib_a-sysread.* *libc-psram-workaround.a:lib_a-memccpy.* *libc-psram-workaround.a:lib_a-isspace.* *libc-psram-workaround.a:lib_a-fflush.* *libc-psram-workaround.a:lib_a-strsep.* *libc-psram-workaround.a:lib_a-strupr.* *libc-psram-workaround.a:lib_a-strlwr.* *libc-psram-workaround.a:lib_a-ungetc.* *libc-psram-workaround.a:lib_a-isgraph.* *libc-psram-workaround.a:lib_a-strcasecmp.* *libc-psram-workaround.a:lib_a-strcpy.* *libc-psram-workaround.a:lib_a-strdup_r.* *libc-psram-workaround.a:lib_a-rand.* *libc-psram-workaround.a:lib_a-strncasecmp.* *libc-psram-workaround.a:lib_a-toupper.* *libc-psram-workaround.a:lib_a-strtoul.* *libc-psram-workaround.a:lib_a-longjmp.* *libc-psram-workaround.a:lib_a-makebuf.* *libc-psram-workaround.a:lib_a-memmove.* *libc-psram-workaround.a:lib_a-isupper.* *libc-psram-workaround.a:lib_a-isblank.* *libc-psram-workaround.a:lib_a-strdup.* *libc-psram-workaround.a:lib_a-strcat.* *libc-psram-workaround.a:lib_a-memcmp.* *libc-psram-workaround.a:lib_a-strspn.* *libc-psram-workaround.a:lib_a-strlcpy.* *libc-psram-workaround.a:lib_a-tzvars.* *libc-psram-workaround.a:lib_a-ctype_.* *libc-psram-workaround.a:creat.* *libc-psram-workaround.a:lib_a-strndup_r.* *libc-psram-workaround.a:lib_a-memchr.* *libc-psram-workaround.a:lib_a-fwalk.* *libc-psram-workaround.a:lib_a-strcasestr.* *libc-psram-workaround.a:lib_a-strcoll.* *libc-psram-workaround.a:lib_a-refill.* *libc-psram-workaround.a:lib_a-asctime_r.* *libc-psram-workaround.a:lib_a-sf_nan.* *libc-psram-workaround.a:lib_a-asctime.* *libc-psram-workaround.a:lib_a-wcrtomb.* *libc-psram-workaround.a:lib_a-envlock.* *libc-psram-workaround.a:lib_a-fvwrite.* *libc-psram-workaround.a:lib_a-srand.* *libc-psram-workaround.a:lib_a-gmtime_r.* *libc-psram-workaround.a:lib_a-lcltime_r.* *libc-psram-workaround.a:lib_a-ldiv.* *libc-psram-workaround.a:lib_a-strlen.* *libc-psram-workaround.a:lib_a-s_fpclassify.* *libc-psram-workaround.a:lib_a-sccl.* *libc-psram-workaround.a:lib_a-memset.* *libc-psram-workaround.a:lib_a-bzero.* *libc-psram-workaround.a:lib_a-strndup.* *libc-psram-workaround.a:lib_a-mktime.* *libc-psram-workaround.a:lib_a-memrchr.* *libc-psram-workaround.a:lib_a-utoa.* *libc-psram-workaround.a:lock.* *libc-psram-workaround.a:lib_a-tzcalc_limits.* *libc-psram-workaround.a:lib_a-labs.* *libc-psram-workaround.a:lib_a-strncat.* *libc-psram-workaround.a:lib_a-wsetup.* *libc-psram-workaround.a:lib_a-strnlen.* *libc-psram-workaround.a:lib_a-toascii.* *libc-psram-workaround.a:lib_a-wctomb_r.* *libc-psram-workaround.a:lib_a-strtok_r.* *libc-psram-workaround.a:lib_a-timelocal.* *libc-psram-workaround.a:lib_a-rand_r.* *libc-psram-workaround.a:lib_a-strstr.* *libc-psram-workaround.a:lib_a-sysopen.* *libc-psram-workaround.a:lib_a-wbuf.* *libc-psram-workaround.a:lib_a-close.* *libc-psram-workaround.a:lib_a-open.* *libc-psram-workaround.a:lib_a-atoi.* *libc-psram-workaround.a:lib_a-isascii.* *libc-psram-workaround.a:lib_a-system.* *libc-psram-workaround.a:lib_a-fputwc.* *libc-psram-workaround.a:lib_a-setjmp.* *libc-psram-workaround.a:lib_a-sbrk.* *libc-psram-workaround.a:lib_a-div.* *libc-psram-workaround.a:lib_a-gmtime.* *libc-psram-workaround.a:lib_a-ctime.* *libc-psram-workaround.a:isatty.* *libc-psram-workaround.a:lib_a-itoa.* *libc-psram-workaround.a:lib_a-strftime.* *libc-psram-workaround.a:lib_a-strncmp.* *libc-psram-workaround.a:lib_a-creat.* *libc-psram-workaround.a:lib_a-strptime.* *libc-psram-workaround.a:lib_a-strchr.* *libc-psram-workaround.a:lib_a-memcpy.* *libc-psram-workaround.a:lib_a-findfp.* *libfreertos.a *libgcov.a *libxtensa-debug-module.a:eri.* *libheap.a:multi_heap.* *libheap.a:multi_heap_poisoning.*) .text.* .wifi0iram .wifi0iram.*) + + *(.stub .gnu.warning .gnu.linkonce.literal.* .gnu.linkonce.t.*.literal .gnu.linkonce.t.*) + *(.irom0.text) /* catch stray ICACHE_RODATA_ATTR */ + *(.fini.literal) + *(.fini) + *(.gnu.version) + _text_end = ABSOLUTE(.); + _etext = .; + + /* Similar to _iram_start, this symbol goes here so it is + resolved by addr2line in preference to the first symbol in + the flash.text segment. + */ + _flash_cache_start = ABSOLUTE(0); + } >iram0_2_seg +} diff --git a/esp32/esp32.rom.libgcc.ld b/esp32/esp32.rom.libgcc.ld new file mode 100644 index 0000000000..51448b3327 --- /dev/null +++ b/esp32/esp32.rom.libgcc.ld @@ -0,0 +1,91 @@ +__absvdi2 = 0x4006387c; +__absvsi2 = 0x40063868; +__adddf3 = 0x40002590; +__addsf3 = 0x400020e8; +__addvdi3 = 0x40002cbc; +__addvsi3 = 0x40002c98; +__ashldi3 = 0x4000c818; +__ashrdi3 = 0x4000c830; +__bswapdi2 = 0x40064b08; +__bswapsi2 = 0x40064ae0; +__clrsbdi2 = 0x40064b7c; +__clrsbsi2 = 0x40064b64; +__clzdi2 = 0x4000ca50; +__clzsi2 = 0x4000c7e8; +__cmpdi2 = 0x40063820; +__ctzdi2 = 0x4000ca64; +__ctzsi2 = 0x4000c7f0; +__divdc3 = 0x400645a4; +__divdf3 = 0x40002954; +__divdi3 = 0x4000ca84; +__divsc3 = 0x4006429c; +__divsf3 = 0x4000234c; +__divsi3 = 0x4000c7b8; +__eqdf2 = 0x400636a8; +__eqsf2 = 0x40063374; +__extendsfdf2 = 0x40002c34; +__ffsdi2 = 0x4000ca2c; +__ffssi2 = 0x4000c804; +__fixdfdi = 0x40002ac4; +__fixdfsi = 0x40002a78; +__fixsfdi = 0x4000244c; +__fixsfsi = 0x4000240c; +__fixunsdfsi = 0x40002b30; +__fixunssfdi = 0x40002504; +__fixunssfsi = 0x400024ac; +__floatdidf = 0x4000c988; +__floatdisf = 0x4000c8c0; +__floatsidf = 0x4000c944; +__floatsisf = 0x4000c870; +__floatundidf = 0x4000c978; +__floatundisf = 0x4000c8b0; +__floatunsidf = 0x4000c938; +__floatunsisf = 0x4000c864; +__gedf2 = 0x40063768; +__gesf2 = 0x4006340c; +__gtdf2 = 0x400636dc; +__gtsf2 = 0x400633a0; +__ledf2 = 0x40063704; +__lesf2 = 0x400633c0; +__lshrdi3 = 0x4000c84c; +__ltdf2 = 0x40063790; +__ltsf2 = 0x4006342c; +__moddi3 = 0x4000cd4c; +__modsi3 = 0x4000c7c0; +__muldc3 = 0x40063c90; +__muldf3 = 0x4006358c; +__muldi3 = 0x4000c9fc; +__mulsc3 = 0x40063944; +__mulsf3 = 0x400632c8; +__mulsi3 = 0x4000c7b0; +__mulvdi3 = 0x40002d78; +__mulvsi3 = 0x40002d60; +__nedf2 = 0x400636a8; +__negdf2 = 0x400634a0; +__negdi2 = 0x4000ca14; +__negsf2 = 0x400020c0; +__negvdi2 = 0x40002e98; +__negvsi2 = 0x40002e78; +__nesf2 = 0x40063374; +__nsau_data = 0x3ff96544; +__paritysi2 = 0x40002f3c; +__popcount_tab = 0x3ff96544; +__popcountdi2 = 0x40002ef8; +__popcountsi2 = 0x40002ed0; +__powidf2 = 0x400638e4; +__powisf2 = 0x4006389c; +__subdf3 = 0x400026e4; +__subsf3 = 0x400021d0; +__subvdi3 = 0x40002d20; +__subvsi3 = 0x40002cf8; +__truncdfsf2 = 0x40002b90; +__ucmpdi2 = 0x40063840; +__udiv_w_sdiv = 0x40064bec; +__udivdi3 = 0x4000cff8; +__udivmoddi4 = 0x40064bf4; +__udivsi3 = 0x4000c7c8; +__umoddi3 = 0x4000d280; +__umodsi3 = 0x4000c7d0; +__umulsidi3 = 0x4000c7d8; +__unorddf2 = 0x400637f4; +__unordsf2 = 0x40063478; diff --git a/esp32/fatfs/src/drivers/sd_diskio.c b/esp32/fatfs/src/drivers/sd_diskio.c index f5ae8b7a6c..3bd90b2c41 100644 --- a/esp32/fatfs/src/drivers/sd_diskio.c +++ b/esp32/fatfs/src/drivers/sd_diskio.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/fatfs/src/drivers/sd_diskio.h b/esp32/fatfs/src/drivers/sd_diskio.h index 93d9432601..0c1d012da2 100644 --- a/esp32/fatfs/src/drivers/sd_diskio.h +++ b/esp32/fatfs/src/drivers/sd_diskio.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/fatfs/src/drivers/sflash_diskio.c b/esp32/fatfs/src/drivers/sflash_diskio.c index 6e20352a68..421fb98a79 100644 --- a/esp32/fatfs/src/drivers/sflash_diskio.c +++ b/esp32/fatfs/src/drivers/sflash_diskio.c @@ -54,7 +54,7 @@ DRESULT sflash_disk_init (void) { sflash_start_address = SFLASH_START_ADDR_4MB; sflash_fs_sector_count = SFLASH_FS_SECTOR_COUNT_4MB; } - sflash_block_cache = (uint8_t *)heap_caps_malloc(SFLASH_BLOCK_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + sflash_block_cache = (uint8_t *)malloc(SFLASH_BLOCK_SIZE); sflash_prev_block_addr = UINT32_MAX; sflash_cache_is_dirty = false; sflash_init_done = true; diff --git a/esp32/frozen/LTE/sqnsbrz.py b/esp32/frozen/LTE/sqnsbrz.py index a1d9923418..0755c2c8a1 100644 --- a/esp32/frozen/LTE/sqnsbrz.py +++ b/esp32/frozen/LTE/sqnsbrz.py @@ -1,4 +1,4 @@ -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/frozen/LTE/sqnsupgrade.py b/esp32/frozen/LTE/sqnsupgrade.py index 4ada7da510..2aa6a49f2c 100644 --- a/esp32/frozen/LTE/sqnsupgrade.py +++ b/esp32/frozen/LTE/sqnsupgrade.py @@ -1,7 +1,7 @@ #!/usr/bin/env python VERSION = "1.2.6" -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information @@ -527,7 +527,7 @@ def __run(self, file_path=None, baudrate=921600, port=None, resume=False, load_f time.sleep(.5) self.__serial.read(100) print('Going into MIRROR mode... please close this terminal to resume the upgrade via UART') - self.uart_mirror(rgbled) + return self.uart_mirror(rgbled) elif bootrom: if verbose: print('Starting STP') @@ -570,10 +570,10 @@ def __run(self, file_path=None, baudrate=921600, port=None, resume=False, load_f time.sleep(.5) self.__serial.read(100) print('Going into MIRROR mode... please close this terminal to resume the upgrade via UART') - self.uart_mirror(rgbled) + return self.uart_mirror(rgbled) else: self.__serial.write(b"AT+STP\n") - response = self.read_rsp(size=6) + response = self.read_rsp(size=2) if not b'OK' in response: print('Failed to start STP mode!') reconnect_uart() @@ -584,7 +584,7 @@ def __run(self, file_path=None, baudrate=921600, port=None, resume=False, load_f else: if debug: print('Starting STP mode...') self.__serial.write(b"AT+STP\n") - response = self.read_rsp(size=6) + response = self.read_rsp(size=2) if not b'OK' in response: print('Failed to start STP mode!') reconnect_uart() @@ -871,6 +871,7 @@ def uart_mirror(self, color): time.sleep(.5) pycom.rgbled(color) LTE.modem_upgrade_mode() + return True def success_message(self, port=None, verbose=False, debug=False): print("Your modem has been successfully updated.") diff --git a/esp32/frozen/Pybytes/_OTA.py b/esp32/frozen/Pybytes/_OTA.py index ab4f1d0b02..63d20ac3ec 100644 --- a/esp32/frozen/Pybytes/_OTA.py +++ b/esp32/frozen/Pybytes/_OTA.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or @@ -57,20 +57,27 @@ def update_device_network_config(self, fcota, config): def get_current_version(self): return os.uname().release - def get_update_manifest(self): + def get_update_manifest(self, fwtype=None, token=None): current_version = self.get_current_version() sysname = os.uname().sysname wmac = hexlify(machine.unique_id()).decode('ascii') - request_template = "manifest.json?current_ver={}&sysname={}&wmac={}&ota_slot={}" - req = request_template.format(current_version, sysname, wmac, hex(pycom.ota_slot())) + if fwtype == 'pymesh': + request_template = "manifest.json?current_ver={}&sysname={}&token={}&ota_slot={}&wmac={}&fwtype={}¤t_fwtype={}" + req = request_template.format(current_version, sysname, token, hex(pycom.ota_slot()), wmac.upper(), fwtype, 'pymesh' if hasattr(os.uname(),'pymesh') else 'pybytes') + elif fwtype == 'pygate': + request_template = "manifest.json?current_ver={}&sysname={}&ota_slot={}&wmac={}&fwtype={}¤t_fwtype={}" + req = request_template.format(current_version, sysname, hex(pycom.ota_slot()), wmac.upper(), fwtype, 'pygate' if hasattr(os.uname(),'pygate') else 'pybytes') + else: + request_template = "manifest.json?current_ver={}&sysname={}&wmac={}&ota_slot={}" + req = request_template.format(current_version, sysname, wmac, hex(pycom.ota_slot())) manifest_data = self.get_data(req).decode() manifest = ujson.loads(manifest_data) gc.collect() return manifest - def update(self, customManifest=None): + def update(self, customManifest=None, fwtype=None, token=None): try: - manifest = self.get_update_manifest() if not customManifest else customManifest + manifest = self.get_update_manifest(fwtype, token) if not customManifest else customManifest except Exception as e: print('Error reading the manifest, aborting: {}'.format(e)) return 0 @@ -240,7 +247,6 @@ def get_data(self, req, dest_path=None, hash=False, firmware=False): fp = open(dest_path, 'wb') if firmware: - print('start') pycom.ota_start() h = uhashlib.sha1() diff --git a/esp32/frozen/Pybytes/_coap.py b/esp32/frozen/Pybytes/_coap.py new file mode 100644 index 0000000000..234fccd3ac --- /dev/null +++ b/esp32/frozen/Pybytes/_coap.py @@ -0,0 +1,36 @@ +''' +Copyright (c) 2020, Pycom Limited. +This software is licensed under the GNU GPL version 3 or any +later version, with permitted additional terms. For more information +see the Pycom Licence v1.0 document supplied with this file, or +available at https://www.pycom.io/opensource/licensing +''' + +from network import WLAN +from network import Coap +# import uselect +# import _thread +# import machine + + +class COAPClient(): + def __init__(self, target_server, port): + self.__coap_server = target_server + self.__coap_server_port = port + + wlan = WLAN(mode=WLAN.STA) + self.__device_ip = wlan.ifconfig()[0] + + Coap.init(str(wlan.ifconfig()[0]), service_discovery=False) + + def send_coap_message(self, message, method, uri_path, token, include_options=True): + message_id = Coap.send_request( + self.__coap_server, + method, + uri_port=int(self.__coap_server_port), + uri_path=uri_path, + payload=message, + token=token, + include_options=include_options + ) + return message_id diff --git a/esp32/frozen/Pybytes/_flash_control_OTA.py b/esp32/frozen/Pybytes/_flash_control_OTA.py index 7a96cee695..22b195112f 100644 --- a/esp32/frozen/Pybytes/_flash_control_OTA.py +++ b/esp32/frozen/Pybytes/_flash_control_OTA.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/frozen/Pybytes/_main.py b/esp32/frozen/Pybytes/_main.py index 54e77ec3fa..e69de29bb2 100644 --- a/esp32/frozen/Pybytes/_main.py +++ b/esp32/frozen/Pybytes/_main.py @@ -1,99 +0,0 @@ - -''' -Copyright (c) 2019, Pycom Limited. -This software is licensed under the GNU GPL version 3 or any -later version, with permitted additional terms. For more information -see the Pycom Licence v1.0 document supplied with this file, or -available at https://www.pycom.io/opensource/licensing - -This is the main.py file for Pybytes -This code and included libraries are intended for users wishing to fully -customise pybytes. It is the same code that is included in the Pybytes firmware -If you're planning to use the Pybytes firmware, please check out the -examples in the examples directory which are much easier to use. -If you make changes to any of the libraries in the lib directory, -you only need to upload the changed files if using the Pybytes firmware. -The other libraries will be loaded from the built-in code. -If you make changes above "Please put your USER code below this line" while -using a Pybytes enabled firmware, you need to disable auto-start. -You can disable auto-start by setting "pybytes_autostart": false in -pybytes_project.json or pybytes_config.json. -If using the Pybytes firmware, the configuration is already loaded and this -cannot be deactivated. However if you disable auto-start, you can modify the -configuration before connecting to Pybytes manually using pybytes.connect() -''' - -# Load configuration, migrate to pybytes_config.json if necessary -if 'pybytes_config' not in globals().keys(): - try: - from pybytes_config import PybytesConfig - except: - from _pybytes_config import PybytesConfig - try: - from pybytes import Pybytes - except: - from _pybytes import Pybytes - - pybytes_config = PybytesConfig().read_config() - -if (not pybytes_config.get('pybytes_autostart', True)) and pybytes_config.get('cfg_msg') is not None: - print(pybytes_config.get('cfg_msg')) - print("Not starting Pybytes as auto-start is disabled") - -else: - # Load Pybytes if it is not already loaded - if 'pybytes' not in globals().keys(): - pybytes = Pybytes(pybytes_config, pybytes_config.get('cfg_msg') is None, True) - - # Please put your USER code below this line - - # SEND SIGNAL - # You can currently send Strings, Int32, Float32 and Tuples to pybytes using this method. - # pybytes.send_signal(signalNumber, value) - - # SEND SENSOR DATA THROUGH SIGNALS - # # If you use a Pysense, some libraries are necessary to access its sensors - # # you can find them here: https://github.com/pycom/pycom-libraries - # - # # Include the libraries in the lib folder then import the ones you want to use here: - # from SI7006A20 import SI7006A20 - # si = SI7006A20() - # from LTR329ALS01 import LTR329ALS01 - # ltr = LTR329ALS01() - # - # # Import what is necessary to create a thread - # import _thread - # from time import sleep - # from machine import Pin - # - # # Define your thread's behaviour, here it's a loop sending sensors data every 10 seconds - # def send_env_data(): - # while (pybytes): - # pybytes.send_signal(1, si.humidity()) - # pybytes.send_signal(2, si.temperature()) - # pybytes.send_signal(3, ltr.light()); - # sleep(10) - # - # # Start your thread - # _thread.start_new_thread(send_env_data, ()) - - # SET THE BATTERY LEVEL - # pybytes.send_battery_level(23) - - # SEND DIGITAL VALUE - # pybytes.send_digital_pin_value(False, 12, Pin.PULL_UP) - - # SEND ANALOG VALUE - # pybytes.send_analog_pin_value(False, 13) - - # REGISTER PERIODICAL DIGIAL VALUE SEND - # pybytes.register_periodical_digital_pin_publish(False, PIN_NUMBER, Pin.PULL_UP, INTERVAL_SECONDS) - - # REGISTER PERIODICAL ANALOG VALUE SEND - # pybytes.register_periodical_analog_pin_publish(False, PIN_NUMBER, INTERVAL_SECONDS) - - # CUSTOM METHOD EXAMPLE - # def custom_print(params): - # print("Custom method called") - # return [255, 20] - # pybytes.add_custom_method(0, custom_print) diff --git a/esp32/frozen/Pybytes/_main_pybytes.py b/esp32/frozen/Pybytes/_main_pybytes.py new file mode 100644 index 0000000000..f89ab25054 --- /dev/null +++ b/esp32/frozen/Pybytes/_main_pybytes.py @@ -0,0 +1,99 @@ + +''' +Copyright (c) 2020, Pycom Limited. +This software is licensed under the GNU GPL version 3 or any +later version, with permitted additional terms. For more information +see the Pycom Licence v1.0 document supplied with this file, or +available at https://www.pycom.io/opensource/licensing + +This is the main.py file for Pybytes +This code and included libraries are intended for users wishing to fully +customise pybytes. It is the same code that is included in the Pybytes firmware +If you're planning to use the Pybytes firmware, please check out the +examples in the examples directory which are much easier to use. +If you make changes to any of the libraries in the lib directory, +you only need to upload the changed files if using the Pybytes firmware. +The other libraries will be loaded from the built-in code. +If you make changes above "Please put your USER code below this line" while +using a Pybytes enabled firmware, you need to disable auto-start. +You can disable auto-start by setting "pybytes_autostart": false in +pybytes_project.json or pybytes_config.json. +If using the Pybytes firmware, the configuration is already loaded and this +cannot be deactivated. However if you disable auto-start, you can modify the +configuration before connecting to Pybytes manually using pybytes.connect() +''' + +# Load configuration, migrate to pybytes_config.json if necessary +if 'pybytes_config' not in globals().keys(): + try: + from pybytes_config import PybytesConfig + except: + from _pybytes_config import PybytesConfig + try: + from pybytes import Pybytes + except: + from _pybytes import Pybytes + + pybytes_config = PybytesConfig().read_config() + +if (not pybytes_config.get('pybytes_autostart', True)) and pybytes_config.get('cfg_msg') is not None: + print(pybytes_config.get('cfg_msg')) + print("Not starting Pybytes as auto-start is disabled") + +else: + # Load Pybytes if it is not already loaded + if 'pybytes' not in globals().keys(): + pybytes = Pybytes(pybytes_config, pybytes_config.get('cfg_msg') is None, True) + + # Please put your USER code below this line + + # SEND SIGNAL + # You can currently send Strings, Int32, Float32 and Tuples to pybytes using this method. + # pybytes.send_signal(signalNumber, value) + + # SEND SENSOR DATA THROUGH SIGNALS + # # If you use a Pysense, some libraries are necessary to access its sensors + # # you can find them here: https://github.com/pycom/pycom-libraries + # + # # Include the libraries in the lib folder then import the ones you want to use here: + # from SI7006A20 import SI7006A20 + # si = SI7006A20() + # from LTR329ALS01 import LTR329ALS01 + # ltr = LTR329ALS01() + # + # # Import what is necessary to create a thread + # import _thread + # from time import sleep + # from machine import Pin + # + # # Define your thread's behaviour, here it's a loop sending sensors data every 10 seconds + # def send_env_data(): + # while (pybytes): + # pybytes.send_signal(1, si.humidity()) + # pybytes.send_signal(2, si.temperature()) + # pybytes.send_signal(3, ltr.light()); + # sleep(10) + # + # # Start your thread + # _thread.start_new_thread(send_env_data, ()) + + # SET THE BATTERY LEVEL + # pybytes.send_battery_level(23) + + # SEND DIGITAL VALUE + # pybytes.send_digital_pin_value(False, 12, Pin.PULL_UP) + + # SEND ANALOG VALUE + # pybytes.send_analog_pin_value(False, 13) + + # REGISTER PERIODICAL DIGIAL VALUE SEND + # pybytes.register_periodical_digital_pin_publish(False, PIN_NUMBER, Pin.PULL_UP, INTERVAL_SECONDS) + + # REGISTER PERIODICAL ANALOG VALUE SEND + # pybytes.register_periodical_analog_pin_publish(False, PIN_NUMBER, INTERVAL_SECONDS) + + # CUSTOM METHOD EXAMPLE + # def custom_print(params): + # print("Custom method called") + # return [255, 20] + # pybytes.add_custom_method(0, custom_print) diff --git a/esp32/frozen/Pybytes/_mqtt.py b/esp32/frozen/Pybytes/_mqtt.py index aef01a7fa9..89be0d3f73 100644 --- a/esp32/frozen/Pybytes/_mqtt.py +++ b/esp32/frozen/Pybytes/_mqtt.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/frozen/Pybytes/_mqtt_core.py b/esp32/frozen/Pybytes/_mqtt_core.py index 72781f4148..80da83bf98 100644 --- a/esp32/frozen/Pybytes/_mqtt_core.py +++ b/esp32/frozen/Pybytes/_mqtt_core.py @@ -2,7 +2,7 @@ umqtt is a simple MQTT client for MicroPython. Original code: https://github.com/micropython/micropython-lib/tree/master/umqtt.simple -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/frozen/Pybytes/_msg_handl.py b/esp32/frozen/Pybytes/_msg_handl.py index 752b07565b..a1b200587d 100644 --- a/esp32/frozen/Pybytes/_msg_handl.py +++ b/esp32/frozen/Pybytes/_msg_handl.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/frozen/Pybytes/_periodical_pin.py b/esp32/frozen/Pybytes/_periodical_pin.py new file mode 100644 index 0000000000..df2463e552 --- /dev/null +++ b/esp32/frozen/Pybytes/_periodical_pin.py @@ -0,0 +1,20 @@ +''' +Copyright (c) 2020, Pycom Limited. +This software is licensed under the GNU GPL version 3 or any +later version, with permitted additional terms. For more information +see the Pycom Licence v1.0 document supplied with this file, or +available at https://www.pycom.io/opensource/licensing +''' + + +class PeriodicalPin: + + TYPE_DIGITAL = 0 + TYPE_ANALOG = 1 + TYPE_VIRTUAL = 2 + + def __init__(self, persistent, pin_number, message_type, message, pin_type): + self.pin_number = pin_number + self.message_type = message_type + self.message = message + self.pin_type = pin_type diff --git a/esp32/frozen/Pybytes/_pybytes.py b/esp32/frozen/Pybytes/_pybytes.py index 607e3a6d70..4251baa2c6 100644 --- a/esp32/frozen/Pybytes/_pybytes.py +++ b/esp32/frozen/Pybytes/_pybytes.py @@ -1,40 +1,40 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or available at https://www.pycom.io/opensource/licensing ''' -import os, json, binascii -import time, pycom +import os +import json +import time +import pycom +import sys from network import WLAN -from machine import Timer +from binascii import hexlify, a2b_base64 +from machine import Timer, deepsleep, pin_sleep_wakeup, unique_id + +try: + from periodical_pin import PeriodicalPin +except: + from _periodical_pin import PeriodicalPin try: from pybytes_debug import print_debug except: from _pybytes_debug import print_debug - -class __PERIODICAL_PIN: - TYPE_DIGITAL = 0 - TYPE_ANALOG = 1 - TYPE_VIRTUAL = 2 - - def __init__( - self, persistent, pin_number, message_type, message, pin_type - ): - self.pin_number = pin_number - self.message_type = message_type - self.message = message - self.pin_type = pin_type +try: + from pybytes_config_reader import PybytesConfigReader +except: + from _pybytes_config_reader import PybytesConfigReader class Pybytes: - WAKEUP_ALL_LOW = const(0) - WAKEUP_ANY_HIGH = const(1) + WAKEUP_ALL_LOW = const(0) # noqa: F821 + WAKEUP_ANY_HIGH = const(1) # noqa: F821 def __init__(self, config, activation=False, autoconnect=False): self.__frozen = globals().get('__name__') == '_pybytes' @@ -44,18 +44,15 @@ def __init__(self, config, activation=False, autoconnect=False): self.__pybytes_connection = None self.__smart_config = False self.__conf = {} + self.__pymesh = None if not self.__activation: self.__conf = config + self.__conf_reader = PybytesConfigReader(config) pycom.wifi_on_boot(False, True) self.__check_dump_ca() - try: - from pybytes_connection import PybytesConnection - except: - from _pybytes_connection import PybytesConnection - self.__pybytes_connection = PybytesConnection(self.__conf, self.__recv_message) - + self.__create_pybytes_connection(self.__conf) self.start(autoconnect) if autoconnect: self.print_cfg_msg() @@ -63,10 +60,18 @@ def __init__(self, config, activation=False, autoconnect=False): if (hasattr(pycom, 'smart_config_on_boot') and pycom.smart_config_on_boot()): self.smart_config(True) + def __create_pybytes_connection(self, conf): + try: + from pybytes_connection import PybytesConnection + except: + from _pybytes_connection import PybytesConnection + + self.__pybytes_connection = PybytesConnection(conf, self.__recv_message) + def __check_config(self): try: print_debug(99, self.__conf) - return (len(self.__conf.get('username','')) > 4 and len(self.__conf.get('device_id', '')) >= 36 and len(self.__conf.get('server', '')) > 4) + return (len(self.__conf.get('username', '')) > 4 and len(self.__conf.get('device_id', '')) >= 36 and len(self.__conf.get('server', '')) > 4) except Exception as e: print_debug(4, 'Exception in __check_config!\n{}'.format(e)) return False @@ -83,25 +88,31 @@ def __check_dump_ca(self): print_debug(4, ' ssl_params={} '.format(ssl_params)) if self.__conf.get('dump_ca', False): try: - stat = os.stat(ssl_params.get('ca_certs')) # noqa + os.stat(ssl_params.get('ca_certs')) except: self.dump_ca(ssl_params.get('ca_certs')) def connect_wifi(self, reconnect=True, check_interval=0.5): self.__check_init() - return self.__pybytes_connection.connect_wifi(reconnect, check_interval) + if self.__pybytes_connection.connect_wifi(reconnect, check_interval): + self.__pybytes_connection.communication_protocol('wifi') + return True + return False - def connect_lte(self, reconnect=True, check_interval=0.5): + def connect_lte(self): self.__check_init() - return self.__pybytes_connection.connect_lte(reconnect, check_interval) + if self.__pybytes_connection.connect_lte(): + self.__pybytes_connection.communication_protocol('lte') + return True + return False def connect_lora_abp(self, timeout, nanogateway=False): self.__check_init() return self.__pybytes_connection.connect_lora_abp(timeout, nanogateway) - def connect_lora_otta(self, timeout=120, nanogateway=False): + def connect_lora_otaa(self, timeout=120, nanogateway=False): self.__check_init() - return self.__pybytes_connection.connect_lora_otta(timeout, nanogateway) + return self.__pybytes_connection.connect_lora_otaa(timeout, nanogateway) def connect_sigfox(self): self.__check_init() @@ -139,27 +150,33 @@ def send_analog_pin_value(self, persistent, pin): self.__check_init() self.__pybytes_connection.__pybytes_protocol.send_pybytes_analog_value(pin) - def send_signal(self, pin, value): + def send_node_signal(self, signal_number, value, token): self.__check_init() - self.__pybytes_connection.__pybytes_protocol.send_pybytes_custom_method_values(pin, [value]) + topic = 'br/{}'.format(token) + self.__pybytes_connection.__pybytes_protocol.send_pybytes_custom_method_values(signal_number, [value], topic) - def send_virtual_pin_value(self, persistent, pin, value): + def send_signal(self, signal_number, value): self.__check_init() - print("This function is deprecated and will be removed in the future. Use send_signal(signalNumber, value)") - self.send_signal(pin, value) + if self.__pymesh: + self.__pymesh.unpack_pymesh_message(signal_number, value) + else: + self.__pybytes_connection.__pybytes_protocol.send_pybytes_custom_method_values(signal_number, [value]) def __periodical_pin_callback(self, periodical_pin): - self.__check_init() - if (periodical_pin.pin_type == __PERIODICAL_PIN.TYPE_DIGITAL): - self.send_digital_pin_value(periodical_pin.persistent, periodical_pin.pin_number, None) - elif (periodical_pin.pin_type == __PERIODICAL_PIN.TYPE_ANALOG): - self.send_analog_pin_value(periodical_pin.persistent, periodical_pin.pin_number) + self.__check_init() + if (periodical_pin.pin_type == PeriodicalPin.TYPE_DIGITAL): + self.send_digital_pin_value( + periodical_pin.persistent, periodical_pin.pin_number, None + ) + elif (periodical_pin.pin_type == PeriodicalPin.TYPE_ANALOG): + self.send_analog_pin_value( + periodical_pin.persistent, periodical_pin.pin_number + ) def register_periodical_digital_pin_publish(self, persistent, pin_number, pull_mode, period): self.__check_init() self.send_digital_pin_value(pin_number, pull_mode) - periodical_pin = __PERIODICAL_PIN(pin_number, None, None, - __PERIODICAL_PIN.TYPE_DIGITAL) + periodical_pin = PeriodicalPin(pin_number, None, None, PeriodicalPin.TYPE_DIGITAL) Timer.Alarm( self.__periodical_pin_callback, period, arg=periodical_pin, periodic=True @@ -168,8 +185,8 @@ def register_periodical_digital_pin_publish(self, persistent, pin_number, pull_m def register_periodical_analog_pin_publish(self, pin_number, period): self.__check_init() self.send_analog_pin_value(pin_number) - periodical_pin = __PERIODICAL_PIN( - pin_number, None, None, __PERIODICAL_PIN.TYPE_ANALOG + periodical_pin = PeriodicalPin( + pin_number, None, None, PeriodicalPin.TYPE_ANALOG ) Timer.Alarm( self.__periodical_pin_callback, period, arg=periodical_pin, @@ -210,25 +227,20 @@ def isconnected(self): except: return False - def connect(self): try: lora_joining_timeout = 120 # seconds to wait for LoRa joining if self.__config_updated: if self.__check_config(): - try: - from pybytes_connection import PybytesConnection - except: - from _pybytes_connection import PybytesConnection - self.__pybytes_connection = PybytesConnection(self.__conf, self.__recv_message) + self.__create_pybytes_connection(self.__conf) self.__config_updated = False self.__check_init() if not self.__conf.get('network_preferences'): - print("network_preferences are empty, set it up in /flash/pybytes_config.json first") # noqa + print("network_preferences are empty, set it up in /flash/pybytes_config.json first") for net in self.__conf['network_preferences']: - print_debug(3,'Attempting to connect with network {}'.format(net)) + print_debug(3, 'Attempting to connect with network {}'.format(net)) if net == 'lte' or net == 'nbiot': if self.connect_lte(): break @@ -239,25 +251,35 @@ def connect(self): if self.connect_lora_abp(lora_joining_timeout): break elif net == 'lora_otaa': - if self.connect_lora_otta(lora_joining_timeout): + if self.connect_lora_otaa(lora_joining_timeout): break elif net == 'sigfox': if self.connect_sigfox(): break - import time time.sleep(.1) if self.is_connected(): if self.__frozen: - print('Pybytes connected successfully (using the built-in pybytes library)') # noqa + print('Pybytes connected successfully (using the built-in pybytes library)') else: - print('Pybytes connected successfully (using a local pybytes library)') # noqa + print('Pybytes connected successfully (using a local pybytes library)') # SEND DEVICE'S INFORMATION - self.send_info_message() + if self.__conf_reader.send_info(): + self.send_info_message() # ENABLE TERMINAL - self.enable_terminal() + if self.__conf_reader.enable_terminal(): + self.enable_terminal() + + # CHECK PYMESH FIRMWARE VERSION + if hasattr(os.uname(), 'pymesh'): + try: + from pybytes_pymesh_config import PybytesPymeshConfig + except: + from _pybytes_pymesh_config import PybytesPymeshConfig + self.__pymesh = PybytesPymeshConfig(self) + self.__pymesh.pymesh_init() else: print('ERROR! Could not connect to Pybytes!') @@ -266,7 +288,6 @@ def connect(self): def write_config(self, file='/flash/pybytes_config.json', silent=False): try: - import json f = open(file, 'w') f.write(json.dumps(self.__conf)) f.close() @@ -278,7 +299,6 @@ def write_config(self, file='/flash/pybytes_config.json', silent=False): def print_cfg_msg(self): if self.__conf.get('cfg_msg') is not None: - import time time.sleep(.1) print(self.__conf['cfg_msg']) time.sleep(.1) @@ -303,6 +323,7 @@ def set_config( ): if key is None and value is not None: self.__conf = value + self.__conf_reader = PybytesConfigReader(value) elif key is not None: self.__conf[key] = value else: @@ -315,30 +336,41 @@ def set_config( def update_config(self, key, value=None, permanent=True, silent=False, reconnect=False): try: - self.__conf[key].update(value) + if isinstance(self.__conf[key], dict): + self.__conf[key].update(value) + elif type(self.__conf[key]) is list: + # set new list + self.__conf[key] = [] + values = list(value.split(",")) + # removes leading whitespaces on array itens + values = [item.strip() for item in values] + self.__conf[key] = values + else: + self.__conf[key] = value self.__config_updated = True - if permanent: self.write_config(silent=silent) + if permanent: + self.write_config(silent=silent) if reconnect: self.reconnect() except Exception as ex: print('Error updating configuration!') - print('{}: {}'.format(ex.__name__, ex)) - + sys.print_exception(ex) def read_config(self, file='/flash/pybytes_config.json', reconnect=False): try: - import json f = open(file, 'r') jfile = f.read() f.close() try: - self.__conf = json.loads(jfile.strip()) + config_from_file = json.loads(jfile.strip()) + self.__conf = config_from_file + self.__conf_reader = PybytesConfigReader(config_from_file) self.__config_updated = True print("Pybytes configuration read from {}".format(file)) if reconnect: self.reconnect() except Exception as ex: - print("JSON error in configuration file {}!\n Exception: {}".format(file, ex)) # noqa + print("JSON error in configuration file {}!\n Exception: {}".format(file, ex)) except Exception as ex: print("Cannot open file {}\nException: {}".format(file, ex)) @@ -346,7 +378,6 @@ def reconnect(self): self.__check_init() try: self.disconnect() - import time time.sleep(1) self.connect() except Exception as ex: @@ -355,7 +386,6 @@ def reconnect(self): def export_config(self, file='/flash/pybytes_config.json'): self.__check_init() try: - import json f = open(file, 'w') f.write(json.dumps(self.__conf)) f.close() @@ -363,7 +393,7 @@ def export_config(self, file='/flash/pybytes_config.json'): except Exception as e: print("Error writing to file {}\nException: {}".format(file, e)) - def enable_ssl(self, ca_file='/flash/cert/pycom-ca.pem', dump_ca = True): + def enable_ssl(self, ca_file='/flash/cert/pycom-ca.pem', dump_ca=True): self.__check_init() self.set_config('dump_ca', dump_ca, permanent=False) if ca_file is not None: @@ -378,7 +408,7 @@ def enable_ssl(self, ca_file='/flash/cert/pycom-ca.pem', dump_ca = True): def enable_lte(self, carrier=None, cid=None, band=None, apn=None, type=None, reset=None, fallback=False): nwpref = None self.__check_init() - self.set_config('lte', {"carrier": carrier, "cid": cid, "band": band, "apn": apn, "type": type, "reset": reset }, permanent=False) + self.set_config('lte', {"carrier": carrier, "cid": cid, "band": band, "apn": apn, "type": type, "reset": reset}, permanent=False) if fallback: nwpref = self.__conf.get('network_preferences', []) nwpref.extend(['lte']) @@ -391,20 +421,20 @@ def enable_lte(self, carrier=None, cid=None, band=None, apn=None, type=None, res def deepsleep(self, ms, pins=None, mode=None, enable_pull=None): self.__check_init() - import machine if pins is not None: if mode is None or type(mode) != int: raise ValueError('You must specify a mode as integer!') - machine.pin_sleep_wakeup(pins, mode, enable_pull) + pin_sleep_wakeup(pins, mode, enable_pull) self.disconnect() - machine.deepsleep(ms) + deepsleep(ms) def dump_ca(self, ca_file='/flash/cert/pycom-ca.pem'): try: - try: - from _pybytes_ca import PYBYTES_CA - except: - from pybytes_ca import PYBYTES_CA + from _pybytes_ca import PYBYTES_CA + except: + from pybytes_ca import PYBYTES_CA + + try: f = open(ca_file, 'w') f.write(PYBYTES_CA) f.close() @@ -412,35 +442,26 @@ def dump_ca(self, ca_file='/flash/cert/pycom-ca.pem'): except Exception as e: print("Error creating {}\nException: {}".format(file, e)) - def start(self, autoconnect=True): if self.__conf is not None: self.__check_dump_ca() self.__config_updated = True - # START code from the old boot.py - import machine - import micropython - from binascii import hexlify - - wmac = hexlify(machine.unique_id()).decode('ascii') - print("WMAC: %s" % wmac.upper()) - try: + print("WMAC: {}".format(hexlify(unique_id()).decode('ascii').upper())) + if hasattr(os.uname(), 'pybytes'): print("Firmware: %s\nPybytes: %s" % (os.uname().release, os.uname().pybytes)) - except: + else: print("Firmware: %s" % os.uname().release) if autoconnect: self.connect() - - def activate(self, activation_string): self.__smart_config = False if self.__pybytes_connection is not None: print('Disconnecting current connection!') self.__pybytes_connection.disconnect(keep_wifi=True, force=True) try: - jstring = json.loads(binascii.a2b_base64(activation_string)) + jstring = json.loads(a2b_base64(activation_string)) except Exception as ex: print('Error decoding activation string!') print(ex) @@ -449,14 +470,17 @@ def activate(self, activation_string): except: from _pybytes_config import PybytesConfig try: - self.__conf = PybytesConfig().cli_config(activation_info=jstring) + self.__create_pybytes_connection(None) + conf_from_pybytes_conf = PybytesConfig().cli_config(activation_info=jstring, pybytes_connection=self.__pybytes_connection) + self.__conf = conf_from_pybytes_conf + self.__conf_reader = PybytesConfigReader(conf_from_pybytes_conf) if self.__conf is not None: self.start() else: print('Activation failed!') except Exception as ex: print('Activation failed! Please try again...') - print_debug(1, ex) + sys.print_exception(ex) if hasattr(pycom, 'smart_config_on_boot'): def smart_config(self, status=None, reset_ap=False): @@ -492,17 +516,20 @@ def __smart_config_callback(self, wl): from _pybytes_config import PybytesConfig print_debug(99, 'smartConfig done... activating') try: - self.__conf = PybytesConfig().smart_config() + conf_smart = PybytesConfig().smart_config() + self.__conf = conf_smart + self.__conf_reader = PybytesConfigReader(conf_smart) self.__smart_config = False self.start() except Exception as ex: + print_debug(99, ex) print('Smart Config failed... restarting!') self.__smart_config = True self.__smart_config_setup() def __smart_config_setup(self): wl = WLAN(mode=WLAN.STA) - wl.callback(trigger= WLAN.SMART_CONF_DONE | WLAN.SMART_CONF_TIMEOUT, handler=self.__smart_config_callback) + wl.callback(trigger=WLAN.SMART_CONF_DONE | WLAN.SMART_CONF_TIMEOUT, handler=self.__smart_config_callback) if pycom.wifi_ssid_sta() is not None and len(pycom.wifi_ssid_sta()) > 0: print('Trying previous AP details for 60 seconds...') pycom.wifi_on_boot(True, True) @@ -517,7 +544,9 @@ def __smart_config_setup(self): from pybytes_config import PybytesConfig except: from _pybytes_config import PybytesConfig - self.__conf = PybytesConfig().smart_config() + conf_smart = PybytesConfig().smart_config() + self.__conf = conf_smart + self.__conf_reader = PybytesConfigReader(conf_smart) self.__smart_config = False self.start() if self.__smart_config: diff --git a/esp32/frozen/Pybytes/_pybytes_ca.py b/esp32/frozen/Pybytes/_pybytes_ca.py index 09d96a6ed0..292d045718 100644 --- a/esp32/frozen/Pybytes/_pybytes_ca.py +++ b/esp32/frozen/Pybytes/_pybytes_ca.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/frozen/Pybytes/_pybytes_config.py b/esp32/frozen/Pybytes/_pybytes_config.py index 233c6e72c3..3b980a02a9 100644 --- a/esp32/frozen/Pybytes/_pybytes_config.py +++ b/esp32/frozen/Pybytes/_pybytes_config.py @@ -1,22 +1,28 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or available at https://www.pycom.io/opensource/licensing ''' -import pycom, time, os, json, binascii, machine -try: - from pybytes_debug import print_debug -except: - from _pybytes_debug import print_debug +import pycom +import time +import os +import json +import binascii +import machine try: from pybytes_constants import constants except: from _pybytes_constants import constants +try: + from pybytes_debug import print_debug +except: + from _pybytes_debug import print_debug + class PybytesConfig: @@ -78,7 +84,6 @@ def __check_cb_config(self, config): print_debug(4, 'Exception in __check_cb_config!\n{}'.format(e)) return False - def __read_activation(self): try: import urequest @@ -88,14 +93,19 @@ def __read_activation(self): from uhashlib import sha512 print('Wifi connection established... activating device!') self.__pybytes_activation = None - data = { "deviceType": os.uname().sysname.lower(), "wirelessMac": binascii.hexlify(machine.unique_id()).upper() } + data = {"deviceType": os.uname().sysname.lower(), "wirelessMac": binascii.hexlify(machine.unique_id()).upper()} try: - data.update({"activation_hash" : binascii.b2a_base64(sha512(data.get("wirelessMac") + '-' + '{}'.format(pycom.wifi_ssid_sta()) + '-' + '{}'.format(pycom.wifi_pwd_sta())).digest()).decode('UTF-8').strip()}) + data.update({"activation_hash": binascii.b2a_base64(sha512(data.get("wirelessMac") + '-' + '{}'.format(pycom.wifi_ssid_sta()) + '-' + '{}'.format( + pycom.wifi_pwd_sta())).digest()).decode('UTF-8').strip()} + ) except: pass time.sleep(1) try: - self.__pybytes_activation = urequest.post('https://api.{}/esp-touch/register-device'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'}) + self.__pybytes_activation = urequest.post( + 'https://api.{}/esp-touch/register-device'.format(constants.__DEFAULT_DOMAIN), + json=data, headers={'content-type': 'application/json'} + ) return True except Exception as ex: if self.__pybytes_activation is not None: @@ -110,13 +120,13 @@ def __read_cli_activation(self, activation_token): except: import _urequest as urequest - from uhashlib import sha512 - print('Wifi connection established... activating device!') self.__pybytes_cli_activation = None - data = { "activationToken": activation_token['a'], "deviceMacAddress": binascii.hexlify(machine.unique_id()).upper()} + data = {"activationToken": activation_token['a'], "deviceMacAddress": binascii.hexlify(machine.unique_id()).upper()} time.sleep(1) try: - self.__pybytes_cli_activation = urequest.post('https://api.{}/v2/quick-device-activation'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'}) + self.__pybytes_cli_activation = urequest.post( + 'https://api.{}/v2/quick-device-activation'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'} + ) except Exception as ex: if self.__pybytes_cli_activation is not None: self.__pybytes_cli_activation.close() @@ -130,14 +140,20 @@ def __process_sigfox_registration(self, activation_token): import _urequest as urequest if hasattr(pycom, 'sigfox_info'): - if pycom.sigfox_info()[0] is None or pycom.sigfox_info()[1] is None or pycom.sigfox_info()[2] is None or pycom.sigfox_info()[3] is None: + if not pycom.sigfox_info(): try: jsigfox = None from network import LoRa - data = { "activationToken": activation_token['a'], "wmac": binascii.hexlify(machine.unique_id()).upper(), "smac": binascii.hexlify(LoRa(region=LoRa.EU868).mac())} - print_debug(99,'sigfox_registration: {}'.format(data)) + data = { + "activationToken": activation_token['a'], + "wmac": binascii.hexlify(machine.unique_id()).upper(), + "smac": binascii.hexlify(LoRa(region=LoRa.EU868).mac()) + } + print_debug(99, 'sigfox_registration: {}'.format(data)) try: - self.__pybytes_sigfox_registration = urequest.post('https://api.{}/v2/register-sigfox'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'}) + self.__pybytes_sigfox_registration = urequest.post( + 'https://api.{}/v2/register-sigfox'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'} + ) jsigfox = self.__pybytes_sigfox_registration.json() except: jsigfox = None @@ -145,7 +161,10 @@ def __process_sigfox_registration(self, activation_token): while jsigfox is None and time.time() - start_time < 300: time.sleep(15) try: - self.__pybytes_sigfox_registration = urequest.post('https://api.{}/v2/register-sigfox'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'}) + self.__pybytes_sigfox_registration = urequest.post( + 'https://api.{}/v2/register-sigfox'.format(constants.__DEFAULT_DOMAIN), json=data, headers={'content-type': 'application/json'} + ) + print_debug(2, '/v2/register-sigfox returned response: {}'.format(self.__pybytes_sigfox_registration.text)) jsigfox = self.__pybytes_sigfox_registration.json() except: jsigfox = None @@ -155,7 +174,13 @@ def __process_sigfox_registration(self, activation_token): except: pass print_debug(99, 'Sigfox regisgtration response:\n{}'.format(jsigfox)) - return pycom.sigfox_info(id=jsigfox.get('sigfoxId'), pac=jsigfox.get('sigfoxPac'), public_key=jsigfox.get('sigfoxPubKey'), private_key=jsigfox.get('sigfoxPrivKey'), force=True) + return pycom.sigfox_info( + id=jsigfox.get('sigfoxId'), + pac=jsigfox.get('sigfoxPac'), + public_key=jsigfox.get('sigfoxPubKey'), + private_key=jsigfox.get('sigfoxPrivKey'), + force=True + ) else: try: self.__pybytes_sigfox_registration.close() @@ -171,7 +196,9 @@ def __process_sigfox_registration(self, activation_token): def __process_cli_activation(self, filename, activation_token): try: if not self.__pybytes_cli_activation.status_code == 200: - print_debug(3, 'Activation request returned {}.'.format(self.__pybytes_cli_activation.status_code)) + print_debug(3, 'Activation request returned {} with text: "{}".'.format( + self.__pybytes_cli_activation.status_code, self.__pybytes_cli_activation.text) + ) else: print_debug(99, 'Activation response:\n{}'.format(self.__pybytes_cli_activation.json())) if self.__process_sigfox_registration(activation_token): @@ -194,7 +221,6 @@ def __process_cli_activation(self, filename, activation_token): print('{}'.format(e)) return None - def __process_activation(self, filename): try: if not self.__pybytes_activation.status_code == 200: @@ -218,58 +244,57 @@ def __read_cb_config(self): config_block = {} try: config_block = { - 'userId' : pycom.pybytes_userId(), - 'device_token' : pycom.pybytes_device_token(), - 'mqttServiceAddress' : pycom.pybytes_mqttServiceAddress(), - 'network_preferences' : pycom.pybytes_network_preferences().split(), - 'wifi_ssid' : pycom.wifi_ssid_sta() if hasattr(pycom, 'wifi_ssid_sta') else pycom.wifi_ssid(), + 'userId': pycom.pybytes_userId(), + 'device_token': pycom.pybytes_device_token(), + 'mqttServiceAddress': pycom.pybytes_mqttServiceAddress(), + 'network_preferences': pycom.pybytes_network_preferences().split(), + 'wifi_ssid': pycom.wifi_ssid_sta() if hasattr(pycom, 'wifi_ssid_sta') else pycom.wifi_ssid(), 'wifi_pwd': pycom.wifi_pwd_sta() if hasattr(pycom, 'wifi_pwd_sta') else pycom.wifi_pwd(), - 'extra_preferences' : pycom.pybytes_extra_preferences(), - 'carrier' : pycom.pybytes_lte_config()[0], - 'apn' : pycom.pybytes_lte_config()[1], - 'cid' : pycom.pybytes_lte_config()[2], - 'band' : pycom.pybytes_lte_config()[3], - 'protocol' : pycom.pybytes_lte_config()[4], - 'reset' : pycom.pybytes_lte_config()[5] + 'extra_preferences': pycom.pybytes_extra_preferences(), + 'carrier': pycom.pybytes_lte_config()[0], + 'apn': pycom.pybytes_lte_config()[1], + 'cid': pycom.pybytes_lte_config()[2], + 'band': pycom.pybytes_lte_config()[3], + 'protocol': pycom.pybytes_lte_config()[4], + 'reset': pycom.pybytes_lte_config()[5] } except: pass return config_block def __generate_cli_config(self): - cli_config = {} + pybytes_config = self.__pybytes_cli_activation.json() + cli_config = { + 'userId': pybytes_config.get('userId'), + 'device_token': pybytes_config.get('deviceToken'), + 'mqttServiceAddress': pybytes_config.get('mqttServiceAddress'), + 'network_preferences': pybytes_config.get('network_preferences'), + 'wifi_ssid': '', + 'wifi_pwd': '', + } try: - cli_config = { - 'userId' : self.__pybytes_cli_activation.json().get('userId'), - 'device_token' : self.__pybytes_cli_activation.json().get('deviceToken'), - 'mqttServiceAddress' : self.__pybytes_cli_activation.json().get('mqttServiceAddress'), - 'network_preferences' : self.__pybytes_cli_activation.json().get('network_preferences'), - 'wifi_ssid' : self.__pybytes_cli_activation.json().get('wifi').get('ssid'), - 'wifi_pwd': self.__pybytes_cli_activation.json().get('wifi').get('password') - } + cli_config.update({'wifi_ssid': pybytes_config.get('wifi').get('ssid')}) except: - pass - - cli_lte_config = {} + print_debug(3, '__generate_cli_config: config does not contain wifi_ssid') try: - cli_lte_config = { - 'carrier' : self.__pybytes_cli_activation.json().get('lte').get('carrier').lower(), - 'apn' : self.__pybytes_cli_activation.json().get('lte').get('apn'), - 'cid' : self.__pybytes_cli_activation.json().get('lte').get('cid'), - 'band' : self.__pybytes_cli_activation.json().get('lte').get('band'), - 'reset' : self.__pybytes_cli_activation.json().get('lte').get('reset'), - 'protocol' : self.__pybytes_cli_activation.json().get('lte').get('protocol') - } + cli_config.update({'wifi_pwd': pybytes_config.get('wifi').get('password')}) except: - pass + print_debug(3, '__generate_cli_config: config does not contain wifi_password') try: - cli_config.update({'extra_preferences' :self.__pybytes_cli_activation.json().get('extra_preferences', '')}) + cli_config.update({ + 'carrier': pybytes_config.get('lte').get('carrier').lower(), + 'apn': pybytes_config.get('lte').get('apn'), + 'cid': pybytes_config.get('lte').get('cid'), + 'band': pybytes_config.get('lte').get('band'), + 'reset': pybytes_config.get('lte').get('reset'), + 'protocol': pybytes_config.get('lte').get('protocol') + }) except: - pass + print_debug(3, '__generate_cli_config: config does not contain LTE configuration') try: - cli_config.update(cli_lte_config) + cli_config.update({'extra_preferences': pybytes_config.get('extra_preferences', '')}) except: - pass + print_debug(3, '__generate_cli_config: config does not contain extra_preferences') return cli_config def __process_config(self, filename, configuration): @@ -316,44 +341,46 @@ def __process_config(self, filename, configuration): elif extra_preference == "ca_certs": index = extra_preferences.index(extra_preference) if len(extra_preferences[index + 1]) > 0: - ssl_params = { "ssl_params": {"ca_certs": extra_preferences[index + 1] }} + ssl_params = {"ssl_params": {"ca_certs": extra_preferences[index + 1]}} else: - ssl_params = { "ssl_params": {"ca_certs": '/flash/cert/pycom-ca.pem' }} + ssl_params = {"ssl_params": {"ca_certs": '/flash/cert/pycom-ca.pem'}} elif extra_preference == "dump_ca": dump_ca = True elif extra_preference == "sigfox": index = extra_preferences.index(extra_preference) if len(extra_preferences[index + 1]) > 0 and extra_preferences[index + 1].isdigit(): rcz = int(extra_preferences[index + 1]) - sigfox_config = { 'sigfox' : - { "RCZ" : rcz } - } + sigfox_config = { + 'sigfox': { + "RCZ": rcz + } + } except Exception as e: print_debug(2, 'Exception __process_config[extra]\n{}'.format(e)) try: - lte_config = { 'lte': - { 'carrier': configuration.get('carrier'), - 'cid': configuration.get('cid'), - 'band': configuration.get('band'), - 'apn': configuration.get('apn'), - 'reset': configuration.get('reset', 'false') == 'true', - 'type': configuration.get('protocol') - } - } + lte_config = { + 'lte': { + 'carrier': configuration.get('carrier'), + 'cid': configuration.get('cid'), + 'band': configuration.get('band'), + 'apn': configuration.get('apn'), + 'reset': configuration.get('reset', 'false') == 'true', + 'type': configuration.get('protocol') + } + } except Exception as e: print_debug(2, 'Exception __process_config[lte]\n{}'.format(e)) try: - #if True: self.__pybytes_config = { 'username': configuration['userId'], # Pybytes username 'device_id': configuration['device_token'], # device token 'server': configuration['mqttServiceAddress'], 'network_preferences': configuration['network_preferences'] \ if type(configuration['network_preferences']) is list \ - else configuration['network_preferences'].split(), # ordered list, first working network used + else configuration['network_preferences'].split(), # noqa # ordered list, first working network used 'wifi': { 'ssid': configuration['wifi_ssid'], 'password': configuration['wifi_pwd'] @@ -376,18 +403,18 @@ def __process_config(self, filename, configuration): if ssl_params is not None: self.__pybytes_config.update(ssl_params) print_debug(2, 'Checking and writing configuration in __process_config') - if (len(self.__pybytes_config['username']) > 4 and len(self.__pybytes_config['device_id']) >= 36 and len(self.__pybytes_config['server']) > 4) and self.__write_config(filename): + if (len(self.__pybytes_config['username']) > 4 and len(self.__pybytes_config['device_id']) >= 36 and len(self.__pybytes_config['server']) > 4) and self.__write_config(filename): # noqa self.__pybytes_config['cfg_msg'] = "Configuration successfully converted to pybytes_config.json" return True return False except Exception as e: - print_debug(2 , 'Exception __process_config[generic]\n{}'.format(e)) + print_debug(2, 'Exception __process_config[generic]\n{}'.format(e)) return False def __convert_legacy_config(self, filename): try: from config import config as pybytes_legacy_config - if pybytes_legacy_config.get('username') is None or pybytes_legacy_config.get('device_id') is None or pybytes_legacy_config.get('server') is None or pybytes_legacy_config.get('network_preferences') is None: + if pybytes_legacy_config.get('username') is None or pybytes_legacy_config.get('device_id') is None or pybytes_legacy_config.get('server') is None or pybytes_legacy_config.get('network_preferences') is None: # noqa print("This config.py does not look like a Pybytes configuration... skipping...") del pybytes_legacy_config raise ValueError() @@ -410,19 +437,31 @@ def smart_config(self, filename='/flash/pybytes_config.json'): time.sleep(10) return self.__pybytes_config - def cli_config(self, filename='/flash/pybytes_config.json', activation_info=None, timeout = 60): + def cli_config(self, pybytes_connection, filename='/flash/pybytes_config.json', activation_info=None): print_debug(99, activation_info) + if 's' in activation_info: + print_debug(3, 'performing Wi-Fi activation') + self.__cli_activation_over_wifi(activation_info) + print('Wifi connection established... activating device!') + if 'apn' in activation_info: + print_debug(3, 'performing LTE activation') + pybytes_connection.connect_lte(activation_info=activation_info, start_mqtt=False) + + self.__read_cli_activation(activation_info) + return self.__process_cli_activation(filename, activation_info) + + def __cli_activation_over_wifi(self, activation_info): print('Please wait while we try to connect to {}'.format(activation_info.get('s'))) from network import WLAN wlan = WLAN(mode=WLAN.STA) attempt = 0 known_nets = [((activation_info['s'], activation_info['p']))] # noqa - print_debug(3,'WLAN connected? {}'.format(wlan.isconnected())) + print_debug(3, 'WLAN connected? {}'.format(wlan.isconnected())) while not wlan.isconnected() and attempt < 10: attempt += 1 print_debug(3, "Wifi connection attempt: {}".format(attempt)) - print_debug(3,'WLAN connected? {}'.format(wlan.isconnected())) + print_debug(3, 'WLAN connected? {}'.format(wlan.isconnected())) available_nets = None while available_nets is None: try: @@ -440,12 +479,15 @@ def cli_config(self, filename='/flash/pybytes_config.json', activation_info=None net_to_use = net_to_use[0] pwd = dict(known_nets)[net_to_use] sec = [e.sec for e in available_nets if e.ssid == net_to_use][0] # noqa - print_debug(2, "Connecting with {} and {}".format(net_to_use, pwd)) - wlan.connect(net_to_use, (sec, pwd), timeout=10000) + print_debug(99, "Connecting with {} and {}".format(net_to_use, pwd)) + if sec == 0: + wlan.connect(net_to_use, timeout=10000) + else: + wlan.connect(net_to_use, (sec, pwd), timeout=10000) start_time = time.time() while not wlan.isconnected(): - if time.time() - start_time > timeout: - raise TimeoutError('Timeout trying to connect via WiFi') + if time.time() - start_time > 300: + raise TimeoutError('Timeout trying to connect via WiFi') # noqa: F821 time.sleep(0.1) except Exception as e: if str(e) == "list index out of range" and attempt == 3: @@ -455,9 +497,6 @@ def cli_config(self, filename='/flash/pybytes_config.json', activation_info=None elif attempt == 3: print("Error connecting using WIFI: %s" % e) return None - self.__read_cli_activation(activation_info) - return self.__process_cli_activation(filename, activation_info) - def read_config(self, filename='/flash/pybytes_config.json'): try: @@ -478,9 +517,6 @@ def read_config(self, filename='/flash/pybytes_config.json'): except Exception as ex: self.__force_update = True -# if self.__force_update: -# self.__convert_legacy_config(filename) - if self.__force_update: if not self.__process_config(filename, self.__read_cb_config()): self.__pybytes_config['pybytes_autostart'] = False @@ -507,6 +543,6 @@ def read_config(self, filename='/flash/pybytes_config.json'): except: pass if self.__pybytes_config.get('pybytes_autostart', False): - self.__pybytes_config['pybytes_autostart'] = self.__check_config() + self.__pybytes_config['pybytes_autostart'] = self.__check_config() return self.__pybytes_config diff --git a/esp32/frozen/Pybytes/_pybytes_config_reader.py b/esp32/frozen/Pybytes/_pybytes_config_reader.py new file mode 100644 index 0000000000..bb13ab1842 --- /dev/null +++ b/esp32/frozen/Pybytes/_pybytes_config_reader.py @@ -0,0 +1,55 @@ +''' +Copyright (c) 2020, Pycom Limited. +This software is licensed under the GNU GPL version 3 or any +later version, with permitted additional terms. For more information +see the Pycom Licence v1.0 document supplied with this file, or +available at https://www.pycom.io/opensource/licensing +''' + + +class PybytesConfigReader: + + def __init__(self, config): + self.__pybytes_config = config + + def get_pybytes(self): + return self.__pybytes_config.get( + 'pybytes', {} + ) + + def send_info(self): + return self.get_pybytes().get( + 'send_info', True + ) + + def enable_terminal(self): + return self.get_pybytes().get( + 'enable_terminal', True + ) + + def get_communication_obj(self): + return self.get_pybytes().get( + 'communication', {} + ) + + def get_communication_type(self): + return self.get_communication_obj().get( + 'type', 'mqtt' + ).lower() + + def get_coap(self): + return self.get_communication_obj().get( + 'servers', {} + ).get( + 'coap', {} + ) + + def get_coap_host(self): + return self.get_coap().get( + 'host', None + ) + + def get_coap_port(self): + return self.get_coap().get( + 'port', None + ) diff --git a/esp32/frozen/Pybytes/_pybytes_connection.py b/esp32/frozen/Pybytes/_pybytes_connection.py index bc86eb6c59..6ddc2d68c4 100644 --- a/esp32/frozen/Pybytes/_pybytes_connection.py +++ b/esp32/frozen/Pybytes/_pybytes_connection.py @@ -1,15 +1,29 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or available at https://www.pycom.io/opensource/licensing ''' +import os +import sys +import _thread +import time +import socket +import struct +import binascii +import pycom +from machine import WDT + try: from mqtt import MQTTClient except: from _mqtt import MQTTClient +try: + from pybytes_config_reader import PybytesConfigReader +except: + from _pybytes_config_reader import PybytesConfigReader try: from pybytes_protocol import PybytesProtocol @@ -25,36 +39,32 @@ from pybytes_debug import print_debug except: from _pybytes_debug import print_debug - -import os -import _thread -import time -import socket -import struct -import binascii -import pycom -from machine import WDT +try: + from coap import COAPClient +except: + from _coap import COAPClient class PybytesConnection: def __init__(self, config, message_callback): - self.__conf = config - try: - self.__host = pycom.nvs_get('pybytes_server') - except: - self.__host = config.get('server') - self.__ssl = config.get('ssl', False) - self.__ssl_params = config.get('ssl_params', {}) - self.__user_name = config.get('username') - self.__device_id = config.get('device_id') - self.__mqtt_download_topic = "d" + self.__device_id - self.__mqtt_upload_topic = "u" + self.__device_id + if config is not None: + self.__conf = config + self.__conf_reader = PybytesConfigReader(config) + try: + self.__host = pycom.nvs_get('pybytes_server') + except: + self.__host = config.get('server') + self.__ssl = config.get('ssl', False) + self.__ssl_params = config.get('ssl_params', {}) + self.__user_name = config.get('username') + self.__device_id = config.get('device_id') + self.__mqtt_download_topic = "d" + self.__device_id + self.__mqtt_upload_topic = "u" + self.__device_id + self.__pybytes_protocol = PybytesProtocol( + config, message_callback, pybytes_connection=self + ) self.__connection = None -# self.__thread_stack_size = 8192 self.__connection_status = constants.__CONNECTION_STATUS_DISCONNECTED - self.__pybytes_protocol = PybytesProtocol( - config, message_callback, pybytes_connection=self - ) self.__lora_socket = None self.lora = None self.lora_lock = _thread.allocate_lock() @@ -130,11 +140,14 @@ def connect_wifi(self, reconnect=True, check_interval=0.5, timeout=120): pwd = dict(known_nets)[net_to_use] sec = [e.sec for e in available_nets if e.ssid == net_to_use][0] # noqa print_debug(99, "Connecting with {} and {}".format(net_to_use, pwd)) - self.wlan.connect(net_to_use, (sec, pwd), timeout=10000) + if sec == 0: + self.wlan.connect(net_to_use, timeout=self.__conf.get('wifi', {}).get('timeout', 10000)) + else: + self.wlan.connect(net_to_use, (sec, pwd), timeout=self.__conf.get('wifi', {}).get('timeout', 10000)) start_time = time.time() while not self.wlan.isconnected(): if time.time() - start_time > timeout: - raise TimeoutError('Timeout trying to connect via WiFi') + raise TimeoutError('Timeout trying to connect via WiFi') # noqa: F821 time.sleep(0.1) except Exception as e: if str(e) == "list index out of range" and attempt == 3: @@ -144,42 +157,23 @@ def connect_wifi(self, reconnect=True, check_interval=0.5, timeout=120): elif attempt == 3: print("Error connecting using WIFI: %s" % e) return False - self.__network_type = constants.__NETWORK_TYPE_WIFI print("WiFi connection established") - try: - self.__connection = MQTTClient( - self.__device_id, - self.__host, - self.__mqtt_download_topic, - self.__pybytes_protocol, - user=self.__user_name, - password=self.__device_id - ) - self.__connection.connect() - self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI # noqa - self.__pybytes_protocol.start_MQTT( - self, - constants.__NETWORK_TYPE_WIFI - ) - return True - except Exception as ex: - if '{}'.format(ex) == '4': - print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) # noqa - else: - print("MQTT ERROR! {}".format(ex)) - return False + return True except Exception as ex: print("Exception connect_wifi: {}".format(ex)) return False # Establish a connection through LTE before connecting to mqtt server - def connect_lte(self, reconnect=True, check_interval=0.5): - self.__initialise_watchdog() + def connect_lte(self, activation_info=False, start_mqtt=True): + if activation_info: + lte_cfg = activation_info + else: + lte_cfg = self.__conf.get('lte') + self.__initialise_watchdog() - lte_cfg = self.__conf.get('lte') if lte_cfg is not None: - if (os.uname()[0] not in ['FiPy', 'GPy']): + if (os.uname().sysname not in ['FiPy', 'GPy']): print("You need a device with FiPy or GPy firmware to connect via LTE") # noqa return False try: @@ -223,41 +217,22 @@ def connect_lte(self, reconnect=True, check_interval=0.5): print_debug(1, 'LTE is_connected()') while not self.lte.isconnected(): time.sleep(0.25) - print("LTE connection established") self.__network_type = constants.__NETWORK_TYPE_LTE - try: - self.__connection = MQTTClient( - self.__device_id, - self.__host, - self.__mqtt_download_topic, - self.__pybytes_protocol, - user=self.__user_name, - password=self.__device_id - ) - self.__connection.connect() - self.__connection_status = constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE # noqa - self.__pybytes_protocol.start_MQTT( - self, - constants.__NETWORK_TYPE_WIFI - ) - print("Connected to MQTT {}".format(self.__host)) - return True - except Exception as ex: - if '{}'.format(ex) == '4': - print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) # noqa - else: - print("MQTT ERROR! {}".format(ex)) - return False + print("LTE connection established") + if start_mqtt: + print("connect_lte with start_mqtt is now removed please call communication_protocol or start_mqtt directly") + return True except Exception as ex: print("Exception connect_lte: {}".format(ex)) - return False + sys.print_exception(ex) + return False else: print("Error... missing configuration!") return False # LORA def connect_lora_abp(self, lora_timeout, nanogateway): - print_debug(1,'Attempting to connect via LoRa') + print_debug(1, 'Attempting to connect via LoRa') if (self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED): # noqa print("Error connect_lora_abp: Connection already exists. Disconnect First") # noqa return False @@ -267,10 +242,11 @@ def connect_lora_abp(self, lora_timeout, nanogateway): print("This device does not support LoRa connections: %s" % ex) return False + lora_class = self.__conf.get('lora', {}).get('class', 0) if self.__conf.get('lora', {}).get('region') is not None: - self.lora = LoRa(mode=LoRa.LORAWAN, region=self.__conf.get('lora', {}).get('region')) + self.lora = LoRa(mode=LoRa.LORAWAN, region=self.__conf.get('lora').get('region'), device_class=lora_class) else: - self.lora = LoRa(mode=LoRa.LORAWAN) + self.lora = LoRa(mode=LoRa.LORAWAN, device_class=lora_class) self.lora.nvram_restore() try: @@ -313,10 +289,10 @@ def connect_lora_abp(self, lora_timeout, nanogateway): print_debug(3, 'Exception in LoRa connect: {}'.format(e)) return False - def connect_lora_otta(self, lora_timeout, nanogateway): - print_debug(1,'Attempting to connect via LoRa') + def connect_lora_otaa(self, lora_timeout, nanogateway): + print_debug(1, 'Attempting to connect via LoRa') if (self.__connection_status != constants.__CONNECTION_STATUS_DISCONNECTED): # noqa - print("Error connect_lora_otta: Connection already exists. Disconnect First") # noqa + print("Error connect_lora_otaa: Connection already exists. Disconnect First") # noqa return False try: from network import LoRa @@ -335,10 +311,11 @@ def connect_lora_otta(self, lora_timeout, nanogateway): timeout_ms = self.__conf.get('lora_timeout', lora_timeout) * 1000 + lora_class = self.__conf.get('lora', {}).get('class', 0) if self.__conf.get('lora', {}).get('region') is not None: - self.lora = LoRa(mode=LoRa.LORAWAN, region=self.__conf.get('lora', {}).get('region')) + self.lora = LoRa(mode=LoRa.LORAWAN, region=self.__conf.get('lora', {}).get('region'), device_class=lora_class) else: - self.lora = LoRa(mode=LoRa.LORAWAN) + self.lora = LoRa(mode=LoRa.LORAWAN, device_class=lora_class) self.lora.nvram_restore() dev_eui = binascii.unhexlify(dev_eui.replace(' ', '')) @@ -489,3 +466,61 @@ def is_connected(self): # Added for convention with other connectivity classes def isconnected(self): return not (self.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED) # noqa + + def communication_protocol(self, connection_type): + if self.__conf_reader.get_communication_type() == constants.__SIMPLE_COAP: + + if connection_type == 'wifi': + target_connection_type = constants.__CONNECTION_STATUS_CONNECTED_COAP_WIFI + elif connection_type == 'lte': + target_connection_type = constants.__CONNECTION_STATUS_CONNECTED_COAP_LTE + + return self.start_coap(target_connection_type) + + else: + + if connection_type == 'wifi': + target_connection_type = constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI + elif connection_type == 'lte': + target_connection_type = constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE + + return self.start_mqtt(target_connection_type) + + def start_coap(self, connection_type): + print_debug(1, 'CoAP Protocol') + self.__connection = COAPClient( + self.__conf_reader.get_coap_host(), + self.__conf_reader.get_coap_port(), + ) + self.__connection_status = connection_type + self.__pybytes_protocol.start_coap( + self, + self.__network_type + ) + return True + + def start_mqtt(self, connection_type): + print_debug(1, 'MQTT Protocol') + try: + self.__connection = MQTTClient( + self.__device_id, + self.__host, + self.__mqtt_download_topic, + self.__pybytes_protocol, + user=self.__user_name, + password=self.__device_id + ) + self.__connection.connect() + self.__connection_status = connection_type + self.__pybytes_protocol.start_MQTT( + self, + self.__network_type + ) + print("Connected to MQTT {}".format(self.__host)) + return True + except Exception as ex: + if '{}'.format(ex) == '4': + print('MQTT ERROR! Bad credentials when connecting to server: "{}"'.format(self.__host)) + else: + print("MQTT ERROR! {}".format(ex)) + return False diff --git a/esp32/frozen/Pybytes/_pybytes_constants.py b/esp32/frozen/Pybytes/_pybytes_constants.py index f7efbce88c..bd2117fef5 100644 --- a/esp32/frozen/Pybytes/_pybytes_constants.py +++ b/esp32/frozen/Pybytes/_pybytes_constants.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or @@ -58,6 +58,8 @@ class constants: __CONNECTION_STATUS_CONNECTED_MQTT_LTE = 2 __CONNECTION_STATUS_CONNECTED_LORA = 3 __CONNECTION_STATUS_CONNECTED_SIGFOX = 4 + __CONNECTION_STATUS_CONNECTED_COAP_WIFI = 5 + __CONNECTION_STATUS_CONNECTED_COAP_LTE = 6 __TYPE_PING = 0x00 __TYPE_INFO = 0x01 @@ -67,6 +69,7 @@ class constants: __TYPE_OTA = 0x05 __TYPE_FCOTA = 0x06 __TYPE_PONG = 0x07 + __TYPE_PYMESH = 0x0D __TYPE_PYBYTES = 0x0E __TYPE_RELEASE_INFO = 0x0B __TYPE_RELEASE_DEPLOY = 0x0A @@ -93,6 +96,7 @@ class constants: __FCOTA_COMMAND_FILE_UPDATE = 0x02 __FCOTA_PING = 0x03 __FCOTA_COMMAND_FILE_DELETE = 0x04 + __FCOTA_COMMAND_FILE_UPDATE_NO_RESET = 0x05 __DEVICE_TYPE_WIPY = 0x00 __DEVICE_TYPE_LOPY = 0x01 @@ -118,6 +122,8 @@ class constants: __WDT_MAX_TIMEOUT_MILLISECONDS = sys.maxsize + __SIMPLE_COAP = 'simple_coap' + try: __DEFAULT_DOMAIN = pycom.nvs_get('pybytes_domain', 'pybytes.pycom.io') except: diff --git a/esp32/frozen/Pybytes/_pybytes_debug.py b/esp32/frozen/Pybytes/_pybytes_debug.py index 7fa973ec10..a8be1ddbaf 100644 --- a/esp32/frozen/Pybytes/_pybytes_debug.py +++ b/esp32/frozen/Pybytes/_pybytes_debug.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/frozen/Pybytes/_pybytes_library.py b/esp32/frozen/Pybytes/_pybytes_library.py index 665c10440e..e3ac7898ff 100644 --- a/esp32/frozen/Pybytes/_pybytes_library.py +++ b/esp32/frozen/Pybytes/_pybytes_library.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or @@ -49,11 +49,11 @@ def pack_release_info_message(self, releaseId): print("This is pack_release_info_message") return self.__pack_message(constants.__TYPE_RELEASE_INFO, releaseId) - def pack_pybytes_message_variable(self, command, pin, parameters): + def pack_pybytes_message_variable(self, command, pin, parameters, message_type): print_debug(5, "This is pack_pybytes_message_variable({}, {}, {})".format(command, pin, parameters)) body = struct.pack(constants.__PYBYTES_INTERNAL_PROTOCOL_VARIABLE % len(parameters), command, pin, parameters) - return self.__pack_message(constants.__TYPE_PYBYTES, body) + return self.__pack_message(getattr(constants, message_type), body) def pack_ping_message(self): return self.__pack_message(constants.__TYPE_PING, None) @@ -150,12 +150,6 @@ def pack_scan_info_message(self, lora): body = bytearray() - # max_networks = 5 - # if (len(wifi_networks) < 5): - # max_networks = len(wifi_networks) - # - # for x in range(0, max_networks): - for x in range(0, len(wifi_networks)): wifi_pack = struct.pack(constants.__WIFI_NETWORK_FORMAT, wifi_networks[x][1], wifi_networks[x][3], wifi_networks[x][4]) diff --git a/esp32/frozen/Pybytes/_pybytes_main.py b/esp32/frozen/Pybytes/_pybytes_main.py new file mode 100644 index 0000000000..f89ab25054 --- /dev/null +++ b/esp32/frozen/Pybytes/_pybytes_main.py @@ -0,0 +1,99 @@ + +''' +Copyright (c) 2020, Pycom Limited. +This software is licensed under the GNU GPL version 3 or any +later version, with permitted additional terms. For more information +see the Pycom Licence v1.0 document supplied with this file, or +available at https://www.pycom.io/opensource/licensing + +This is the main.py file for Pybytes +This code and included libraries are intended for users wishing to fully +customise pybytes. It is the same code that is included in the Pybytes firmware +If you're planning to use the Pybytes firmware, please check out the +examples in the examples directory which are much easier to use. +If you make changes to any of the libraries in the lib directory, +you only need to upload the changed files if using the Pybytes firmware. +The other libraries will be loaded from the built-in code. +If you make changes above "Please put your USER code below this line" while +using a Pybytes enabled firmware, you need to disable auto-start. +You can disable auto-start by setting "pybytes_autostart": false in +pybytes_project.json or pybytes_config.json. +If using the Pybytes firmware, the configuration is already loaded and this +cannot be deactivated. However if you disable auto-start, you can modify the +configuration before connecting to Pybytes manually using pybytes.connect() +''' + +# Load configuration, migrate to pybytes_config.json if necessary +if 'pybytes_config' not in globals().keys(): + try: + from pybytes_config import PybytesConfig + except: + from _pybytes_config import PybytesConfig + try: + from pybytes import Pybytes + except: + from _pybytes import Pybytes + + pybytes_config = PybytesConfig().read_config() + +if (not pybytes_config.get('pybytes_autostart', True)) and pybytes_config.get('cfg_msg') is not None: + print(pybytes_config.get('cfg_msg')) + print("Not starting Pybytes as auto-start is disabled") + +else: + # Load Pybytes if it is not already loaded + if 'pybytes' not in globals().keys(): + pybytes = Pybytes(pybytes_config, pybytes_config.get('cfg_msg') is None, True) + + # Please put your USER code below this line + + # SEND SIGNAL + # You can currently send Strings, Int32, Float32 and Tuples to pybytes using this method. + # pybytes.send_signal(signalNumber, value) + + # SEND SENSOR DATA THROUGH SIGNALS + # # If you use a Pysense, some libraries are necessary to access its sensors + # # you can find them here: https://github.com/pycom/pycom-libraries + # + # # Include the libraries in the lib folder then import the ones you want to use here: + # from SI7006A20 import SI7006A20 + # si = SI7006A20() + # from LTR329ALS01 import LTR329ALS01 + # ltr = LTR329ALS01() + # + # # Import what is necessary to create a thread + # import _thread + # from time import sleep + # from machine import Pin + # + # # Define your thread's behaviour, here it's a loop sending sensors data every 10 seconds + # def send_env_data(): + # while (pybytes): + # pybytes.send_signal(1, si.humidity()) + # pybytes.send_signal(2, si.temperature()) + # pybytes.send_signal(3, ltr.light()); + # sleep(10) + # + # # Start your thread + # _thread.start_new_thread(send_env_data, ()) + + # SET THE BATTERY LEVEL + # pybytes.send_battery_level(23) + + # SEND DIGITAL VALUE + # pybytes.send_digital_pin_value(False, 12, Pin.PULL_UP) + + # SEND ANALOG VALUE + # pybytes.send_analog_pin_value(False, 13) + + # REGISTER PERIODICAL DIGIAL VALUE SEND + # pybytes.register_periodical_digital_pin_publish(False, PIN_NUMBER, Pin.PULL_UP, INTERVAL_SECONDS) + + # REGISTER PERIODICAL ANALOG VALUE SEND + # pybytes.register_periodical_analog_pin_publish(False, PIN_NUMBER, INTERVAL_SECONDS) + + # CUSTOM METHOD EXAMPLE + # def custom_print(params): + # print("Custom method called") + # return [255, 20] + # pybytes.add_custom_method(0, custom_print) diff --git a/esp32/frozen/Pybytes/_pybytes_protocol.py b/esp32/frozen/Pybytes/_pybytes_protocol.py index ba11c509e3..385d8c6f9c 100644 --- a/esp32/frozen/Pybytes/_pybytes_protocol.py +++ b/esp32/frozen/Pybytes/_pybytes_protocol.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or @@ -26,6 +26,16 @@ except: from _OTA import WiFiOTA +try: + from pybytes_pymesh_config import PybytesPymeshConfig +except: + from _pybytes_pymesh_config import PybytesPymeshConfig + +try: + from pybytes_config_reader import PybytesConfigReader +except: + from _pybytes_config_reader import PybytesConfigReader + try: from flash_control_OTA import FCOTA except: @@ -45,6 +55,8 @@ from machine import PWM from machine import Timer from machine import reset +from binascii import hexlify +from network import Coap import os import _thread @@ -57,6 +69,7 @@ class PybytesProtocol: def __init__(self, config, message_callback, pybytes_connection): self.__conf = config + self.__conf_reader = PybytesConfigReader(config) self.__thread_stack_size = 8192 self.__device_id = config['device_id'] self.__mqtt_download_topic = "d" + self.__device_id @@ -99,6 +112,11 @@ def start_Sigfox(self, pybytes_connection): constants.__NETWORK_TYPE_SIGFOX) self.__pybytes_connection = pybytes_connection + def start_coap(self, pybytes_connection, networkType): + print_debug(5, "This is PybytesProtocol.start_coap()") + self.__pybytes_connection = pybytes_connection + self.__pybytes_library.set_network_type(networkType) + def __wifi_or_lte_connection(self): return self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_MQTT_WIFI or self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_MQTT_LTE # noqa @@ -119,7 +137,7 @@ def __check_lora_messages(self): self.__pybytes_connection.__lora_socket.setblocking(False) message = self.__pybytes_connection.__lora_socket.recv(256) except Exception as ex: - print_debug(5, "Exception in PybytesProtocol.__check_lora_messages: {}".format(ex)) # noqa + print_debug(5, "Exception in PybytesProtocol.__check_lora_messages: {}".format(ex)) if (message): self.__process_recv_message(message) time.sleep(0.5) @@ -128,16 +146,16 @@ def __process_recv_message(self, message): print_debug(5, "This is PybytesProtocol.__process_recv_message()") if message.payload: - network_type, message_type, body = self.__pybytes_library.unpack_message(message.payload) # noqa + network_type, message_type, body = self.__pybytes_library.unpack_message(message.payload) else: # for lora messages - network_type, message_type, body = self.__pybytes_library.unpack_message(message) # noqa + network_type, message_type, body = self.__pybytes_library.unpack_message(message) if self.__user_message_callback is not None: if (message_type == constants.__TYPE_PING): self.send_ping_message() - elif message_type == constants.__TYPE_PONG and self.__conf.get('connection_watchdog', True): # noqa + elif message_type == constants.__TYPE_PONG and self.__conf.get('connection_watchdog', True): self.__pybytes_connection.__wifi_lte_watchdog.feed() elif (message_type == constants.__TYPE_INFO): @@ -168,6 +186,32 @@ def __process_recv_message(self, message): ) ota.update_device_network_config(self.__FCOTA, self.__conf) + elif (message_type == constants.__TYPE_PYMESH): + # create pymesh config file + wmac = hexlify(machine.unique_id()).decode('ascii') + pymeshConfig = PybytesPymeshConfig() + pymeshConfig.write_config(wmac=wmac.upper(), pymeshSettings=pymeshConfig.get_config(token=self.__conf['device_id'])) + + # start OTA update + ota = WiFiOTA( + self.__conf['wifi']['ssid'], + self.__conf['wifi']['password'], + self.__conf['ota_server']['domain'], + self.__conf['ota_server']['port'] + ) + + if (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): + print_debug(5, 'Connecting to WiFi') + ota.connect() + + print_debug(5, "Performing OTA") + result = ota.update(fwtype="pymesh", token=self.__conf['device_id']) + self.send_ota_response(result=result, topic='mesh') + time.sleep(1.5) + if (result == 2): + # Reboot the device to run the new decode + machine.reset() + elif (message_type == constants.__TYPE_OTA): ota = WiFiOTA( self.__conf['wifi']['ssid'], @@ -176,13 +220,13 @@ def __process_recv_message(self, message): self.__conf['ota_server']['port'] ) - if (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): # noqa + if (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): print_debug(5, 'Connecting to WiFi') ota.connect() print_debug(5, "Performing OTA") result = ota.update() - self.send_ota_response(result) + self.send_ota_response(result=result, topic='ota') time.sleep(1.5) if (result == 2): # Reboot the device to run the new decode @@ -190,19 +234,19 @@ def __process_recv_message(self, message): elif (message_type == constants.__TYPE_FCOTA): print_debug(2, 'receiving FCOTA request') - if (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): # noqa + if (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_DISCONNECTED): print_debug(5, 'Not connected, Re-Connecting ...') ota.connect() command = body[0] - if (command == constants.__FCOTA_COMMAND_HIERARCHY_ACQUISITION): # noqa + if (command == constants.__FCOTA_COMMAND_HIERARCHY_ACQUISITION): self.send_fcota_ping('acquiring hierarchy...') hierarchy = self.__FCOTA.get_flash_hierarchy() self.send_fcota_hierarchy(hierarchy) elif (command == constants.__FCOTA_COMMAND_FILE_ACQUISITION): path = body[1:len(body)].decode() - if (path[len(path)-2:len(path)] == '.py'): + if (path[len(path) - 2:len(path)] == '.py'): self.send_fcota_ping('acquiring file...') content = self.__FCOTA.get_file_content(path) size = self.__FCOTA.get_file_size(path) @@ -213,14 +257,14 @@ def __process_recv_message(self, message): splittedBody = bodyString.split(',') if (len(splittedBody) >= 2): path = splittedBody[0] - print_debug(2, path[len(path)-7:len(path)]) - if (path[len(path)-7:len(path)] != '.pymakr'): + print_debug(2, path[len(path) - 7:len(path)]) + if (path[len(path) - 7:len(path)] != '.pymakr'): self.send_fcota_ping('updating file...') - newContent = bodyString[len(path)+1:len(body)] - if (self.__FCOTA.update_file_content(path, newContent) is True): # noqa + newContent = bodyString[len(path) + 1:len(body)] + if (self.__FCOTA.update_file_content(path, newContent) is True): size = self.__FCOTA.get_file_size(path) self.send_fcota_file(newContent, path, size) - if (path[len(path)-7:len(path)] != '.pymakr'): + if (path[len(path) - 7:len(path)] != '.pymakr'): time.sleep(2) self.send_fcota_ping('board restarting...') time.sleep(2) @@ -232,6 +276,23 @@ def __process_recv_message(self, message): else: self.send_fcota_ping("file update failed!") + elif (command == constants.__FCOTA_COMMAND_FILE_UPDATE_NO_RESET): + bodyString = body[1:len(body)].decode() + splittedBody = bodyString.split(',') + if (len(splittedBody) >= 2): + path = splittedBody[0] + print_debug(2, path[len(path)-7:len(path)]) + if (path[len(path)-7:len(path)] != '.pymakr'): + self.send_fcota_ping('updating file...') + newContent = bodyString[len(path)+1:len(body)] + if (self.__FCOTA.update_file_content(path, newContent) is True): # noqa + size = self.__FCOTA.get_file_size(path) + self.send_fcota_file(newContent, path, size) + else: + self.send_fcota_ping('file update failed!') + else: + self.send_fcota_ping("file update failed!") + elif (command == constants.__FCOTA_PING): self.send_fcota_ping('') @@ -289,7 +350,7 @@ def __process_recv_message(self, message): pin.duty_cycle(value * 100) elif (command == constants.__COMMAND_CUSTOM_METHOD): - if (pin_number == constants.__TERMINAL_PIN and self.__terminal_enabled): # noqa + if (pin_number == constants.__TERMINAL_PIN and self.__terminal_enabled): original_dupterm = os.dupterm() os.dupterm(self.__terminal) self.__terminal.message_sent_from_pybytes_start() @@ -319,15 +380,15 @@ def __process_recv_message(self, message): value = body[i: i + 2] parameters[i / 3] = (value[0] << 8) | value[1] - method_return = self.__custom_methods[pin_number](parameters) # noqa + method_return = self.__custom_methods[pin_number](parameters) - if (method_return is not None and len(method_return) > 0): # noqa + if (method_return is not None and len(method_return) > 0): self.send_pybytes_custom_method_values( - pin_number, method_return + signal_number, method_return ) else: - print("WARNING: Trying to write to an unregistered Virtual Pin") # noqa + print("WARNING: Trying to write to an unregistered Virtual Pin") else: try: @@ -372,28 +433,39 @@ def __configure_pwm_pin(self, pin_number): ) def __send_message(self, message, topic=None, priority=True): - try: - finalTopic = self.__mqtt_upload_topic if topic is None else self.__mqtt_upload_topic + "/" + topic # noqa - if self.__wifi_or_lte_connection(): - self.__pybytes_connection.__connection.publish( - finalTopic, message, priority=priority - ) - elif (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_LORA): # noqa - with self.__pybytes_connection.lora_lock: - self.__pybytes_connection.__lora_socket.setblocking(True) - self.__pybytes_connection.__lora_socket.send(message) - self.__pybytes_connection.__lora_socket.setblocking(False) - elif (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_SIGFOX): # noqa - if (len(message) > 12): - print("WARNING: Message not sent, Sigfox only supports 12 Bytes messages") # noqa - return - self.__pybytes_connection.__sigfox_socket.send(message) + finalTopic = self.__mqtt_upload_topic if topic is None else self.__mqtt_upload_topic + "/" + topic + if self.__conf_reader.get_communication_type() == constants.__SIMPLE_COAP: + print_debug(1, 'CoAP Protocol') + owner = self.__conf.get('username') + self.__pybytes_connection.__connection.send_coap_message( + message, + Coap.REQUEST_GET, + '{}/{}'.format(owner, finalTopic), + "t{}".format(time.time()), + ) + else: + print_debug(1, 'MQTT Protocol') + try: + if self.__wifi_or_lte_connection(): + self.__pybytes_connection.__connection.publish( + finalTopic, message, priority=priority + ) + elif (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_LORA): + with self.__pybytes_connection.lora_lock: + self.__pybytes_connection.__lora_socket.setblocking(True) + self.__pybytes_connection.__lora_socket.send(message) + self.__pybytes_connection.__lora_socket.setblocking(False) + elif (self.__pybytes_connection.__connection_status == constants.__CONNECTION_STATUS_CONNECTED_SIGFOX): + if (len(message) > 12): + print("WARNING: Message not sent, Sigfox only supports 12 Bytes messages") + return + self.__pybytes_connection.__sigfox_socket.send(message) - else: - print_debug(2, "Warning: Sending without a connection") - pass - except Exception as ex: - print(ex) + else: + print_debug(2, "Warning: Sending without a connection") + pass + except Exception as ex: + print(ex) def send_user_message(self, message_type, body): self.__send_message( @@ -416,7 +488,7 @@ def send_network_info_message(self): self.__send_message(self.__pybytes_library.pack_network_info_message()) def send_scan_info_message(self, lora): - print('WARNING! send_scan_info_message is deprecated and should be called only from Pybytes.') # noqa + print('WARNING! send_scan_info_message is deprecated and should be called only from Pybytes.') def send_battery_info(self): self.__send_message( @@ -425,11 +497,11 @@ def send_battery_info(self): ) ) - def send_ota_response(self, result): + def send_ota_response(self, result, topic): print_debug(2, 'Sending OTA result back {}'.format(result)) self.__send_message( self.__pybytes_library.pack_ota_message(result), - 'ota' + topic ) def send_fcota_hierarchy(self, hierarchy): @@ -459,37 +531,37 @@ def send_pybytes_digital_value(self, pin_number, pull_mode): if (pin_number not in self.__pins): self.__configure_digital_pin(pin_number, Pin.IN, pull_mode) pin = self.__pins[pin_number] - self.send_pybytes_custom_method_values(pin_number, [pin()]) + self.send_pybytes_custom_method_values(signal_number, [pin()]) def send_pybytes_analog_value(self, pin_number): if (pin_number not in self.__pins): self.__configure_analog_pin(pin_number) pin = self.__pins[pin_number] - self.send_pybytes_custom_method_values(pin_number, [pin()]) + self.send_pybytes_custom_method_values(signal_number, [pin()]) - def send_pybytes_custom_method_values(self, method_id, parameters): + def send_pybytes_custom_method_values(self, method_id, parameters, topic=None): if(isinstance(parameters[0], int)): values = bytearray(struct.pack(">i", parameters[0])) values.append(constants.__INTEGER) self.__send_pybytes_message_variable( - constants.__COMMAND_CUSTOM_METHOD, method_id, values + constants.__COMMAND_CUSTOM_METHOD, method_id, values, topic ) elif(isinstance(parameters[0], float)): values = bytearray(struct.pack(" 2: + token = x[1] + rcv_data = rcv_data[len(self.__pack_tocken_prefix) + len(token) + len(self.__pack_tocken_sep):] + pkt = 'BR %d B from %s (%s), to %s ( %d): %s' % (len(rcv_data), token, rcv_ip, dest_ip, dest_port, str(rcv_data)) + print_debug(99, 'Pymesh node packet: {} '.format(pkt)) + self.__pybytes.send_node_signal(1, str(rcv_data.decode()).replace("#", ""), token.decode()) + return + + def get_config(self, token, silent=False): + url = '{}://{}/pymesh/{}'.format( + constants.__DEFAULT_PYCONFIG_PROTOCOL, + constants.__DEFAULT_PYCONFIG_DOMAIN, + token + ) + try: + pymesh = urequest.get(url, headers={'content-type': 'application/json'}) + except Exception as e: + if not silent: + print("Exception: {}".format(e)) + return pymesh.content + + def write_config(self, wmac, file='/flash/pymesh_config.json', pymeshSettings={}, silent=False): + try: + customSettings = json.loads(pymeshSettings.decode()) + default = { + "LoRa": customSettings["LoRa"], + "Pymesh": customSettings["Pymesh"], + "debug": 5, + "ble_api": False, + "ble_name_prefix": "Device-{}".format(wmac), + "br_prio": 0, + "br_ena": customSettings["br_ena"], + "autostart": True + } + + f = open(file, 'w') + f.write(json.dumps(default).encode('utf-8')) + f.close() + if not silent: + print("Pymesh configuration written to {}".format(file)) + except Exception as e: + if not silent: + print("Exception: {}".format(e)) diff --git a/esp32/frozen/Pybytes/_terminal.py b/esp32/frozen/Pybytes/_terminal.py index 202a4e889d..9906a1ba2d 100644 --- a/esp32/frozen/Pybytes/_terminal.py +++ b/esp32/frozen/Pybytes/_terminal.py @@ -1,5 +1,5 @@ ''' -Copyright (c) 2019, Pycom Limited. +Copyright (c) 2020, Pycom Limited. This software is licensed under the GNU GPL version 3 or any later version, with permitted additional terms. For more information see the Pycom Licence v1.0 document supplied with this file, or diff --git a/esp32/ftp/ftp.c b/esp32/ftp/ftp.c index 76c72959ac..6c551614bc 100644 --- a/esp32/ftp/ftp.c +++ b/esp32/ftp/ftp.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -338,7 +338,7 @@ STATIC FRESULT f_readdir_helper(ftp_dir_t *dp, ftp_fileinfo_t *fno ) { if(length_of_relative_path > 1) { path_length++; } - char* file_relative_path = m_malloc(path_length); + char* file_relative_path = malloc(path_length); // Copy the current working directory (relative path) memcpy(file_relative_path, path_relative, length_of_relative_path); @@ -359,7 +359,7 @@ STATIC FRESULT f_readdir_helper(ftp_dir_t *dp, ftp_fileinfo_t *fno ) { fno->u.fpinfo_lfs.timestamp.ftime = 0; } - m_free(file_relative_path); + free(file_relative_path); } xSemaphoreGive(littlefs->mutex); @@ -614,10 +614,10 @@ static void ftp_return_to_previous_path (char *pwd, char *dir); ******************************************************************************/ void ftp_init (void) { // allocate memory for the data buffer, and the file system structs (from the RTOS heap) - ftp_data.dBuffer = heap_caps_malloc(FTP_BUFFER_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); - ftp_path = heap_caps_malloc(FTP_MAX_PARAM_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); - ftp_scratch_buffer = heap_caps_malloc(FTP_MAX_PARAM_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); - ftp_cmd_buffer = heap_caps_malloc(FTP_MAX_PARAM_SIZE + FTP_CMD_SIZE_MAX, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + ftp_data.dBuffer = malloc(FTP_BUFFER_SIZE); + ftp_path = malloc(FTP_MAX_PARAM_SIZE); + ftp_scratch_buffer = malloc(FTP_MAX_PARAM_SIZE); + ftp_cmd_buffer = malloc(FTP_MAX_PARAM_SIZE + FTP_CMD_SIZE_MAX); SOCKETFIFO_Init (&ftp_socketfifo, (void *)ftp_fifoelements, FTP_SOCKETFIFO_ELEMENTS_MAX); ftp_data.c_sd = -1; ftp_data.d_sd = -1; @@ -933,7 +933,7 @@ static void ftp_send_reply (uint32_t status, char *message) { strcat ((char *)ftp_cmd_buffer, "\r\n"); fifoelement.sd = &ftp_data.c_sd; fifoelement.datasize = strlen((char *)ftp_cmd_buffer); - fifoelement.data = pvPortMalloc(fifoelement.datasize); + fifoelement.data = malloc(fifoelement.datasize); if (status == 221) { fifoelement.closesockets = E_FTP_CLOSE_CMD_AND_DATA; } else if (status == 426 || status == 451 || status == 550) { @@ -945,7 +945,7 @@ static void ftp_send_reply (uint32_t status, char *message) { if (fifoelement.data) { memcpy (fifoelement.data, ftp_cmd_buffer, fifoelement.datasize); if (!SOCKETFIFO_Push (&fifoelement)) { - vPortFree(fifoelement.data); + free(fifoelement.data); } } } @@ -979,13 +979,13 @@ static void ftp_send_from_fifo (void) { ftp_close_filesystem_on_error(); } if (fifoelement.freedata) { - vPortFree(fifoelement.data); + free(fifoelement.data); } } } else { // socket closed, remove it from the queue SOCKETFIFO_Pop (&fifoelement); if (fifoelement.freedata) { - vPortFree(fifoelement.data); + free(fifoelement.data); } } } else if (ftp_data.state == E_FTP_STE_END_TRANSFER && (ftp_data.d_sd > 0)) { diff --git a/esp32/ftp/ftp.h b/esp32/ftp/ftp.h index d4824c572b..39e9d4658c 100644 --- a/esp32/ftp/ftp.h +++ b/esp32/ftp/ftp.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/ftp/updater.c b/esp32/ftp/updater.c index febe418986..03513a10cd 100644 --- a/esp32/ftp/updater.c +++ b/esp32/ftp/updater.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/ftp/updater.h b/esp32/ftp/updater.h index 5ae31ceaa5..b274ba53bd 100644 --- a/esp32/ftp/updater.h +++ b/esp32/ftp/updater.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/get_idf_libs.py b/esp32/get_idf_libs.py old mode 100644 new mode 100755 index 1a5c377dff..b2bd8129b0 --- a/esp32/get_idf_libs.py +++ b/esp32/get_idf_libs.py @@ -1,3 +1,5 @@ +#!/usr/bin/python + import os import sys import argparse @@ -6,8 +8,9 @@ def main(): + src_def = os.environ['IDF_PATH']+'/examples/wifi/scan/build' cmd_parser = argparse.ArgumentParser(description='Get the precompiled libs from the IDF') - cmd_parser.add_argument('--idflibs', default=None, help='the path to the idf libraries') + cmd_parser.add_argument('--idflibs', default=src_def, help='the path to the idf libraries (' + src_def + ')') cmd_args = cmd_parser.parse_args() src = cmd_args.idflibs @@ -28,6 +31,7 @@ def main(): shutil.copy(src + '/bootloader/micro-ecc/libmicro-ecc.a', dsttmpbl) shutil.copy(src + '/bootloader/soc/libsoc.a', dsttmpbl) shutil.copy(src + '/bootloader/spi_flash/libspi_flash.a', dsttmpbl) + shutil.copy(src + '/bootloader/efuse/libefuse.a', dsttmpbl) # copy the application libraries @@ -62,6 +66,10 @@ def main(): shutil.copy(src + '/esp_ringbuf/libesp_ringbuf.a', dsttmpapp) shutil.copy(src + '/coap/libcoap.a', dsttmpapp) shutil.copy(src + '/mdns/libmdns.a', dsttmpapp) + shutil.copy(src + '/efuse/libefuse.a', dsttmpapp) + shutil.copy(src + '/espcoredump/libespcoredump.a', dsttmpapp) + shutil.copy(src + '/app_update/libapp_update.a', dsttmpapp) + except: print("Couldn't Copy IDF libs defaulting to Local Lib Folders!") traceback.print_exc() @@ -75,10 +83,19 @@ def main(): for item in os.listdir(dsttmpapp): shutil.copy(dsttmpapp + '/' + item, dstapp + '/' + item) + # copy the project's linker script + shutil.copy(src + '/esp32/esp32.project.ld', ".") + + # copy the generated sdkconfig.h + with open(src + '/include/sdkconfig.h', 'r') as input: + content = input.read() + with open(os.path.dirname(os.path.realpath(__file__)) + '/sdkconfig.h', 'w') as output: + output.write(content.replace('#define CONFIG_SECURE_BOOT_ENABLED 1','')) + shutil.rmtree(dsttmpbl) shutil.rmtree(dsttmpapp) - print("IDF Libs copied Successfully!") + print("IDF Libs, linker script and sdkconfig.h copied successfully!") if __name__ == "__main__": diff --git a/esp32/get_sigfox_libs.py b/esp32/get_sigfox_libs.py new file mode 100755 index 0000000000..92ba7f0375 --- /dev/null +++ b/esp32/get_sigfox_libs.py @@ -0,0 +1,24 @@ +#!/usr/bin/python3 + +import os +import sys +import argparse +import shutil +import traceback + + +def main(): + try: + shutil.copy('./build/FIPY/release/sigfox/sigfox.a', './sigfox/modsigfox_FIPY.a') + shutil.copy('./build/LOPY4/release/sigfox/sigfox.a', './sigfox/modsigfox_LOPY4.a') + shutil.copy('./build/SIPY/release/sigfox/sigfox.a', './sigfox/modsigfox_SIPY.a') + except: + print("Couldn't copy Sigfox libs!") + traceback.print_exc() + return + + print("Sigfox libs copied successfully!") + + +if __name__ == "__main__": + main() diff --git a/esp32/hal/esp32_mphal.c b/esp32/hal/esp32_mphal.c index 233591325d..cdca99d8b5 100644 --- a/esp32/hal/esp32_mphal.c +++ b/esp32/hal/esp32_mphal.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/hal/esp32_mphal.h b/esp32/hal/esp32_mphal.h index 66cd974b1a..8958e391ed 100644 --- a/esp32/hal/esp32_mphal.h +++ b/esp32/hal/esp32_mphal.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lib/libapp_update.a b/esp32/lib/libapp_update.a new file mode 100644 index 0000000000..94394a73e5 Binary files /dev/null and b/esp32/lib/libapp_update.a differ diff --git a/esp32/lib/libbootloader_support.a b/esp32/lib/libbootloader_support.a index 827bda5744..79ca81540b 100644 Binary files a/esp32/lib/libbootloader_support.a and b/esp32/lib/libbootloader_support.a differ diff --git a/esp32/lib/libbt.a b/esp32/lib/libbt.a index fea2543c3f..ca64a29ad8 100644 Binary files a/esp32/lib/libbt.a and b/esp32/lib/libbt.a differ diff --git a/esp32/lib/libcoap.a b/esp32/lib/libcoap.a index e4dedc793e..4a33b6ffd5 100644 Binary files a/esp32/lib/libcoap.a and b/esp32/lib/libcoap.a differ diff --git a/esp32/lib/libcxx.a b/esp32/lib/libcxx.a index f82dfa4760..10d85b4bcc 100644 Binary files a/esp32/lib/libcxx.a and b/esp32/lib/libcxx.a differ diff --git a/esp32/lib/libdriver.a b/esp32/lib/libdriver.a index bfda23dee8..321664b292 100644 Binary files a/esp32/lib/libdriver.a and b/esp32/lib/libdriver.a differ diff --git a/esp32/lib/libefuse.a b/esp32/lib/libefuse.a new file mode 100644 index 0000000000..e8f31cd1d3 Binary files /dev/null and b/esp32/lib/libefuse.a differ diff --git a/esp32/lib/libesp32.a b/esp32/lib/libesp32.a index 3545e7ab13..f565dd3582 100644 Binary files a/esp32/lib/libesp32.a and b/esp32/lib/libesp32.a differ diff --git a/esp32/lib/libesp_adc_cal.a b/esp32/lib/libesp_adc_cal.a index 064cc3cb26..33a62acd7b 100644 Binary files a/esp32/lib/libesp_adc_cal.a and b/esp32/lib/libesp_adc_cal.a differ diff --git a/esp32/lib/libesp_ringbuf.a b/esp32/lib/libesp_ringbuf.a index 9984660ba7..f668616246 100644 Binary files a/esp32/lib/libesp_ringbuf.a and b/esp32/lib/libesp_ringbuf.a differ diff --git a/esp32/lib/libespcoredump.a b/esp32/lib/libespcoredump.a new file mode 100644 index 0000000000..32cf2d5402 Binary files /dev/null and b/esp32/lib/libespcoredump.a differ diff --git a/esp32/lib/libexpat.a b/esp32/lib/libexpat.a index 59a7bea4ef..084dfb0365 100644 Binary files a/esp32/lib/libexpat.a and b/esp32/lib/libexpat.a differ diff --git a/esp32/lib/libfreertos.a b/esp32/lib/libfreertos.a index 41eaa61b75..1012fbdef2 100644 Binary files a/esp32/lib/libfreertos.a and b/esp32/lib/libfreertos.a differ diff --git a/esp32/lib/libheap.a b/esp32/lib/libheap.a index 4e26d21651..7ec9091c45 100644 Binary files a/esp32/lib/libheap.a and b/esp32/lib/libheap.a differ diff --git a/esp32/lib/libjsmn.a b/esp32/lib/libjsmn.a index cb8fcdd8fa..70858f09c3 100644 Binary files a/esp32/lib/libjsmn.a and b/esp32/lib/libjsmn.a differ diff --git a/esp32/lib/libjson.a b/esp32/lib/libjson.a index acc84d42a4..93b2e6f797 100644 Binary files a/esp32/lib/libjson.a and b/esp32/lib/libjson.a differ diff --git a/esp32/lib/liblog.a b/esp32/lib/liblog.a index df43624c42..22f3ab1f6f 100644 Binary files a/esp32/lib/liblog.a and b/esp32/lib/liblog.a differ diff --git a/esp32/lib/liblwip.a b/esp32/lib/liblwip.a index c3840f8adb..feb0a24e47 100644 Binary files a/esp32/lib/liblwip.a and b/esp32/lib/liblwip.a differ diff --git a/esp32/lib/libmbedtls.a b/esp32/lib/libmbedtls.a index 1ddd73744f..23f89a4b1e 100644 Binary files a/esp32/lib/libmbedtls.a and b/esp32/lib/libmbedtls.a differ diff --git a/esp32/lib/libmdns.a b/esp32/lib/libmdns.a index 2d930b1c17..e3e492e8b7 100644 Binary files a/esp32/lib/libmdns.a and b/esp32/lib/libmdns.a differ diff --git a/esp32/lib/libmicro-ecc.a b/esp32/lib/libmicro-ecc.a index 3fac87564c..710d1e34b0 100644 Binary files a/esp32/lib/libmicro-ecc.a and b/esp32/lib/libmicro-ecc.a differ diff --git a/esp32/lib/libnewlib.a b/esp32/lib/libnewlib.a index ce45de2f81..c118ba894e 100644 Binary files a/esp32/lib/libnewlib.a and b/esp32/lib/libnewlib.a differ diff --git a/esp32/lib/libnghttp.a b/esp32/lib/libnghttp.a index 3cb3159025..7e79a2c9ef 100644 Binary files a/esp32/lib/libnghttp.a and b/esp32/lib/libnghttp.a differ diff --git a/esp32/lib/libnvs_flash.a b/esp32/lib/libnvs_flash.a index 1dd0272fbd..2aa0d9f61c 100644 Binary files a/esp32/lib/libnvs_flash.a and b/esp32/lib/libnvs_flash.a differ diff --git a/esp32/lib/libopenssl.a b/esp32/lib/libopenssl.a index 3a7ba5afe1..d843303fc0 100644 Binary files a/esp32/lib/libopenssl.a and b/esp32/lib/libopenssl.a differ diff --git a/esp32/lib/libpthread.a b/esp32/lib/libpthread.a index 74263519b5..475cfc9272 100644 Binary files a/esp32/lib/libpthread.a and b/esp32/lib/libpthread.a differ diff --git a/esp32/lib/libsdmmc.a b/esp32/lib/libsdmmc.a index 83544cc3fa..356fcc7803 100644 Binary files a/esp32/lib/libsdmmc.a and b/esp32/lib/libsdmmc.a differ diff --git a/esp32/lib/libsmartconfig_ack.a b/esp32/lib/libsmartconfig_ack.a index c7ecd2c0d7..2541ac8b38 100644 Binary files a/esp32/lib/libsmartconfig_ack.a and b/esp32/lib/libsmartconfig_ack.a differ diff --git a/esp32/lib/libsoc.a b/esp32/lib/libsoc.a index c9ad01eb5f..e1dd6f1513 100644 Binary files a/esp32/lib/libsoc.a and b/esp32/lib/libsoc.a differ diff --git a/esp32/lib/libspi_flash.a b/esp32/lib/libspi_flash.a index 276b95b5ac..15f014b0f9 100644 Binary files a/esp32/lib/libspi_flash.a and b/esp32/lib/libspi_flash.a differ diff --git a/esp32/lib/libtcpip_adapter.a b/esp32/lib/libtcpip_adapter.a index a90caa38f1..6575ed7676 100644 Binary files a/esp32/lib/libtcpip_adapter.a and b/esp32/lib/libtcpip_adapter.a differ diff --git a/esp32/lib/libvfs.a b/esp32/lib/libvfs.a index 7a5bdde185..ddf514fafc 100644 Binary files a/esp32/lib/libvfs.a and b/esp32/lib/libvfs.a differ diff --git a/esp32/lib/libwpa_supplicant.a b/esp32/lib/libwpa_supplicant.a index d9cde52574..2bbda5189a 100644 Binary files a/esp32/lib/libwpa_supplicant.a and b/esp32/lib/libwpa_supplicant.a differ diff --git a/esp32/lib/libxtensa-debug-module.a b/esp32/lib/libxtensa-debug-module.a index 6708183cc0..3896557a10 100644 Binary files a/esp32/lib/libxtensa-debug-module.a and b/esp32/lib/libxtensa-debug-module.a differ diff --git a/esp32/littlefs/lfs_util.h b/esp32/littlefs/lfs_util.h index 6c1c8ebe82..801ac80eda 100644 --- a/esp32/littlefs/lfs_util.h +++ b/esp32/littlefs/lfs_util.h @@ -21,7 +21,6 @@ #include "py/mpconfig.h" #include "py/misc.h" -#include "py/gc.h" // System includes #include @@ -204,7 +203,7 @@ uint32_t lfs_crc(uint32_t crc, const void *buffer, size_t size); // Note, memory must be 64-bit aligned static inline void *lfs_malloc(size_t size) { #ifndef LFS_NO_MALLOC - return gc_alloc(size, false); + return malloc(size); #else return NULL; #endif @@ -213,7 +212,7 @@ static inline void *lfs_malloc(size_t size) { // Deallocate memory, only used if buffers are not provided to littlefs static inline void lfs_free(void *p) { #ifndef LFS_NO_MALLOC - m_free(p); + free(p); #endif } diff --git a/esp32/littlefs/vfs_littlefs.c b/esp32/littlefs/vfs_littlefs.c index 1cb8c8ece2..f56ee84caa 100644 --- a/esp32/littlefs/vfs_littlefs.c +++ b/esp32/littlefs/vfs_littlefs.c @@ -4,7 +4,6 @@ #include #include "py/runtime.h" #include "py/mperrno.h" -#include "py/gc.h" #include "lib/oofatfs/ff.h" #include "extmod/vfs.h" #include "vfs_littlefs.h" @@ -18,14 +17,14 @@ int lfs_statvfs_count(void *p, lfs_block_t b) return 0; } -// After this function m_free() must be called on the returned address after usage!! +// After this function free() must be called on the returned address after usage!! const char* concat_with_cwd(vfs_lfs_struct_t* littlefs, const char* path) { char* path_out = NULL; if (path[0] == '/') /* Absolute path */ { - path_out = (char*)gc_alloc(strlen(path) + 1, false); // Count the \0 too + path_out = (char*)malloc(strlen(path) + 1); // Count the \0 too if(path_out != NULL) { strcpy(path_out, path); @@ -33,7 +32,7 @@ const char* concat_with_cwd(vfs_lfs_struct_t* littlefs, const char* path) } else { - path_out = (char*)gc_alloc(strlen(littlefs->cwd) + 1 + strlen(path) + 1, false); + path_out = (char*)malloc(strlen(littlefs->cwd) + 1 + strlen(path) + 1); if(path_out != NULL) { strcpy(path_out, littlefs->cwd); @@ -130,9 +129,8 @@ static int change_cwd(vfs_lfs_struct_t* littlefs, const char* path_in) } else if(is_valid_directory(littlefs, new_path)) { - m_free(littlefs->cwd); + free(littlefs->cwd); littlefs->cwd = (char*)new_path; - MP_STATE_PORT(lfs_cwd) = littlefs->cwd; res = LFS_ERR_OK; } @@ -354,12 +352,12 @@ void littlefs_prepare_attributes(struct lfs_file_config *cfg) { // Currently we only have 1 attribute cfg->attr_count = 1; - cfg->attrs = m_malloc(cfg->attr_count * sizeof(struct lfs_attr)); + cfg->attrs = malloc(cfg->attr_count * sizeof(struct lfs_attr)); // Set attribute for storing the timestamp cfg->attrs[0].size = sizeof(lfs_timestamp_attribute_t); cfg->attrs[0].type = LFS_ATTRIBUTE_TIMESTAMP; - cfg->attrs[0].buffer = m_malloc(sizeof(lfs_timestamp_attribute_t)); + cfg->attrs[0].buffer = malloc(sizeof(lfs_timestamp_attribute_t)); } @@ -367,8 +365,8 @@ void littlefs_free_up_attributes(struct lfs_file_config *cfg) { cfg->attr_count = 0; // Currently we only have 1 attribute for timestamp - m_free(cfg->attrs[0].buffer); - m_free(cfg->attrs); + free(cfg->attrs[0].buffer); + free(cfg->attrs); } @@ -479,18 +477,15 @@ STATIC mp_obj_t littlefs_vfs_ilistdir_func(size_t n_args, const mp_obj_t *args) iter->is_str = is_str_type; xSemaphoreTake(self->fs.littlefs.mutex, portMAX_DELAY); - const char* path = concat_with_cwd(&self->fs.littlefs, path_in); - if(path == NULL) - { + const char *path = concat_with_cwd(&self->fs.littlefs, path_in); + if (path == NULL) { res = LFS_ERR_NOMEM; - } - else - { + } else { res = lfs_dir_open(&self->fs.littlefs.lfs, &iter->dir, path); } xSemaphoreGive(self->fs.littlefs.mutex); - m_free((void*)path); + free((void*)path); if (res != LFS_ERR_OK) { mp_raise_OSError(littleFsErrorToErrno(res)); @@ -507,21 +502,18 @@ STATIC mp_obj_t littlefs_vfs_mkdir(mp_obj_t vfs_in, mp_obj_t path_param) { const char *path_in = mp_obj_str_get_str(path_param); xSemaphoreTake(self->fs.littlefs.mutex, portMAX_DELAY); - const char* path = concat_with_cwd(&self->fs.littlefs, path_in); - if(path == NULL) - { + const char *path = concat_with_cwd(&self->fs.littlefs, path_in); + if (path == NULL) { res = LFS_ERR_NOMEM; - } - else - { + } else { res = lfs_mkdir(&self->fs.littlefs.lfs, path); - if(res == LFS_ERR_OK) { + if (res == LFS_ERR_OK) { littlefs_update_timestamp(&self->fs.littlefs.lfs, path); } } xSemaphoreGive(self->fs.littlefs.mutex); - m_free((void*)path); + free((void*)path); if (res != LFS_ERR_OK) { mp_raise_OSError(littleFsErrorToErrno(res)); @@ -539,18 +531,15 @@ STATIC mp_obj_t littlefs_vfs_remove(mp_obj_t vfs_in, mp_obj_t path_param) { const char *path_in = mp_obj_str_get_str(path_param); xSemaphoreTake(self->fs.littlefs.mutex, portMAX_DELAY); - const char* path = concat_with_cwd(&self->fs.littlefs, path_in); - if(path == NULL) - { + const char *path = concat_with_cwd(&self->fs.littlefs, path_in); + if (path == NULL) { res = LFS_ERR_NOMEM; - } - else - { + } else { res = lfs_remove(&self->fs.littlefs.lfs, path); } xSemaphoreGive(self->fs.littlefs.mutex); - m_free((void*)path); + free((void*)path); if (res != LFS_ERR_OK) { mp_raise_OSError(littleFsErrorToErrno(res)); @@ -569,21 +558,18 @@ STATIC mp_obj_t littlefs_vfs_rename(mp_obj_t vfs_in, mp_obj_t path_param_in, mp_ const char *path_out = mp_obj_str_get_str(path_param_out); xSemaphoreTake(self->fs.littlefs.mutex, portMAX_DELAY); - const char* old_path = concat_with_cwd(&self->fs.littlefs, path_in); - const char* new_path = concat_with_cwd(&self->fs.littlefs, path_out); + const char *old_path = concat_with_cwd(&self->fs.littlefs, path_in); + const char *new_path = concat_with_cwd(&self->fs.littlefs, path_out); - if(old_path == NULL || new_path == NULL) - { + if (old_path == NULL || new_path == NULL) { res = LFS_ERR_NOMEM; - } - else - { + } else { res = lfs_rename(&self->fs.littlefs.lfs, old_path, new_path); } xSemaphoreGive(self->fs.littlefs.mutex); - m_free((void*)old_path); - m_free((void*)new_path); + free((void*)old_path); + free((void*)new_path); if (res != LFS_ERR_OK) { mp_raise_OSError(littleFsErrorToErrno(res)); @@ -634,13 +620,10 @@ STATIC mp_obj_t littlefs_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_param) { xSemaphoreTake(self->fs.littlefs.mutex, portMAX_DELAY); - const char* path = concat_with_cwd(&self->fs.littlefs, path_in); - if(path == NULL) - { + const char *path = concat_with_cwd(&self->fs.littlefs, path_in); + if (path == NULL) { res = LFS_ERR_NOMEM; - } - else if (path[0] == 0 || (path[0] == '/' && path[1] == 0)) - { + } else if (path[0] == 0 || (path[0] == '/' && path[1] == 0)) { // stat root directory fno.size = 0; fno.type = LFS_TYPE_DIR; @@ -650,7 +633,7 @@ STATIC mp_obj_t littlefs_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_param) { xSemaphoreGive(self->fs.littlefs.mutex); - m_free((void*)path); + free((void*)path); if (res < LFS_ERR_OK) { mp_raise_OSError(littleFsErrorToErrno(res)); @@ -686,9 +669,9 @@ STATIC mp_obj_t littlefs_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_param) { else { t->items[6] = mp_obj_new_int_from_uint(0); // st_size } - t->items[7] = MP_OBJ_NEW_SMALL_INT(seconds); // st_atime - t->items[8] = MP_OBJ_NEW_SMALL_INT(seconds); // st_mtime - t->items[9] = MP_OBJ_NEW_SMALL_INT(seconds); // st_ctime + t->items[7] = mp_obj_new_int_from_uint(seconds); // st_atime + t->items[8] = mp_obj_new_int_from_uint(seconds); // st_mtime + t->items[9] = mp_obj_new_int_from_uint(seconds); // st_ctime return MP_OBJ_FROM_PTR(t); } diff --git a/esp32/littlefs/vfs_littlefs_file.c b/esp32/littlefs/vfs_littlefs_file.c index e16e45df9d..aa7a90edb5 100644 --- a/esp32/littlefs/vfs_littlefs_file.c +++ b/esp32/littlefs/vfs_littlefs_file.c @@ -171,7 +171,7 @@ STATIC mp_obj_t file_open(fs_user_mount_t *vfs, const mp_obj_type_t *type, mp_ar int res = littlefs_open_common_helper(&vfs->fs.littlefs.lfs, fname, &o->fp, mode, &o->cfg, &o->timestamp_update); xSemaphoreGive(vfs->fs.littlefs.mutex); - m_free((void*)fname); + free((void*)fname); if (res < LFS_ERR_OK) { m_del_obj(pyb_file_obj_t, o); mp_raise_OSError(littleFsErrorToErrno(res)); diff --git a/esp32/lora/board.c b/esp32/lora/board.c index c918e58742..7a6c7f1bd9 100644 --- a/esp32/lora/board.c +++ b/esp32/lora/board.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/board.h b/esp32/lora/board.h index 61dfeb0a60..fc4829f8b5 100644 --- a/esp32/lora/board.h +++ b/esp32/lora/board.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/gpio-board.c b/esp32/lora/gpio-board.c index 30f26a3b37..babbbcefdd 100644 --- a/esp32/lora/gpio-board.c +++ b/esp32/lora/gpio-board.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/gpio-board.h b/esp32/lora/gpio-board.h index 7f9a5f84d4..a5d3577cea 100644 --- a/esp32/lora/gpio-board.h +++ b/esp32/lora/gpio-board.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/ot-log.c b/esp32/lora/ot-log.c index ec3399795f..d9de4a30e4 100644 --- a/esp32/lora/ot-log.c +++ b/esp32/lora/ot-log.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/ot-log.h b/esp32/lora/ot-log.h index 9a7a0b9905..678e92c9ec 100644 --- a/esp32/lora/ot-log.h +++ b/esp32/lora/ot-log.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/ot-settings.c b/esp32/lora/ot-settings.c index 2977edeb11..3948116791 100644 --- a/esp32/lora/ot-settings.c +++ b/esp32/lora/ot-settings.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/ot-settings.h b/esp32/lora/ot-settings.h index d769eacad5..a367d41473 100644 --- a/esp32/lora/ot-settings.h +++ b/esp32/lora/ot-settings.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/otplat_alarm.c b/esp32/lora/otplat_alarm.c index e89e27fdd2..9506db43e3 100644 --- a/esp32/lora/otplat_alarm.c +++ b/esp32/lora/otplat_alarm.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/otplat_alarm.h b/esp32/lora/otplat_alarm.h index 6e9a003e5c..bdbfa6af59 100644 --- a/esp32/lora/otplat_alarm.h +++ b/esp32/lora/otplat_alarm.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/otplat_radio.c b/esp32/lora/otplat_radio.c index 64f3bee47f..365a6771a0 100644 --- a/esp32/lora/otplat_radio.c +++ b/esp32/lora/otplat_radio.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/otplat_radio.h b/esp32/lora/otplat_radio.h index 487e7a7ec7..f0baa82918 100644 --- a/esp32/lora/otplat_radio.h +++ b/esp32/lora/otplat_radio.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/lora/pinName-board.h b/esp32/lora/pinName-board.h index 8b7d403875..a50a67b1c3 100644 --- a/esp32/lora/pinName-board.h +++ b/esp32/lora/pinName-board.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/spi-board.c b/esp32/lora/spi-board.c index 3a988515f1..27a7b6330a 100644 --- a/esp32/lora/spi-board.c +++ b/esp32/lora/spi-board.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/spi-board.h b/esp32/lora/spi-board.h index d790125665..4c77ec4aa5 100644 --- a/esp32/lora/spi-board.h +++ b/esp32/lora/spi-board.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lora/timer-board.c b/esp32/lora/timer-board.c index 61620ca2c3..7c11b0e392 100644 --- a/esp32/lora/timer-board.c +++ b/esp32/lora/timer-board.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence @@ -56,17 +56,11 @@ static TimerTime_t TimerTickCounterContext = 0; * Value trigging the IRQ */ DRAM_ATTR volatile TimerTime_t TimeoutCntValue = 0; -extern TaskHandle_t xLoRaTimerTaskHndl; static IRAM_ATTR void TimerCallback (void) { - BaseType_t xHigherPriorityTaskWoken = pdFALSE; - TimerTickCounter++; if (TimeoutCntValue > 0 && TimerTickCounter == TimeoutCntValue) { TimerIrqHandler(); - // Notify the thread so it will wake up when the ISR is complete - vTaskNotifyGiveFromISR(xLoRaTimerTaskHndl, &xHigherPriorityTaskWoken); - portYIELD_FROM_ISR(); } } diff --git a/esp32/lora/timer-board.h b/esp32/lora/timer-board.h index f0d930f600..cde36de4fb 100644 --- a/esp32/lora/timer-board.h +++ b/esp32/lora/timer-board.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/lte/lteppp.c b/esp32/lte/lteppp.c index 455fe4add4..43c46904a5 100644 --- a/esp32/lte/lteppp.c +++ b/esp32/lte/lteppp.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -159,7 +159,7 @@ void lteppp_init(void) { lteppp_connstatus = LTE_PPP_IDLE; #ifdef LTE_DEBUG_BUFF - lteppp_log.log = heap_caps_malloc(LTE_LOG_BUFF_SIZE, MALLOC_CAP_SPIRAM); + lteppp_log.log = malloc(LTE_LOG_BUFF_SIZE); #endif } diff --git a/esp32/lte/lteppp.h b/esp32/lte/lteppp.h index 2a76340ad2..ace8c2c3de 100644 --- a/esp32/lte/lteppp.h +++ b/esp32/lte/lteppp.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/main.c b/esp32/main.c index f337a05578..0d64729b67 100644 --- a/esp32/main.c +++ b/esp32/main.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -58,7 +58,7 @@ TaskHandle_t svTaskHandle; TaskHandle_t SmartConfTaskHandle; #if defined(LOPY) || defined (LOPY4) || defined (FIPY) TaskHandle_t xLoRaTaskHndl; -TaskHandle_t xLoRaTimerTaskHndl; +DRAM_ATTR TaskHandle_t xLoRaTimerTaskHndl; #endif #if defined(SIPY) || defined (LOPY4) || defined (FIPY) TaskHandle_t xSigfoxTaskHndl; @@ -149,7 +149,7 @@ void app_main(void) { micropy_lpwan_dio_pin_num = 23; micropy_lpwan_dio_pin = &pin_GPIO23; - mpTaskStack = heap_caps_malloc(MICROPY_TASK_STACK_SIZE_PSRAM, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + mpTaskStack = malloc(MICROPY_TASK_STACK_SIZE_PSRAM); // create the MicroPython task mpTaskHandle = @@ -172,7 +172,7 @@ void app_main(void) { micropy_lpwan_dio_pin_num = 23; micropy_lpwan_dio_pin = &pin_GPIO23; - mpTaskStack = heap_caps_malloc(MICROPY_TASK_STACK_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + mpTaskStack = malloc(MICROPY_TASK_STACK_SIZE); // create the MicroPython task mpTaskHandle = diff --git a/esp32/mods/lwipsocket.c b/esp32/mods/lwipsocket.c index 63d184c5aa..ebe5e70859 100644 --- a/esp32/mods/lwipsocket.c +++ b/esp32/mods/lwipsocket.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/lwipsocket.h b/esp32/mods/lwipsocket.h index 40f8bd2af3..08c5b30528 100644 --- a/esp32/mods/lwipsocket.h +++ b/esp32/mods/lwipsocket.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machcan.c b/esp32/mods/machcan.c index 49d8f4dc77..3715acb540 100644 --- a/esp32/mods/machcan.c +++ b/esp32/mods/machcan.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machcan.h b/esp32/mods/machcan.h index 9d0d30cf63..2b62acf5c5 100644 --- a/esp32/mods/machcan.h +++ b/esp32/mods/machcan.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machine_i2c.c b/esp32/mods/machine_i2c.c index ebe67c7e47..a29c0492be 100644 --- a/esp32/mods/machine_i2c.c +++ b/esp32/mods/machine_i2c.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/machine_i2c.h b/esp32/mods/machine_i2c.h index 1a84ff30fa..9762b88904 100644 --- a/esp32/mods/machine_i2c.h +++ b/esp32/mods/machine_i2c.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/machpin.c b/esp32/mods/machpin.c index 51c087c22b..ced3e65ef5 100644 --- a/esp32/mods/machpin.c +++ b/esp32/mods/machpin.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence @@ -118,6 +118,7 @@ void pin_init0(void) { pin_obj_t *self = (pin_obj_t *)named_map->table[i].value; if (self != &PIN_MODULE_P1) { // temporal while we remove all the IDF logs #ifdef DEBUG + // Pins needed for JTAG if (self == &PIN_MODULE_P4 || self == &PIN_MODULE_P9 || self == &PIN_MODULE_P10 || self == &PIN_MODULE_P23) { continue; } diff --git a/esp32/mods/machpin.h b/esp32/mods/machpin.h index 9cc8570590..af432283c6 100644 --- a/esp32/mods/machpin.h +++ b/esp32/mods/machpin.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machpwm.c b/esp32/mods/machpwm.c index a0b9f65544..323deb4f46 100644 --- a/esp32/mods/machpwm.c +++ b/esp32/mods/machpwm.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machpwm.h b/esp32/mods/machpwm.h index 708572f98c..ea268c78c1 100644 --- a/esp32/mods/machpwm.h +++ b/esp32/mods/machpwm.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machrmt.c b/esp32/mods/machrmt.c index c82809efc3..880f64b803 100644 --- a/esp32/mods/machrmt.c +++ b/esp32/mods/machrmt.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -365,7 +365,7 @@ STATIC mp_obj_t mach_rmt_pulses_send(mp_uint_t n_args, const mp_obj_t *pos_args, /* An rmt_item32_t can contain 2 bits, calculate the number of the necessary objects needed to store the input data */ mp_uint_t items_to_send_count = (data_length / 2) + (data_length % 2); - rmt_item32_t* items_to_send = (rmt_item32_t*)m_malloc(items_to_send_count * sizeof(rmt_item32_t)); + rmt_item32_t* items_to_send = (rmt_item32_t*)malloc(items_to_send_count * sizeof(rmt_item32_t)); for(mp_uint_t i = 0, j = 0; i < items_to_send_count; i++, j++) { items_to_send[i].level0 = mp_obj_get_int(data_ptr[j]); @@ -396,7 +396,7 @@ STATIC mp_obj_t mach_rmt_pulses_send(mp_uint_t n_args, const mp_obj_t *pos_args, esp_err_t retval = rmt_write_items(self->config.channel, items_to_send, items_to_send_count, wait_tx_done); MP_THREAD_GIL_ENTER(); - m_free(items_to_send); + free(items_to_send); if (retval != ESP_OK) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Could not send data!")); diff --git a/esp32/mods/machrmt.h b/esp32/mods/machrmt.h index 5c47471078..bfae12b30f 100644 --- a/esp32/mods/machrmt.h +++ b/esp32/mods/machrmt.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machrtc.c b/esp32/mods/machrtc.c index 75e06d0951..f2908c9899 100644 --- a/esp32/mods/machrtc.c +++ b/esp32/mods/machrtc.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machrtc.h b/esp32/mods/machrtc.h index e5f99133f7..f0238207d7 100644 --- a/esp32/mods/machrtc.h +++ b/esp32/mods/machrtc.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machspi.c b/esp32/mods/machspi.c index f16ea138b3..6ac7f81df0 100644 --- a/esp32/mods/machspi.c +++ b/esp32/mods/machspi.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/machspi.h b/esp32/mods/machspi.h index 9a06d371e4..73fa967d77 100644 --- a/esp32/mods/machspi.h +++ b/esp32/mods/machspi.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machtimer.c b/esp32/mods/machtimer.c index c5d489050f..03e2c902bc 100644 --- a/esp32/mods/machtimer.c +++ b/esp32/mods/machtimer.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machtimer.h b/esp32/mods/machtimer.h index b8cad3ec89..e2ed094fb1 100644 --- a/esp32/mods/machtimer.h +++ b/esp32/mods/machtimer.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machtimer_alarm.c b/esp32/mods/machtimer_alarm.c index 1415f539be..4bf444fcb4 100644 --- a/esp32/mods/machtimer_alarm.c +++ b/esp32/mods/machtimer_alarm.c @@ -8,7 +8,6 @@ #include "py/mpconfig.h" #include "py/nlr.h" #include "py/runtime.h" -#include "py/gc.h" #include "py/mperrno.h" #include "util/mpirq.h" @@ -56,7 +55,7 @@ void mach_timer_alarm_preinit(void) { void mach_timer_alarm_init_heap(void) { alarm_heap.count = 0; - MP_STATE_PORT(mp_alarm_heap) = gc_alloc(ALARM_HEAP_MAX_ELEMENTS * sizeof(mp_obj_alarm_t *), false); + MP_STATE_PORT(mp_alarm_heap) = m_malloc(ALARM_HEAP_MAX_ELEMENTS * sizeof(mp_obj_alarm_t *)); alarm_heap.data = MP_STATE_PORT(mp_alarm_heap); if (alarm_heap.data == NULL) { mp_printf(&mp_plat_print, "FATAL ERROR: not enough memory for the alarms heap\n"); diff --git a/esp32/mods/machtouch.h b/esp32/mods/machtouch.h index 3cf014d65e..0ad70ced7e 100644 --- a/esp32/mods/machtouch.h +++ b/esp32/mods/machtouch.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machuart.c b/esp32/mods/machuart.c index 40fb624929..6e515485c1 100644 --- a/esp32/mods/machuart.c +++ b/esp32/mods/machuart.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machuart.h b/esp32/mods/machuart.h index 1b1d0c9416..f116a29414 100644 --- a/esp32/mods/machuart.h +++ b/esp32/mods/machuart.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machwdt.c b/esp32/mods/machwdt.c index c2f03d0dd7..ad4e165958 100644 --- a/esp32/mods/machwdt.c +++ b/esp32/mods/machwdt.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/machwdt.h b/esp32/mods/machwdt.h index db5f674931..10f3a83cca 100644 --- a/esp32/mods/machwdt.h +++ b/esp32/mods/machwdt.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modbt.c b/esp32/mods/modbt.c index 6c3e389b64..2b720d69ab 100644 --- a/esp32/mods/modbt.c +++ b/esp32/mods/modbt.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -80,7 +80,6 @@ #define MOD_BT_GATTS_CLOSE_EVT (0x0400) #define MOD_BT_NVS_NAMESPACE "BT_NVS" #define MOD_BT_HASH_SIZE (20) -#define MOD_BT_PIN_LENGTH (6) /****************************************************************************** DEFINE PRIVATE TYPES @@ -103,6 +102,8 @@ typedef struct { bool advertising; bool controller_active; bool secure; + bool secure_connections; + bool privacy; } bt_obj_t; typedef struct { @@ -220,6 +221,14 @@ typedef union { uint8_t value[4]; } bt_hash_obj_t; +typedef struct { + bt_gatts_char_obj_t *chr; + uint32_t event; + uint32_t data_length; + uint8_t* data; +} char_cbk_arg_t; + + /****************************************************************************** DECLARE PRIVATE DATA ******************************************************************************/ @@ -247,16 +256,6 @@ static esp_ble_adv_params_t bt_adv_params = { .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, }; -static esp_ble_adv_params_t bt_adv_params_sec = { - .adv_int_min = 0x100, - .adv_int_max = 0x100, - .adv_type = ADV_TYPE_IND, - .own_addr_type = BLE_ADDR_TYPE_RANDOM, - .channel_map = ADV_CHNL_ALL, - .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, -}; - - static bool mod_bt_allow_resume_deinit; static uint16_t mod_bt_gatts_mtu_restore = 0; static bool mod_bt_is_conn_restore_available; @@ -416,11 +415,7 @@ void bt_resume(bool reconnect) /* See if there was an averstisment active before Sleep */ if(bt_obj.advertising) { - if (!bt_obj.secure){ - esp_ble_gap_start_advertising(&bt_adv_params); - } else { - esp_ble_gap_start_advertising(&bt_adv_params_sec); - } + esp_ble_gap_start_advertising(&bt_adv_params); } } @@ -472,22 +467,6 @@ static void create_hash(uint32_t pin, uint8_t *h_value) mbedtls_sha1_free(&sha1_context); } -static bool is_pin_valid(uint32_t pin) -{ - int digits = 0; - - while(pin != 0) - { - digits++; - pin /= 10; - } - - if (digits != MOD_BT_PIN_LENGTH){ - return false; - } - - return true; -} static bool pin_changed(uint32_t new_pin) { bool ret = false; @@ -521,25 +500,16 @@ static void remove_all_bonded_devices(void) { int dev_num = esp_ble_get_bond_device_num(); - esp_ble_bond_dev_t *dev_list = heap_caps_malloc(sizeof(esp_ble_bond_dev_t) * dev_num, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + esp_ble_bond_dev_t *dev_list = malloc(sizeof(esp_ble_bond_dev_t) * dev_num); esp_ble_get_bond_device_list(&dev_num, dev_list); for (int i = 0; i < dev_num; i++) { esp_ble_remove_bond_device(dev_list[i].bd_addr); } - free(dev_list); } -static void set_secure_parameters(uint32_t passKey){ - - if (pin_changed(passKey)) { - remove_all_bonded_devices(); - } - - uint32_t passkey = passKey; - esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t)); - - esp_ble_auth_req_t auth_req = ESP_LE_AUTH_REQ_SC_MITM_BOND; +static void set_secure_parameters(bool secure_connections) { + esp_ble_auth_req_t auth_req = secure_connections ? ESP_LE_AUTH_REQ_SC_MITM_BOND : ESP_LE_AUTH_BOND; esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &auth_req, sizeof(uint8_t)); esp_ble_io_cap_t iocap = ESP_IO_CAP_OUT; @@ -550,7 +520,7 @@ static void set_secure_parameters(uint32_t passKey){ uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE; esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t)); - + uint8_t init_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK; esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &init_key, sizeof(uint8_t)); @@ -558,6 +528,22 @@ static void set_secure_parameters(uint32_t passKey){ esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t)); } +static void set_pin(uint32_t new_pin) +{ + if (new_pin > 999999) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Pin code with 1-6 digit length is allowed only!")); + } + + if (pin_changed(new_pin)) { + remove_all_bonded_devices(); + } + + uint32_t passkey = new_pin; + esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t)); + bt_obj.secure = true; + set_secure_parameters(bt_obj.secure_connections); +} + static void close_connection (int32_t conn_id) { for (mp_uint_t i = 0; i < MP_STATE_PORT(btc_conn_list).len; i++) { bt_connection_obj_t *connection_obj = ((bt_connection_obj_t *)(MP_STATE_PORT(btc_conn_list).items[i])); @@ -642,7 +628,7 @@ static void gap_events_handler (esp_gap_ble_cb_event_t event, esp_ble_gap_cb_par } case ESP_GAP_BLE_NC_REQ_EVT: case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: { - printf("BLE paring passkey : %d\n", param->ble_security.key_notif.passkey); + //printf("BLE paring passkey : %d\n", param->ble_security.key_notif.passkey); break; } case ESP_GAP_BLE_SEC_REQ_EVT: { @@ -659,7 +645,7 @@ static void gap_events_handler (esp_gap_ble_cb_event_t event, esp_ble_gap_cb_par xQueueSend(xScanQueue, (void *)&bt_event_result, (TickType_t)0); bt_obj.events |= MOD_BT_GATTC_ADV_EVT; if (bt_obj.trigger & MOD_BT_GATTC_ADV_EVT) { - mp_irq_queue_interrupt(bluetooth_callback_handler, (void *)&bt_obj); + mp_irq_queue_interrupt_non_ISR(bluetooth_callback_handler, (void *)&bt_obj); } break; case ESP_GAP_SEARCH_DISC_RES_EVT: @@ -691,7 +677,7 @@ static void gattc_events_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc status = p_data->reg.status; bt_obj.gattc_if = gattc_if; if (bt_obj.secure){ - esp_ble_gap_config_local_privacy(true); + esp_ble_gap_config_local_privacy(bt_obj.privacy); } break; case ESP_GATTC_OPEN_EVT: @@ -765,7 +751,7 @@ static void gattc_events_handler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc char_obj->events |= MOD_BT_GATTC_INDICATE_EVT; } if ((char_obj->trigger & MOD_BT_GATTC_NOTIFY_EVT) || (char_obj->trigger & MOD_BT_GATTC_INDICATE_EVT)) { - mp_irq_queue_interrupt(gattc_char_callback_handler, char_obj); + mp_irq_queue_interrupt_non_ISR(gattc_char_callback_handler, char_obj); } } break; @@ -805,10 +791,21 @@ STATIC void gattc_char_callback_handler(void *arg) { // this function will be called by the interrupt thread STATIC void gatts_char_callback_handler(void *arg) { - bt_gatts_char_obj_t *chr = arg; + + bt_gatts_char_obj_t *chr = ((char_cbk_arg_t*)arg)->chr; if (chr->handler && chr->handler != mp_const_none) { - mp_obj_t r_value = mp_call_function_1(chr->handler, chr->handler_arg); + + mp_obj_t tuple[2]; + tuple[0] = mp_obj_new_int(((char_cbk_arg_t*)arg)->event); + tuple[1] = mp_const_none; + if(((char_cbk_arg_t*)arg)->data_length > 0) { + tuple[1] = mp_obj_new_bytes(((char_cbk_arg_t*)arg)->data, ((char_cbk_arg_t*)arg)->data_length); + free(((char_cbk_arg_t*)arg)->data); + free((char_cbk_arg_t*)arg); + } + + mp_obj_t r_value = mp_call_function_2(chr->handler, chr->handler_arg, mp_obj_new_tuple(2, tuple)); if (chr->read_request) { uint32_t u_value; @@ -855,7 +852,7 @@ static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_ case ESP_GATTS_REG_EVT: bt_obj.gatts_if = gatts_if; if (bt_obj.secure){ - esp_ble_gap_config_local_privacy(true); + esp_ble_gap_config_local_privacy(bt_obj.privacy); } break; case ESP_GATTS_READ_EVT: { @@ -867,7 +864,15 @@ static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_ if (char_obj->trigger & MOD_BT_GATTS_READ_EVT) { char_obj->read_request = true; char_obj->trans_id = p->read.trans_id; - mp_irq_queue_interrupt(gatts_char_callback_handler, char_obj); + + char_cbk_arg_t *cbk_arg = malloc(sizeof(char_cbk_arg_t)); + + cbk_arg->chr = char_obj; + cbk_arg->event = MOD_BT_GATTS_READ_EVT; + cbk_arg->data_length = 0; + cbk_arg->data = NULL; + + mp_irq_queue_interrupt_non_ISR(gatts_char_callback_handler, cbk_arg); break; } } @@ -894,7 +899,16 @@ static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_ bt_gatts_char_obj_t *char_obj = (bt_gatts_char_obj_t *)attr_obj; char_obj->events |= MOD_BT_GATTS_WRITE_EVT; if (char_obj->trigger & MOD_BT_GATTS_WRITE_EVT) { - mp_irq_queue_interrupt(gatts_char_callback_handler, char_obj); + + char_cbk_arg_t *cbk_arg = malloc(sizeof(char_cbk_arg_t)); + + cbk_arg->chr = char_obj; + cbk_arg->event = MOD_BT_GATTS_WRITE_EVT; + cbk_arg->data_length = write_len; + cbk_arg->data = malloc(cbk_arg->data_length); + memcpy(cbk_arg->data, p->write.value, cbk_arg->data_length); + + mp_irq_queue_interrupt_non_ISR(gatts_char_callback_handler, cbk_arg); } } else { // descriptor if (attr_obj->uuid.len == ESP_UUID_LEN_16 && attr_obj->uuid.uuid.uuid16 == GATT_UUID_CHAR_CLIENT_CONFIG) { @@ -903,7 +917,15 @@ static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_ char_obj->config = value; char_obj->events |= MOD_BT_GATTS_SUBSCRIBE_EVT; if (char_obj->trigger & MOD_BT_GATTS_SUBSCRIBE_EVT) { - mp_irq_queue_interrupt(gatts_char_callback_handler, char_obj); + + char_cbk_arg_t *cbk_arg = malloc(sizeof(char_cbk_arg_t)); + + cbk_arg->chr = char_obj; + cbk_arg->event = MOD_BT_GATTS_SUBSCRIBE_EVT; + cbk_arg->data_length = 0; + cbk_arg->data = NULL; + + mp_irq_queue_interrupt_non_ISR(gatts_char_callback_handler, cbk_arg); } if (value == 0x0001) { // notifications enabled @@ -961,10 +983,7 @@ static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_ bt_obj.gatts_conn_id = p->connect.conn_id; bt_obj.events |= MOD_BT_GATTS_CONN_EVT; if (bt_obj.trigger & MOD_BT_GATTS_CONN_EVT) { - mp_irq_queue_interrupt(bluetooth_callback_handler, (void *)&bt_obj); - } - if (bt_obj.secure){ - esp_ble_set_encryption(p->connect.remote_bda, ESP_BLE_SEC_ENCRYPT_MITM); + mp_irq_queue_interrupt_non_ISR(bluetooth_callback_handler, (void *)&bt_obj); } } break; @@ -972,16 +991,12 @@ static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_ bt_obj.gatts_conn_id = -1; xEventGroupClearBits(bt_event_group, MOD_BT_GATTS_MTU_EVT); if (bt_obj.advertising) { - if (!bt_obj.secure){ - esp_ble_gap_start_advertising(&bt_adv_params); - } else { - esp_ble_gap_start_advertising(&bt_adv_params_sec); - } + esp_ble_gap_start_advertising(&bt_adv_params); } bt_obj.events |= MOD_BT_GATTS_DISCONN_EVT; xEventGroupSetBits(bt_event_group, MOD_BT_GATTS_DISCONN_EVT); if (bt_obj.trigger & MOD_BT_GATTS_DISCONN_EVT) { - mp_irq_queue_interrupt(bluetooth_callback_handler, (void *)&bt_obj); + mp_irq_queue_interrupt_non_ISR(bluetooth_callback_handler, (void *)&bt_obj); } break; case ESP_GATTS_CLOSE_EVT: @@ -1028,7 +1043,7 @@ static mp_obj_t bt_init_helper(bt_obj_t *self, const mp_arg_val_t *args) { esp_ble_gatts_app_register(MOD_BT_SERVER_APP_ID); //set MTU - uint16_t mtu = args[5].u_int; + uint16_t mtu = args[6].u_int; if(mtu > BT_MTU_SIZE_MAX) { esp_ble_gatt_set_local_mtu(BT_MTU_SIZE_MAX); @@ -1072,27 +1087,35 @@ static mp_obj_t bt_init_helper(bt_obj_t *self, const mp_arg_val_t *args) { } } - if (args[3].u_bool){ + bt_obj.secure_connections = args[5].u_bool; + + if (args[3].u_obj != MP_OBJ_NULL){ bt_obj.secure = true; - uint32_t passKey = args[4].u_int; - if (!is_pin_valid(passKey)){ - nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Only 6 digit (0-9) pins are allowed")); - } - set_secure_parameters(passKey); + // modified default advertisement parameters for secure + bt_adv_params.adv_int_min = 0x100; + bt_adv_params.adv_int_max = 0x100; + bt_adv_params.own_addr_type = args[4].u_bool ? BLE_ADDR_TYPE_RANDOM : BLE_ADDR_TYPE_PUBLIC; + + set_pin(mp_obj_get_int(args[3].u_obj)); + bt_obj.privacy = args[4].u_bool; + set_secure_parameters(bt_obj.secure_connections); + } else { + bt_obj.secure = false; } return mp_const_none; } STATIC const mp_arg_t bt_init_args[] = { - { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = E_BT_STACK_MODE_BLE} }, - { MP_QSTR_antenna, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_modem_sleep, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_secure, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 123456} }, - { MP_QSTR_mtu, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = BT_MTU_SIZE_MAX} }, + { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_mode, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = E_BT_STACK_MODE_BLE} }, + { MP_QSTR_antenna, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_modem_sleep, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_pin, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_privacy, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_secure_connections, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_mtu, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = BT_MTU_SIZE_MAX} }, }; STATIC mp_obj_t bt_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *all_args) { @@ -1112,7 +1135,7 @@ STATIC mp_obj_t bt_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_resource_not_avaliable)); } - if (args[4].u_bool) { + if (args[4].u_obj != MP_OBJ_NULL) { if (heap_caps_get_free_size(MALLOC_CAP_SPIRAM) == 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError,"Secure BLE not available for 512K RAM devices")); } @@ -1376,6 +1399,8 @@ static mp_obj_t bt_connect_helper(mp_obj_t addr, TickType_t timeout){ MP_THREAD_GIL_EXIT(); if (xQueueReceive(xScanQueue, &bt_event, timeout) == pdTRUE) { + MP_THREAD_GIL_ENTER(); + if (bt_event.connection.conn_id < 0) { nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "connection refused")); } @@ -1385,7 +1410,11 @@ static mp_obj_t bt_connect_helper(mp_obj_t addr, TickType_t timeout){ conn->base.type = (mp_obj_t)&mod_bt_connection_type; conn->conn_id = bt_event.connection.conn_id; conn->gatt_if = bt_event.connection.gatt_if; + + MP_THREAD_GIL_EXIT(); uxBits = xEventGroupWaitBits(bt_event_group, MOD_BT_GATTC_MTU_EVT, true, true, 1000/portTICK_PERIOD_MS); + MP_THREAD_GIL_ENTER(); + if(uxBits & MOD_BT_GATTC_MTU_EVT) { conn->mtu = bt_conn_mtu; @@ -1396,10 +1425,11 @@ static mp_obj_t bt_connect_helper(mp_obj_t addr, TickType_t timeout){ } else { + MP_THREAD_GIL_ENTER(); + (void)esp_ble_gap_disconnect(bufinfo.buf); nlr_raise(mp_obj_new_exception_msg(&mp_type_TimeoutError, "timed out")); } - MP_THREAD_GIL_ENTER(); return mp_const_none; } @@ -1445,35 +1475,47 @@ static mp_obj_t modbt_connect(mp_obj_t addr) STATIC mp_obj_t bt_set_advertisement_params (mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { - { MP_QSTR_adv_int_min, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0x20} }, - { MP_QSTR_adv_int_max, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0x40} }, - { MP_QSTR_adv_type, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = ADV_TYPE_IND} }, - { MP_QSTR_own_addr_type, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = BLE_ADDR_TYPE_PUBLIC} }, - { MP_QSTR_channel_map, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = ADV_CHNL_ALL} }, - { MP_QSTR_adv_filter_policy, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY} }, + { MP_QSTR_adv_int_min, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_adv_int_max, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_adv_type, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_own_addr_type, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_channel_map, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_adv_filter_policy, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, }; // parse args mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), allowed_args, args); - + // adv_int_min - bt_adv_params.adv_int_min = (uint16_t)args[0].u_int; - + if (args[0].u_obj != MP_OBJ_NULL) { + bt_adv_params.adv_int_min = (uint16_t) mp_obj_get_int(args[0].u_obj); + } + // adv_int_max - bt_adv_params.adv_int_max = (uint16_t)args[1].u_int; + if (args[1].u_obj != MP_OBJ_NULL) { + bt_adv_params.adv_int_max = (uint16_t) mp_obj_get_int(args[1].u_obj); + } // adv_type - bt_adv_params.adv_type = (esp_ble_adv_type_t)args[2].u_int; - + if (args[2].u_obj != MP_OBJ_NULL) { + bt_adv_params.adv_type = (esp_ble_adv_type_t) mp_obj_get_int(args[2].u_obj); + } + // own_addr_type - bt_adv_params.own_addr_type = (esp_ble_addr_type_t)args[3].u_int; - + if (args[3].u_obj != MP_OBJ_NULL) { + bt_adv_params.own_addr_type = (esp_ble_addr_type_t) mp_obj_get_int(args[3].u_obj); + } + // channel_map - bt_adv_params.channel_map = (esp_ble_adv_channel_t)args[4].u_int; - + if (args[4].u_obj != MP_OBJ_NULL) { + bt_adv_params.channel_map = (esp_ble_adv_channel_t) mp_obj_get_int(args[4].u_obj); + } + // adv_filter_policy - bt_adv_params.adv_filter_policy = (esp_ble_adv_filter_t)args[5].u_int; + if (args[5].u_obj != MP_OBJ_NULL) { + bt_adv_params.adv_filter_policy = (esp_ble_adv_filter_t) mp_obj_get_int(args[5].u_obj); + } return mp_const_none; } @@ -1606,15 +1648,18 @@ STATIC mp_obj_t bt_set_advertisement_raw(mp_obj_t self_in, mp_obj_t raw_data) { STATIC MP_DEFINE_CONST_FUN_OBJ_2(bt_set_advertisement_raw_obj, bt_set_advertisement_raw); +STATIC mp_obj_t bt_set_pin(mp_obj_t self_in, mp_obj_t arg) { + set_pin(mp_obj_get_int(arg)); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(bt_set_pin_obj, bt_set_pin); + + STATIC mp_obj_t bt_advertise(mp_obj_t self_in, mp_obj_t enable) { if (mp_obj_is_true(enable)) { // some sensible time to wait for the advertisement configuration to complete mp_hal_delay_ms(50); - if (!bt_obj.secure){ - esp_ble_gap_start_advertising(&bt_adv_params); - } else { - esp_ble_gap_start_advertising(&bt_adv_params_sec); - } + esp_ble_gap_start_advertising(&bt_adv_params); bt_obj.advertising = true; } else { esp_ble_gap_stop_advertising(); @@ -2056,6 +2101,7 @@ STATIC const mp_map_elem_t bt_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_set_advertisement_params),(mp_obj_t)&bt_set_advertisement_params_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_advertisement), (mp_obj_t)&bt_set_advertisement_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_set_advertisement_raw), (mp_obj_t)&bt_set_advertisement_raw_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_set_pin), (mp_obj_t)&bt_set_pin_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_advertise), (mp_obj_t)&bt_advertise_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_service), (mp_obj_t)&bt_service_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_callback), (mp_obj_t)&bt_callback_obj }, @@ -2109,6 +2155,15 @@ STATIC const mp_map_elem_t bt_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_PROP_AUTH), MP_OBJ_NEW_SMALL_INT(ESP_GATT_CHAR_PROP_BIT_AUTH) }, { MP_OBJ_NEW_QSTR(MP_QSTR_PROP_EXT_PROP), MP_OBJ_NEW_SMALL_INT(ESP_GATT_CHAR_PROP_BIT_EXT_PROP) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_READ), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_READ) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_READ_ENCRYPTED), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_READ_ENCRYPTED) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_READ_ENC_MITM), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_READ_ENC_MITM) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_WRITE), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_WRITE) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_WRITE_ENCRYPTED), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_WRITE_ENCRYPTED) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_WRITE_ENC_MITM), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_WRITE_ENC_MITM) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_WRITE_SIGNED), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_WRITE_SIGNED) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PERM_WRITE_SIGNED_MITM), MP_OBJ_NEW_SMALL_INT(ESP_GATT_PERM_WRITE_SIGNED_MITM) }, + // Defined at https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml { MP_OBJ_NEW_QSTR(MP_QSTR_CHAR_CONFIG_NOTIFY), MP_OBJ_NEW_SMALL_INT(1 << 0) }, { MP_OBJ_NEW_QSTR(MP_QSTR_CHAR_CONFIG_INDICATE), MP_OBJ_NEW_SMALL_INT(1 << 1) }, @@ -2289,7 +2344,7 @@ STATIC mp_obj_t bt_srv_characteristics(mp_obj_t self_in) { &attr_count); if (attr_count > 0) { - esp_gattc_char_elem_t *char_elems = (esp_gattc_char_elem_t *)heap_caps_malloc(sizeof(esp_gattc_char_elem_t) * attr_count, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + esp_gattc_char_elem_t *char_elems = (esp_gattc_char_elem_t *)malloc(sizeof(esp_gattc_char_elem_t) * attr_count); if (!char_elems) { mp_raise_OSError(MP_ENOMEM); } else { @@ -2530,7 +2585,7 @@ STATIC mp_obj_t bt_char_callback(mp_uint_t n_args, const mp_obj_t *pos_args, mp_ self->characteristic.char_handle, &attr_count); if (attr_count > 0) { - esp_gattc_descr_elem_t *descr_elems = (esp_gattc_descr_elem_t *)heap_caps_malloc(sizeof(esp_gattc_descr_elem_t) * attr_count, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + esp_gattc_descr_elem_t *descr_elems = (esp_gattc_descr_elem_t *)malloc(sizeof(esp_gattc_descr_elem_t) * attr_count); if (!descr_elems) { mp_raise_OSError(MP_ENOMEM); } else { diff --git a/esp32/mods/modbt.h b/esp32/mods/modbt.h index ffb13c604c..5c04a98f18 100644 --- a/esp32/mods/modbt.h +++ b/esp32/mods/modbt.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modcoap.c b/esp32/mods/modcoap.c index 967282b242..cae166d61d 100644 --- a/esp32/mods/modcoap.c +++ b/esp32/mods/modcoap.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -11,7 +11,6 @@ #include "py/mpconfig.h" #include "py/obj.h" #include "py/runtime.h" -#include "py/gc.h" #include "coap.h" #include "coap_list.h" @@ -1235,7 +1234,7 @@ STATIC mp_obj_t mod_coap_send_request(mp_uint_t n_args, const mp_obj_t *pos_args // Split up the URI-PATH into more segments if needed //TODO: allocate the proper length size_t length = 300; - unsigned char* path = m_malloc(length); + unsigned char* path = malloc(length); int segments = coap_split_path(coap_uri.path.s, coap_uri.path.length, path, &length); // Insert the segments as separate URI-Path options @@ -1249,7 +1248,7 @@ STATIC mp_obj_t mod_coap_send_request(mp_uint_t n_args, const mp_obj_t *pos_args } - m_free(path); + free(path); // Put Content Format option if given if(content_format != -1) { diff --git a/esp32/mods/modcoap.h b/esp32/mods/modcoap.h index 1446465c4f..76a89f7190 100644 --- a/esp32/mods/modcoap.h +++ b/esp32/mods/modcoap.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modled.c b/esp32/mods/modled.c index 40b8d9ecdb..665db353c4 100644 --- a/esp32/mods/modled.c +++ b/esp32/mods/modled.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modled.h b/esp32/mods/modled.h index 56b8bdb554..7981405c1d 100644 --- a/esp32/mods/modled.h +++ b/esp32/mods/modled.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modlora.c b/esp32/mods/modlora.c index f28d88f5b4..94f742094d 100644 --- a/esp32/mods/modlora.c +++ b/esp32/mods/modlora.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -53,6 +53,7 @@ #include "lora/mac/region/RegionEU868.h" #include "lora/mac/region/RegionCN470.h" #include "lora/mac/region/RegionIN865.h" +#include "lora/mac/region/RegionEU433.h" // openThread includes #ifdef LORA_OPENTHREAD_ENABLED @@ -262,7 +263,6 @@ static const char *modlora_nvs_data_key[E_LORA_NVS_NUM_KEYS] = { "JOINED", "UPLN "MACPARAMS", "CHANNELS", "SRVACK", "MACNXTTX", "MACBUFIDX", "MACRPTIDX", "MACBUF", "MACRPTBUF", "REGION", "CHANMASK", "CHANMASKREM" }; -DRAM_ATTR static modlora_timerCallback modlora_timer_cb; /****************************************************************************** DECLARE PUBLIC DATA ******************************************************************************/ @@ -394,10 +394,16 @@ bool modlora_is_module_sleep(void) IRAM_ATTR void modlora_set_timer_callback(modlora_timerCallback cb) { - modlora_timer_cb = cb; if(cb != NULL) { - xQueueSendFromISR(xCbQueue, &cb, NULL); + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + + xQueueSendFromISR(xCbQueue, &cb, &xHigherPriorityTaskWoken); + + if( xHigherPriorityTaskWoken) + { + portYIELD_FROM_ISR(); + } } } @@ -1185,20 +1191,14 @@ static void TASK_LoRa (void *pvParameters) { static void TASK_LoRa_Timer (void *pvParameters) { - static uint32_t thread_notification; - for(;;) { - thread_notification = ulTaskNotifyTake(pdTRUE, portMAX_DELAY); - if (thread_notification) { - - modlora_timerCallback cb; - while (pdTRUE == xQueueReceive(xCbQueue, &cb, 0)) + modlora_timerCallback cb; + while (pdTRUE == xQueueReceive(xCbQueue, &cb, portMAX_DELAY)) + { + if(cb != NULL) { - if(cb != NULL) - { - cb(); - } + cb(); } } } @@ -1362,12 +1362,17 @@ static void lora_validate_frequency (uint32_t frequency) { goto freq_error; } break; - case LORAMAC_REGION_EU868: + case LORAMAC_REGION_EU433: #if defined(LOPY4) - if (frequency < 410000000 || frequency > 870000000) { + if (frequency < 433000000 || frequency > 435000000) { // LoRa 433 - 434 + goto freq_error; + } #else - if (frequency < 863000000 || frequency > 870000000) { + goto freq_error; #endif + break; + case LORAMAC_REGION_EU868: + if (frequency < 863000000 || frequency > 870000000) { goto freq_error; } break; @@ -1438,6 +1443,7 @@ static bool lora_validate_data_rate (uint32_t data_rate) { case LORAMAC_REGION_AS923: case LORAMAC_REGION_EU868: case LORAMAC_REGION_AU915: + case LORAMAC_REGION_EU433: case LORAMAC_REGION_CN470: case LORAMAC_REGION_IN865: if (data_rate > DR_6) { @@ -1490,11 +1496,16 @@ static void lora_validate_device_class (DeviceClass_t device_class) { static void lora_validate_region (LoRaMacRegion_t region) { if (region != LORAMAC_REGION_AS923 && region != LORAMAC_REGION_AU915 && region != LORAMAC_REGION_EU868 && region != LORAMAC_REGION_US915 - && region != LORAMAC_REGION_CN470 && region != LORAMAC_REGION_IN865) { + && region != LORAMAC_REGION_IN865 +#if defined(LOPY4) + && region != LORAMAC_REGION_EU433 && region != LORAMAC_REGION_CN470 +#endif + ) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "invalid region %d", region)); } } + static void lora_set_config (lora_cmd_data_t *cmd_data) { lora_obj.stack_mode = cmd_data->info.init.stack_mode; lora_obj.bandwidth = cmd_data->info.init.bandwidth; @@ -1711,6 +1722,9 @@ static mp_obj_t lora_init_helper(lora_obj_t *self, const mp_arg_val_t *args) { case LORAMAC_REGION_EU868: cmd_data.info.init.frequency = 868000000; break; + case LORAMAC_REGION_EU433: + cmd_data.info.init.frequency = 433175000; + break; case LORAMAC_REGION_CN470: cmd_data.info.init.frequency = 470000000; case LORAMAC_REGION_IN865: @@ -1736,6 +1750,9 @@ static mp_obj_t lora_init_helper(lora_obj_t *self, const mp_arg_val_t *args) { case LORAMAC_REGION_EU868: cmd_data.info.init.tx_power = 14; break; + case LORAMAC_REGION_EU433: + cmd_data.info.init.tx_power = 12; + break; default: break; } @@ -1895,6 +1912,7 @@ STATIC mp_obj_t lora_join(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t * break; case LORAMAC_REGION_CN470: case LORAMAC_REGION_EU868: + case LORAMAC_REGION_EU433: case LORAMAC_REGION_IN865: dr = DR_5; break; @@ -1926,6 +1944,7 @@ STATIC mp_obj_t lora_join(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t * goto dr_error; } break; + case LORAMAC_REGION_EU433: case LORAMAC_REGION_CN470: case LORAMAC_REGION_EU868: if (dr > DR_5) { @@ -2507,6 +2526,7 @@ STATIC const mp_map_elem_t lora_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_US915), MP_OBJ_NEW_SMALL_INT(LORAMAC_REGION_US915) }, { MP_OBJ_NEW_QSTR(MP_QSTR_CN470), MP_OBJ_NEW_SMALL_INT(LORAMAC_REGION_CN470) }, { MP_OBJ_NEW_QSTR(MP_QSTR_IN865), MP_OBJ_NEW_SMALL_INT(LORAMAC_REGION_IN865) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_EU433), MP_OBJ_NEW_SMALL_INT(LORAMAC_REGION_EU433) }, }; STATIC MP_DEFINE_CONST_DICT(lora_locals_dict, lora_locals_dict_table); @@ -2552,6 +2572,7 @@ static int lora_socket_socket (mod_network_socket_obj_t *s, int *_errno) { switch (lora_obj.region) { case LORAMAC_REGION_AS923: case LORAMAC_REGION_EU868: + case LORAMAC_REGION_EU433: case LORAMAC_REGION_CN470: dr = DR_5; break; diff --git a/esp32/mods/modlora.h b/esp32/mods/modlora.h index 2bfae486b1..e2b7b0e4ac 100644 --- a/esp32/mods/modlora.h +++ b/esp32/mods/modlora.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -144,7 +144,7 @@ typedef void ( *modlora_timerCallback )( void ); /****************************************************************************** EXPORTED DATA ******************************************************************************/ -extern TaskHandle_t xLoRaTimerTaskHndl; +extern DRAM_ATTR TaskHandle_t xLoRaTimerTaskHndl; /****************************************************************************** DECLARE FUNCTIONS ******************************************************************************/ diff --git a/esp32/mods/modlte.c b/esp32/mods/modlte.c index f05a3f4d84..d8e8db84a0 100644 --- a/esp32/mods/modlte.c +++ b/esp32/mods/modlte.c @@ -1,5 +1,5 @@ /* -* Copyright (c) 2019, Pycom Limited and its licensors. +* Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence @@ -68,6 +68,8 @@ #include "modmachine.h" #include "mpirq.h" +#include "str_utils.h" + /****************************************************************************** DEFINE TYPES ******************************************************************************/ @@ -83,6 +85,23 @@ #define SQNS_SW_FULL_BAND_SUPPORT 41000 #define SQNS_SW_5_8_BAND_SUPPORT 39000 + +// PSM Power saving mode +// PERIOD, aka Requested Periodic TAU (T3412), in GPRS Timer 3 format +#define PSM_PERIOD_2S 0b011 +#define PSM_PERIOD_30S 0b100 +#define PSM_PERIOD_1M 0b101 +#define PSM_PERIOD_10M 0b000 +#define PSM_PERIOD_1H 0b001 +#define PSM_PERIOD_10H 0b010 +#define PSM_PERIOD_320H 0b110 +#define PSM_PERIOD_DISABLED 0b111 +// ACTIVE, aka Requested Active Time (T3324), in GPRS Timer 2 format +#define PSM_ACTIVE_2S 0b000 +#define PSM_ACTIVE_1M 0b001 +#define PSM_ACTIVE_6M 0b010 +#define PSM_ACTIVE_DISABLED 0b111 + /****************************************************************************** DECLARE PRIVATE DATA ******************************************************************************/ @@ -95,6 +114,7 @@ uart_config_t lte_uart_config0; uart_config_t lte_uart_config1; static bool lte_legacyattach_flag = true; +static bool lte_debug = false; static bool lte_ue_is_out_of_coverage = false; @@ -175,13 +195,17 @@ static void lte_callback_handler(void* arg) static bool lte_push_at_command_ext(char *cmd_str, uint32_t timeout, const char *expected_rsp, size_t len) { lte_task_cmd_data_t cmd = { .timeout = timeout, .dataLen = len}; memcpy(cmd.data, cmd_str, len); - //printf("[CMD] %s\n", cmd_str); + uint32_t start = mp_hal_ticks_ms(); + if (lte_debug) + printf("[AT] %u %s\n", start, cmd_str); lteppp_send_at_command(&cmd, &modlte_rsp); if ((expected_rsp == NULL) || (strstr(modlte_rsp.data, expected_rsp) != NULL)) { - //printf("[OK] %s\n", modlte_rsp.data); + if (lte_debug) + printf("[AT-OK] +%u %s\n", mp_hal_ticks_ms()-start, modlte_rsp.data); return true; } - //printf("[FAIL] %s\n", modlte_rsp.data); + if (lte_debug) + printf("[AT-FAIL] +%u %s\n", mp_hal_ticks_ms()-start, modlte_rsp.data); return false; } @@ -404,7 +428,8 @@ static void TASK_LTE_UPGRADE(void *pvParameters){ // Micro Python bindings; LTE class static mp_obj_t lte_init_helper(lte_obj_t *self, const mp_arg_val_t *args) { - char at_cmd[LTE_AT_CMD_SIZE_MAX - 4]; + const size_t at_cmd_len = LTE_AT_CMD_SIZE_MAX - 4; + char at_cmd[at_cmd_len]; lte_modem_conn_state_t modem_state; if (lte_obj.init) { @@ -422,7 +447,7 @@ static mp_obj_t lte_init_helper(lte_obj_t *self, const mp_arg_val_t *args) { MP_THREAD_GIL_ENTER(); if (E_LTE_MODEM_DISCONNECTED == lteppp_modem_state()) { xSemaphoreGive(xLTE_modem_Conn_Sem); - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Couldn't connect to Modem!")); + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Couldn't connect to Modem (modem_state=disconnected)")); } break; case E_LTE_MODEM_CONNECTING: @@ -430,16 +455,15 @@ static mp_obj_t lte_init_helper(lte_obj_t *self, const mp_arg_val_t *args) { xSemaphoreTake(xLTE_modem_Conn_Sem, portMAX_DELAY); if (E_LTE_MODEM_DISCONNECTED == lteppp_modem_state()) { xSemaphoreGive(xLTE_modem_Conn_Sem); - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Couldn't connect to Modem!")); + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Couldn't connect to Modem (modem_state=connecting)")); } break; case E_LTE_MODEM_CONNECTED: //continue break; default: - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Couldn't connect to Modem!")); + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Couldn't connect to Modem (modem_state=default)")); break; - } lte_obj.cid = args[1].u_int; @@ -486,15 +510,102 @@ static mp_obj_t lte_init_helper(lte_obj_t *self, const mp_arg_val_t *args) { lteppp_set_state(E_LTE_IDLE); mod_network_register_nic(<e_obj); lte_obj.init = true; + + // configure PSM + u8_t psm_period_value = args[4].u_int; + u8_t psm_period_unit = args[5].u_int; + u8_t psm_active_value = args[6].u_int; + u8_t psm_active_unit = args[7].u_int; + if ( psm_period_unit != PSM_PERIOD_DISABLED && psm_active_unit != PSM_ACTIVE_DISABLED ) { + u8_t psm_period = ( psm_period_unit << 5 ) | psm_period_value; + u8_t psm_active = ( psm_active_unit << 5 ) | psm_active_value; + char p[9]; + char a[9]; + sprint_binary_u8(p, psm_period); + sprint_binary_u8(a, psm_active); + snprintf(at_cmd, at_cmd_len, "AT+CPSMS=1,,,\"%s\",\"%s\"", p, a); + lte_push_at_command(at_cmd, LTE_RX_TIMEOUT_MAX_MS); + } + xSemaphoreGive(xLTE_modem_Conn_Sem); return mp_const_none; } +STATIC mp_obj_t lte_psm(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + lte_check_init(); + lte_check_inppp(); + mp_obj_t tuple[5]; + static const qstr psm_info_fields[] = { + MP_QSTR_enabled, + MP_QSTR_period_value, + MP_QSTR_period_unit, + MP_QSTR_active_value, + MP_QSTR_active_unit, + }; + + lte_push_at_command("AT+CPSMS?", LTE_RX_TIMEOUT_MAX_MS); + const char *resp = modlte_rsp.data; + char *pos; + if ( ( pos = strstr(resp, "+CPSMS: ") ) ) { + // decode the resp: + // +CPSMS: ,[],[],[],[] + + // go to + pos += strlen_const("+CPSMS: "); + tuple[0] = mp_obj_new_bool(*pos == '1'); + + // go to + pos += strlen_const("1,"); + + // find + pos = strstr(pos, ","); + pos++; + + // find + pos = strstr(pos, ","); + pos++; // , + pos++; // " + + // get three digit TAU unit + char* oldpos = pos; + tuple[2] = mp_obj_new_int_from_str_len( (const char**) &pos, 3, false, 2); + assert( pos == oldpos + 3); // mp_obj_new_int_from_str_len is supposed to consume exactly 3 characters + + // get five digit TAU value + tuple[1] = mp_obj_new_int_from_str_len( (const char**) &pos, 5, false, 2); + + // find + pos = strstr(pos, ","); + pos++; // , + pos++; // " + + // get three digit ActiveTime unit + oldpos = pos; + tuple[4] = mp_obj_new_int_from_str_len( (const char**) &pos, 3, false, 2); + assert( pos == oldpos + 3); // mp_obj_new_int_from_str_len is supposed to consume exactly 3 characters + + // get five digit ActiveTime value + tuple[3] = mp_obj_new_int_from_str_len( (const char**) &pos, 5, false, 2); + + } else { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Failed to read PSM setting")); + } + + return mp_obj_new_attrtuple(psm_info_fields, 5, tuple); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(lte_psm_obj, 1, lte_psm); + + static const mp_arg_t lte_init_args[] = { { MP_QSTR_id, MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_carrier, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_cid, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, - { MP_QSTR_legacyattach, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} } + { MP_QSTR_legacyattach, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_debug, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_psm_period_value, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0 } }, + { MP_QSTR_psm_period_unit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = PSM_PERIOD_DISABLED } }, + { MP_QSTR_psm_active_value, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0 } }, + { MP_QSTR_psm_active_unit, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = PSM_ACTIVE_DISABLED } }, }; static mp_obj_t lte_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *all_args) { @@ -504,6 +615,8 @@ static mp_obj_t lte_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uin // parse args mp_arg_val_t args[MP_ARRAY_SIZE(lte_init_args)]; mp_arg_parse_all(n_args, all_args, &kw_args, MP_ARRAY_SIZE(args), lte_init_args, args); + if (args[4].u_bool) + lte_debug = true; // setup the object lte_obj_t *self = <e_obj; @@ -515,6 +628,30 @@ static mp_obj_t lte_make_new(const mp_obj_type_t *type, mp_uint_t n_args, mp_uin nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_resource_not_avaliable)); } } + + // check psm args + u8_t psm_period_value = args[5].u_int; + u8_t psm_period_unit = args[6].u_int; + u8_t psm_active_value = args[7].u_int; + u8_t psm_active_unit = args[8].u_int; + if (psm_period_unit > 7) + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Invalid psm_period_unit")); + if (psm_period_value > 31) + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Invalid psm_period_value")); + switch(psm_active_unit){ + case PSM_ACTIVE_2S: + case PSM_ACTIVE_1M: + case PSM_ACTIVE_6M: + case PSM_ACTIVE_DISABLED: + // ok, nothing to do + break; + default: + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Invalid psm_active_unit")); + break; + } + if (psm_active_value > 31) + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "Invalid psm_active_value")); + // start the peripheral lte_init_helper(self, &args[1]); return (mp_obj_t)self; @@ -524,6 +661,7 @@ STATIC mp_obj_t lte_init(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *k // parse args mp_arg_val_t args[MP_ARRAY_SIZE(lte_init_args) - 1]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(args), <e_init_args[1], args); + lte_debug = args[3].u_bool; return lte_init_helper(pos_args[0], args); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(lte_init_obj, 1, lte_init); @@ -612,6 +750,84 @@ STATIC mp_obj_t lte_deinit(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(lte_deinit_obj, 1, lte_deinit); +STATIC void lte_add_band(uint32_t band, bool is_hw_new_band_support, bool is_sw_new_band_support, int version) +{ + /* Check band support */ + switch(band) + { + case 5: + case 8: + if (!is_hw_new_band_support) + { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by this board hardware!", band)); + } + else if(version < SQNS_SW_5_8_BAND_SUPPORT) + { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by current modem Firmware [%d], please upgrade!", band, version)); + } + break; + case 1: + case 2: + case 14: + case 17: + case 18: + case 19: + case 25: + case 26: + case 66: + if(!is_sw_new_band_support) + { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by current modem Firmware [%d], please upgrade!", band, version)); + } + if (!is_hw_new_band_support) + { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by this board hardware!", band)); + } + break; + default: + break; + } + + if (band == 1) { + lte_push_at_command("AT!=\"RRC::addScanBand band=1\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 2) { + lte_push_at_command("AT!=\"RRC::addScanBand band=2\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 3) { + lte_push_at_command("AT!=\"RRC::addScanBand band=3\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 4) { + lte_push_at_command("AT!=\"RRC::addScanBand band=4\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 5) { + lte_push_at_command("AT!=\"RRC::addScanBand band=5\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 8) { + lte_push_at_command("AT!=\"RRC::addScanBand band=8\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 12) { + lte_push_at_command("AT!=\"RRC::addScanBand band=12\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 13) { + lte_push_at_command("AT!=\"RRC::addScanBand band=13\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 14) { + lte_push_at_command("AT!=\"RRC::addScanBand band=14\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 17) { + lte_push_at_command("AT!=\"RRC::addScanBand band=17\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 18) { + lte_push_at_command("AT!=\"RRC::addScanBand band=18\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 19) { + lte_push_at_command("AT!=\"RRC::addScanBand band=19\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 20) { + lte_push_at_command("AT!=\"RRC::addScanBand band=20\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 25) { + lte_push_at_command("AT!=\"RRC::addScanBand band=25\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 26) { + lte_push_at_command("AT!=\"RRC::addScanBand band=26\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 28) { + lte_push_at_command("AT!=\"RRC::addScanBand band=28\"", LTE_RX_TIMEOUT_MIN_MS); + } else if (band == 66) { + lte_push_at_command("AT!=\"RRC::addScanBand band=66\"", LTE_RX_TIMEOUT_MIN_MS); + } else { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported", band)); + } +} + + STATIC mp_obj_t lte_attach(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { lte_check_init(); bool is_hw_new_band_support = false; @@ -623,7 +839,7 @@ STATIC mp_obj_t lte_attach(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t { MP_QSTR_cid, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_obj = mp_const_none} }, { MP_QSTR_type, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_legacyattach, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, - + { MP_QSTR_bands, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, }; // parse args @@ -675,7 +891,8 @@ STATIC mp_obj_t lte_attach(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t // Delay to ensure next addScan command is not discarded vTaskDelay(1000); - if (args[0].u_obj == mp_const_none) { + if (args[0].u_obj == mp_const_none && args[6].u_obj == mp_const_none) { + // neither the argument 'band', nor 'bands' was supplied lte_push_at_command("AT!=\"RRC::addScanBand band=3\"", LTE_RX_TIMEOUT_MIN_MS); lte_push_at_command("AT!=\"RRC::addScanBand band=4\"", LTE_RX_TIMEOUT_MIN_MS); if (is_hw_new_band_support && version > SQNS_SW_5_8_BAND_SUPPORT) { @@ -689,78 +906,21 @@ STATIC mp_obj_t lte_attach(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t } else { - uint32_t band = mp_obj_get_int(args[0].u_obj); - /* Check band support */ - switch(band) - { - case 5: - case 8: - if (!is_hw_new_band_support) - { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by this board hardware!", band)); - } - else if(version < SQNS_SW_5_8_BAND_SUPPORT) - { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by current modem Firmware [%d], please upgrade!", band, version)); - } - break; - case 1: - case 2: - case 14: - case 17: - case 18: - case 19: - case 25: - case 26: - case 66: - if(!is_sw_new_band_support) - { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by current modem Firmware [%d], please upgrade!", band, version)); - } - if (!is_hw_new_band_support) - { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported by this board hardware!", band)); - } - break; - default: - break; + if (args[0].u_obj != mp_const_none) { + // argument 'band' + lte_add_band(mp_obj_get_int(args[0].u_obj), is_hw_new_band_support, is_sw_new_band_support, version); } - if (band == 1) { - lte_push_at_command("AT!=\"RRC::addScanBand band=1\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 2) { - lte_push_at_command("AT!=\"RRC::addScanBand band=2\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 3) { - lte_push_at_command("AT!=\"RRC::addScanBand band=3\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 4) { - lte_push_at_command("AT!=\"RRC::addScanBand band=4\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 5) { - lte_push_at_command("AT!=\"RRC::addScanBand band=5\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 8) { - lte_push_at_command("AT!=\"RRC::addScanBand band=8\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 12) { - lte_push_at_command("AT!=\"RRC::addScanBand band=12\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 13) { - lte_push_at_command("AT!=\"RRC::addScanBand band=13\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 14) { - lte_push_at_command("AT!=\"RRC::addScanBand band=14\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 17) { - lte_push_at_command("AT!=\"RRC::addScanBand band=17\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 18) { - lte_push_at_command("AT!=\"RRC::addScanBand band=18\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 19) { - lte_push_at_command("AT!=\"RRC::addScanBand band=19\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 20) { - lte_push_at_command("AT!=\"RRC::addScanBand band=20\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 25) { - lte_push_at_command("AT!=\"RRC::addScanBand band=25\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 26) { - lte_push_at_command("AT!=\"RRC::addScanBand band=26\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 28) { - lte_push_at_command("AT!=\"RRC::addScanBand band=28\"", LTE_RX_TIMEOUT_MIN_MS); - } else if (band == 66) { - lte_push_at_command("AT!=\"RRC::addScanBand band=66\"", LTE_RX_TIMEOUT_MIN_MS); - } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "band %d not supported", band)); + + if (args[6].u_obj != mp_const_none){ + // argument 'bands' + mp_obj_t *bands; + size_t n_bands=0; + mp_obj_get_array(args[6].u_obj, &n_bands, &bands); + + for (size_t b = 0 ; b < n_bands ; ++b ) + { + lte_add_band(mp_obj_get_int(bands[b]), is_hw_new_band_support, is_sw_new_band_support, version); + } } } } else { @@ -1027,12 +1187,12 @@ STATIC mp_obj_t lte_disconnect(mp_obj_t self_in) { lte_pause_ppp(); } lteppp_set_state(E_LTE_ATTACHED); - lte_push_at_command("ATH", LTE_RX_TIMEOUT_MIN_MS); + lte_push_at_command("ATH", LTE_RX_TIMEOUT_MAX_MS); while (true) { - mp_hal_delay_ms(LTE_RX_TIMEOUT_MIN_MS); if (lte_push_at_command("AT", LTE_RX_TIMEOUT_MAX_MS)) { break; } + mp_hal_delay_ms(LTE_RX_TIMEOUT_MIN_MS); } lte_check_attached(lte_legacyattach_flag); mod_network_deregister_nic(<e_obj); @@ -1090,13 +1250,11 @@ STATIC mp_obj_t lte_send_at_cmd(mp_uint_t n_args, const mp_obj_t *pos_args, mp_m vstr_t vstr; vstr_init(&vstr, 0); vstr_add_str(&vstr, modlte_rsp.data); - MP_THREAD_GIL_EXIT(); while(modlte_rsp.data_remaining) { lte_push_at_command_ext("Pycom_Dummy", LTE_RX_TIMEOUT_MAX_MS, NULL, strlen("Pycom_Dummy") ); vstr_add_str(&vstr, modlte_rsp.data); } - MP_THREAD_GIL_ENTER(); return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(lte_send_at_cmd_obj, 1, lte_send_at_cmd); @@ -1383,6 +1541,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(lte_events_obj, lte_events); STATIC const mp_map_elem_t lte_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_init), (mp_obj_t)<e_init_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_deinit), (mp_obj_t)<e_deinit_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_psm), (mp_obj_t)<e_psm_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_attach), (mp_obj_t)<e_attach_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_dettach), (mp_obj_t)<e_detach_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_detach), (mp_obj_t)<e_detach_obj }, /* backward compatibility for dettach method FIXME */ @@ -1411,6 +1570,20 @@ STATIC const mp_map_elem_t lte_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_IP), MP_OBJ_NEW_QSTR(MP_QSTR_IP) }, { MP_OBJ_NEW_QSTR(MP_QSTR_IPV4V6), MP_OBJ_NEW_QSTR(MP_QSTR_IPV4V6) }, { MP_OBJ_NEW_QSTR(MP_QSTR_EVENT_COVERAGE_LOSS), MP_OBJ_NEW_SMALL_INT(LTE_TRIGGER_SIG_LOST) }, + // PSM Power Saving Mode + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_2S), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_2S) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_30S), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_30S) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_1M), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_1M) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_10M), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_10M) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_1H), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_1H) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_10H), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_10H) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_320H), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_320H) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_PERIOD_DISABLED), MP_OBJ_NEW_SMALL_INT(PSM_PERIOD_DISABLED) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_ACTIVE_2S), MP_OBJ_NEW_SMALL_INT(PSM_ACTIVE_2S) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_ACTIVE_1M), MP_OBJ_NEW_SMALL_INT(PSM_ACTIVE_1M) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_ACTIVE_6M), MP_OBJ_NEW_SMALL_INT(PSM_ACTIVE_6M) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_PSM_ACTIVE_DISABLED), MP_OBJ_NEW_SMALL_INT(PSM_ACTIVE_DISABLED) }, + }; STATIC MP_DEFINE_CONST_DICT(lte_locals_dict, lte_locals_dict_table); diff --git a/esp32/mods/modlte.h b/esp32/mods/modlte.h index 8a71982803..f38439babe 100644 --- a/esp32/mods/modlte.h +++ b/esp32/mods/modlte.h @@ -1,5 +1,5 @@ /* -* Copyright (c) 2019, Pycom Limited and its licensors. +* Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modmachine.c b/esp32/mods/modmachine.c index f855570cdb..7bbaa76338 100644 --- a/esp32/mods/modmachine.c +++ b/esp32/mods/modmachine.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modmachine.h b/esp32/mods/modmachine.h index 82e20b2749..2e534898e0 100644 --- a/esp32/mods/modmachine.h +++ b/esp32/mods/modmachine.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modmdns.c b/esp32/mods/modmdns.c index de9ae5324e..bb0814d220 100644 --- a/esp32/mods/modmdns.c +++ b/esp32/mods/modmdns.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -168,7 +168,7 @@ STATIC mp_obj_t mod_mdns_add_service(mp_uint_t n_args, const mp_obj_t *pos_args, mp_obj_t* items; mp_obj_tuple_get(args[3].u_obj, &length_total, &items); - service_txt = m_malloc(length_total * sizeof(mdns_txt_item_t)); + service_txt = malloc(length_total * sizeof(mdns_txt_item_t)); for(int i = 0; i < length_total; i++) { size_t length_elem = 0; @@ -186,6 +186,7 @@ STATIC mp_obj_t mod_mdns_add_service(mp_uint_t n_args, const mp_obj_t *pos_args, } esp_err_t ret = mdns_service_add(NULL, service_type, proto, port, service_txt, length_total); + free(service_txt); if(ret != ESP_OK) { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_RuntimeError, "Service could not be added, error code: %d", ret)); } @@ -295,7 +296,13 @@ STATIC mp_obj_t mod_mdns_query(mp_uint_t n_args, const mp_obj_t *pos_args, mp_ma tuple[1] = mp_obj_new_str(result->txt[i].value, strlen(result->txt[i].value)); mp_obj_list_append(query_obj->txt, mp_obj_new_tuple(2, tuple)); } - query_obj->addr = netutils_format_ipv4_addr((uint8_t *)&result->addr->addr.u_addr.ip4.addr, NETUTILS_BIG); + + if (result->addr) { + query_obj->addr = netutils_format_ipv4_addr((uint8_t *)&result->addr->addr.u_addr.ip4.addr, NETUTILS_BIG); + } else { + u32_t zero_ip = 0; + query_obj->addr = netutils_format_ipv4_addr((uint8_t *)&zero_ip, NETUTILS_BIG); + } mp_obj_list_append(queries_list, query_obj); diff --git a/esp32/mods/modmdns.h b/esp32/mods/modmdns.h index 1c4b7ec780..cb3a095868 100644 --- a/esp32/mods/modmdns.h +++ b/esp32/mods/modmdns.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modmesh.c b/esp32/mods/modmesh.c index 1dcc020d73..0e2a67aa9e 100644 --- a/esp32/mods/modmesh.c +++ b/esp32/mods/modmesh.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modmesh.h b/esp32/mods/modmesh.h index 1ca57d4454..5460e00528 100644 --- a/esp32/mods/modmesh.h +++ b/esp32/mods/modmesh.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modnetwork.c b/esp32/mods/modnetwork.c index c55d6ed5ee..55a8594d56 100644 --- a/esp32/mods/modnetwork.c +++ b/esp32/mods/modnetwork.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modnetwork.h b/esp32/mods/modnetwork.h index db31881b42..97aee48580 100644 --- a/esp32/mods/modnetwork.h +++ b/esp32/mods/modnetwork.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modpycom.c b/esp32/mods/modpycom.c index 7b1f976659..c56d47c05b 100644 --- a/esp32/mods/modpycom.c +++ b/esp32/mods/modpycom.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -302,16 +302,15 @@ STATIC mp_obj_t mod_pycom_nvs_get (mp_uint_t n_args, const mp_obj_t *args) { else { esp_err = nvs_get_str(pycom_nvs_handle, key, NULL, &value); if(esp_err == ESP_OK) { - char* value_string = (char*)m_malloc(value); + char* value_string = (char*)malloc(value); esp_err = nvs_get_str(pycom_nvs_handle, key, value_string, &value); if(esp_err == ESP_OK) { //do not count the terminating \0 ret = mp_obj_new_str(value_string, value-1); - m_free(value_string); } - m_free(value_string); + free(value_string); } } @@ -422,7 +421,7 @@ STATIC mp_obj_t mod_pycom_wifi_ssid_sta (mp_uint_t n_args, const mp_obj_t *args) else{/*Nothing*/} } else { - uint8_t * ssid = (uint8_t *)m_malloc(33); + uint8_t * ssid = (uint8_t *)malloc(33); mp_obj_t ssid_obj; if(config_get_wifi_sta_ssid(ssid)) { @@ -432,7 +431,7 @@ STATIC mp_obj_t mod_pycom_wifi_ssid_sta (mp_uint_t n_args, const mp_obj_t *args) { ssid_obj = mp_const_none; } - m_free(ssid); + free(ssid); return ssid_obj; } return mp_const_none; @@ -451,7 +450,7 @@ STATIC mp_obj_t mod_pycom_wifi_pwd_sta (mp_uint_t n_args, const mp_obj_t *args) } else{/*Nothing*/} } else { - uint8_t * pwd = (uint8_t *)m_malloc(65); + uint8_t * pwd = (uint8_t *)malloc(65); mp_obj_t pwd_obj; if(config_get_wifi_sta_pwd(pwd)) { @@ -461,7 +460,7 @@ STATIC mp_obj_t mod_pycom_wifi_pwd_sta (mp_uint_t n_args, const mp_obj_t *args) { pwd_obj = mp_const_none; } - m_free(pwd); + free(pwd); return pwd_obj; } return mp_const_none; @@ -480,7 +479,7 @@ STATIC mp_obj_t mod_pycom_wifi_ssid_ap (mp_uint_t n_args, const mp_obj_t *args) } else{/*Nothing*/} } else { - uint8_t * ssid = (uint8_t *)m_malloc(33); + uint8_t * ssid = (uint8_t *)malloc(33); mp_obj_t ssid_obj; if(config_get_wifi_ap_ssid(ssid)) { @@ -490,7 +489,7 @@ STATIC mp_obj_t mod_pycom_wifi_ssid_ap (mp_uint_t n_args, const mp_obj_t *args) { ssid_obj = mp_const_none; } - m_free(ssid); + free(ssid); return ssid_obj; } return mp_const_none; @@ -509,7 +508,7 @@ STATIC mp_obj_t mod_pycom_wifi_pwd_ap (mp_uint_t n_args, const mp_obj_t *args) { } else{/*Nothing*/} } else { - uint8_t * pwd = (uint8_t *)m_malloc(65); + uint8_t * pwd = (uint8_t *)malloc(65); mp_obj_t pwd_obj; if(config_get_wifi_ap_pwd(pwd)) { @@ -519,7 +518,7 @@ STATIC mp_obj_t mod_pycom_wifi_pwd_ap (mp_uint_t n_args, const mp_obj_t *args) { { pwd_obj = mp_const_none; } - m_free(pwd); + free(pwd); return pwd_obj; } return mp_const_none; @@ -571,6 +570,17 @@ STATIC mp_obj_t mod_pycom_lte_modem_on_boot (mp_uint_t n_args, const mp_obj_t *a } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_pycom_lte_modem_on_boot_obj, 0, 1, mod_pycom_lte_modem_on_boot); +STATIC mp_obj_t mod_pycom_pybytes_on_boot (mp_uint_t n_args, const mp_obj_t *args) { + if (n_args) { + config_set_pybytes_autostart (mp_obj_is_true(args[0])); + } else { + return mp_obj_new_bool(config_get_pybytes_autostart()); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_pycom_pybytes_on_boot_obj, 0, 1, mod_pycom_pybytes_on_boot); + + STATIC mp_obj_t mod_pycom_pybytes_lte_config (size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_carrier, ARG_apn, ARG_cid, ARG_band, ARG_type, ARG_reset }; STATIC const mp_arg_t allowed_args[] = { @@ -839,17 +849,16 @@ STATIC mp_obj_t mod_pycom_sigfox_info (size_t n_args, const mp_obj_t *pos_args, if (args[ARG_id].u_obj == mp_const_none && args[ARG_pac].u_obj == mp_const_none && args[ARG_public_key].u_obj == mp_const_none && args[ARG_private_key].u_obj == mp_const_none) { + // query sigfox info - mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); - - t->items[ARG_id] = is_empty(id, sizeof(id)) ? mp_const_none:mp_obj_new_str((const char*)id, sizeof(id)); - t->items[ARG_pac] = is_empty(pac, sizeof(pac)) ? mp_const_none:mp_obj_new_str((const char*)pac, sizeof(pac)); - t->items[ARG_public_key] = is_empty(public_key, sizeof(public_key)) ? mp_const_none:mp_obj_new_str((const char*)public_key, sizeof(public_key)); - t->items[ARG_private_key] = is_empty(private_key, sizeof(private_key)) ? mp_const_none:mp_obj_new_str((const char*)private_key, sizeof(private_key)); - - return MP_OBJ_FROM_PTR(t); - + if ( !is_empty(id, sizeof(id)) && !is_empty(pac, sizeof(pac)) && !is_empty(public_key, sizeof(public_key)) && !is_empty(private_key, sizeof(private_key)) ){ + // all configs valid + return mp_const_true; + } else { + return mp_const_false; + } } else { + // write sigfox info // temporary array to store even the longest value from id, pac, public_key and private_key uint8_t tmp_array[16]; @@ -881,7 +890,7 @@ STATIC mp_obj_t mod_pycom_sigfox_info (size_t n_args, const mp_obj_t *pos_args, ret_val = config_set_sigfox_id(tmp_array); if (ret_val == false) { - return mp_const_false; + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Failed to write id")); } } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Use force option to overwrite existing id!")); @@ -912,7 +921,7 @@ STATIC mp_obj_t mod_pycom_sigfox_info (size_t n_args, const mp_obj_t *pos_args, ret_val = config_set_sigfox_pac(tmp_array); if (ret_val == false) { - return mp_const_false; + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Failed to write pac")); } } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Use force option to overwrite existing pac!")); @@ -943,7 +952,7 @@ STATIC mp_obj_t mod_pycom_sigfox_info (size_t n_args, const mp_obj_t *pos_args, ret_val = config_set_sigfox_public_key(tmp_array); if (ret_val == false) { - return mp_const_false; + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Failed to write public key")); } } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Use force option to overwrite existing public key!")); @@ -975,7 +984,7 @@ STATIC mp_obj_t mod_pycom_sigfox_info (size_t n_args, const mp_obj_t *pos_args, ret_val = config_set_sigfox_private_key(tmp_array); if (ret_val == false) { - return mp_const_false; + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Failed to write private key")); } } else { nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Use force option to overwrite existing private key!")); @@ -983,7 +992,6 @@ STATIC mp_obj_t mod_pycom_sigfox_info (size_t n_args, const mp_obj_t *pos_args, } return mp_const_true; } - return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_pycom_sigfox_info_obj, 0, mod_pycom_sigfox_info); @@ -1026,6 +1034,8 @@ STATIC const mp_map_elem_t pycom_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_pybytes_force_update), (mp_obj_t)&mod_pycom_pybytes_force_update_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_smart_config_on_boot), (mp_obj_t)&mod_pycom_smartConfig_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_pybytes_lte_config), (mp_obj_t)&mod_pycom_pybytes_lte_config_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_pybytes_on_boot), (mp_obj_t)&mod_pycom_pybytes_on_boot_obj }, + #endif //(VARIANT == PYBYTES) { MP_OBJ_NEW_QSTR(MP_QSTR_bootmgr), (mp_obj_t)&mod_pycom_bootmgr_obj }, diff --git a/esp32/mods/modsigfox_api.c b/esp32/mods/modsigfox_api.c index 306adcf43f..0041b258ed 100644 --- a/esp32/mods/modsigfox_api.c +++ b/esp32/mods/modsigfox_api.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/moducrypto.c b/esp32/mods/moducrypto.c index 49278e7a56..f6340b8998 100644 --- a/esp32/mods/moducrypto.c +++ b/esp32/mods/moducrypto.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -324,7 +324,7 @@ STATIC mp_obj_t mod_crypt_generate_rsa_signature(mp_uint_t n_args, const mp_obj_ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_RuntimeError, "Message Digest operation failed, error code: %d", rc)); } - unsigned char *signature = m_malloc(5000); + unsigned char *signature = malloc(5000); size_t signature_length; rc = mbedtls_pk_sign(&pk_context, MBEDTLS_MD_SHA256, digest, sizeof(digest), signature, &signature_length, mbedtls_ctr_drbg_random, &ctr_drbg); @@ -335,7 +335,7 @@ STATIC mp_obj_t mod_crypt_generate_rsa_signature(mp_uint_t n_args, const mp_obj_ mp_obj_t ret_signature = mp_obj_new_bytes((const byte*)signature, signature_length); mbedtls_pk_free(&pk_context); - m_free((char*)signature); + free((char*)signature); return ret_signature; } @@ -382,7 +382,7 @@ STATIC mp_obj_t mod_crypt_rsa_encrypt(mp_uint_t n_args, const mp_obj_t *pos_args strlen(pers)); size_t output_len = message.len + 256; - unsigned char *output = m_malloc(output_len); + unsigned char *output = malloc(output_len); size_t output_actual_length = 0; rc = mbedtls_pk_encrypt(&pk_context, @@ -401,7 +401,7 @@ STATIC mp_obj_t mod_crypt_rsa_encrypt(mp_uint_t n_args, const mp_obj_t *pos_args mp_obj_t ret_output = mp_obj_new_bytes((const byte*)output, output_actual_length); mbedtls_pk_free(&pk_context); - m_free((char*)output); + free((char*)output); return ret_output; } @@ -448,7 +448,7 @@ STATIC mp_obj_t mod_crypt_rsa_decrypt(mp_uint_t n_args, const mp_obj_t *pos_args strlen(pers)); size_t output_len = message.len + 256; - unsigned char *output = m_malloc(output_len); + unsigned char *output = malloc(output_len); size_t output_actual_length = 0; rc = mbedtls_pk_decrypt(&pk_context, @@ -467,7 +467,7 @@ STATIC mp_obj_t mod_crypt_rsa_decrypt(mp_uint_t n_args, const mp_obj_t *pos_args mp_obj_t ret_output = mp_obj_new_bytes((const byte*)output, output_actual_length); mbedtls_pk_free(&pk_context); - m_free((char*)output); + free((char*)output); return ret_output; } diff --git a/esp32/mods/moduhashlib.c b/esp32/mods/moduhashlib.c index 5ac7fad477..3652676181 100644 --- a/esp32/mods/moduhashlib.c +++ b/esp32/mods/moduhashlib.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/moduos.c b/esp32/mods/moduos.c index 99bb22ad51..a0f1e6769a 100644 --- a/esp32/mods/moduos.c +++ b/esp32/mods/moduos.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/moduos.h b/esp32/mods/moduos.h index f773be75a4..c91eadf406 100644 --- a/esp32/mods/moduos.h +++ b/esp32/mods/moduos.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/moduqueue.c b/esp32/mods/moduqueue.c index 33295778f4..0a5aa10bdd 100644 --- a/esp32/mods/moduqueue.c +++ b/esp32/mods/moduqueue.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -45,7 +45,7 @@ STATIC mp_obj_t mod_uqueue_queue(mp_uint_t n_args, const mp_obj_t *pos_args, mp_ mp_obj_queue_t *queue = m_new_obj_with_finaliser(mp_obj_queue_t); // allocate the queue storage and the queue buffer - queue->buffer = heap_caps_malloc(sizeof(StaticQueue_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + queue->buffer = malloc(sizeof(StaticQueue_t)); if (NULL == queue->buffer) { nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError, "no memory available to create the queue")); } diff --git a/esp32/mods/moduqueue.h b/esp32/mods/moduqueue.h index 38d4edebc2..bdefb02da5 100644 --- a/esp32/mods/moduqueue.h +++ b/esp32/mods/moduqueue.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/modusocket.c b/esp32/mods/modusocket.c index 4362e95b17..afb5daaee2 100644 --- a/esp32/mods/modusocket.c +++ b/esp32/mods/modusocket.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modusocket.h b/esp32/mods/modusocket.h index 22e9209d17..e1a2b5e3d8 100644 --- a/esp32/mods/modusocket.h +++ b/esp32/mods/modusocket.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modussl.c b/esp32/mods/modussl.c index fa2c2d62d8..9e1dbe9a02 100644 --- a/esp32/mods/modussl.c +++ b/esp32/mods/modussl.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -27,26 +27,39 @@ #include "modusocket.h" #include "modussl.h" #include "mptask.h" +#include "pycom_general_util.h" -#include "ff.h" -#include "lfs.h" -#include "extmod/vfs.h" - -#include "mptask.h" /****************************************************************************** DEFINE CONSTANTS ******************************************************************************/ -#define FILE_READ_SIZE 256 #define DEFAULT_SSL_READ_TIMEOUT 10 //sec /****************************************************************************** DECLARE PRIVATE FUNCTIONS ******************************************************************************/ -static char *mod_ssl_read_file (const char *file_path, vstr_t *vstr); /****************************************************************************** DECLARE PRIVATE DATA ******************************************************************************/ +// tiny object for storing ssl sessions +STATIC mp_obj_t ssl_session_free(mp_obj_t self_in) { + mp_obj_ssl_session_t *self = self_in; + mbedtls_ssl_session_free(&self->saved_session); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(ssl_session_free_obj, ssl_session_free); + +STATIC const mp_map_elem_t ssl_session_locals_dict_table[] = { + { MP_OBJ_NEW_QSTR(MP_QSTR___del__), (mp_obj_t)&ssl_session_free_obj }, +}; +STATIC MP_DEFINE_CONST_DICT(ssl_session_locals_dict, ssl_session_locals_dict_table); + +static const mp_obj_type_t mod_ssl_session_type = { + { &mp_type_type }, + .name = MP_QSTR_SSLSession, + .locals_dict = (mp_obj_t)&ssl_session_locals_dict, +}; + // ssl sockets inherit from normal socket, so we take its // locals and stream methods STATIC const mp_obj_type_t ssl_socket_type = { @@ -58,9 +71,9 @@ STATIC const mp_obj_type_t ssl_socket_type = { .locals_dict = (mp_obj_t)&socket_locals_dict, }; -static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const char *host_name, - const char *ca_cert_path, const char *client_cert_path, - const char *key_path, uint32_t ssl_verify, uint32_t client_or_server) { +static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const mbedtls_ssl_session *saved_session, const char *host_name, + const char *ca_cert, const char *client_cert, const char *client_key, + uint32_t ssl_verify, uint32_t client_or_server) { int32_t ret; mbedtls_ssl_init(&ssl_sock->ssl); @@ -76,42 +89,29 @@ static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const char * return ret; } - if (ca_cert_path) { - const char *ca_cert = mod_ssl_read_file(ca_cert_path, &ssl_sock->vstr_ca); - if (ca_cert) { - // printf("Loading the CA root certificate...\n"); - ret = mbedtls_x509_crt_parse(&ssl_sock->cacert, (uint8_t *)ca_cert, strlen(ca_cert) + 1); - if (ret < 0) { - // printf("mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); - return ret; - } - } else { - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "CA file not found")); + if (ca_cert) { + // printf("Loading the CA root certificate...\n"); + ret = mbedtls_x509_crt_parse(&ssl_sock->cacert, (uint8_t *)ca_cert, strlen(ca_cert) + 1); + if (ret < 0) { + // printf("mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); + return ret; } } - if (client_cert_path && key_path) { - const char *client_cert = mod_ssl_read_file(client_cert_path, &ssl_sock->vstr_cert); - if (client_cert) { - // printf("Loading the own certificate...\n"); - ret = mbedtls_x509_crt_parse(&ssl_sock->own_cert, (uint8_t *)client_cert, strlen(client_cert) + 1); - if (ret < 0) { - // printf("mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); - return ret; - } - } else { - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "certificate file not found")); + if (client_cert) { + // printf("Loading the own certificate...\n"); + ret = mbedtls_x509_crt_parse(&ssl_sock->own_cert, (uint8_t *)client_cert, strlen(client_cert) + 1); + if (ret < 0) { + // printf("mbedtls_x509_crt_parse returned -0x%x\n\n", -ret); + return ret; } + } - const char *client_key = mod_ssl_read_file(key_path, &ssl_sock->vstr_key); - if (client_key) { - ret = mbedtls_pk_parse_key(&ssl_sock->pk_key, (uint8_t *)client_key, strlen(client_key) + 1, (const unsigned char *)"", 0); - if (ret < 0) { - // printf("mbedtls_pk_parse_key returned -0x%x\n\n", -ret); - return ret; - } - } else { - nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "key file not found")); + if (client_key) { + ret = mbedtls_pk_parse_key(&ssl_sock->pk_key, (uint8_t *)client_key, strlen(client_key) + 1, (const unsigned char *)"", 0); + if (ret < 0) { + // printf("mbedtls_pk_parse_key returned -0x%x\n\n", -ret); + return ret; } } @@ -126,7 +126,7 @@ static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const char * mbedtls_ssl_conf_authmode(&ssl_sock->conf, ssl_verify); mbedtls_ssl_conf_rng(&ssl_sock->conf, mbedtls_ctr_drbg_random, &ssl_sock->ctr_drbg); mbedtls_ssl_conf_ca_chain(&ssl_sock->conf, &ssl_sock->cacert, NULL); - if (client_cert_path && key_path) { + if (client_cert && client_key) { if ((ret = mbedtls_ssl_conf_own_cert(&ssl_sock->conf, &ssl_sock->own_cert, &ssl_sock->pk_key)) != 0) { @@ -139,6 +139,12 @@ static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const char * // printf("mbedtls_ssl_setup returned -0x%x\n\n", -ret); return ret; } + if (saved_session != NULL) { + if ((ret = mbedtls_ssl_set_session(&ssl_sock->ssl, saved_session)) != 0) { + // printf("mbedtls_ssl_set_session returned -0x%x\n\n", -ret); + return ret; + } + } if (host_name) { // printf("Setting hostname for TLS session...\n"); @@ -162,7 +168,7 @@ static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const char * mbedtls_ssl_set_bio(&ssl_sock->ssl, &ssl_sock->context_fd, mbedtls_net_send, NULL, mbedtls_net_recv_timeout); - // printf("Performing the SSL/TLS handshake...\n"); + //printf("Performing the SSL/TLS handshake...\n"); int count = 0; while ((ret = mbedtls_ssl_handshake(&ssl_sock->ssl)) != 0) { @@ -176,92 +182,27 @@ static int32_t mod_ssl_setup_socket (mp_obj_ssl_socket_t *ssl_sock, const char * } } - // printf("Verifying peer X.509 certificate...\n"); - if ((ret = mbedtls_ssl_get_verify_result(&ssl_sock->ssl)) != 0) { - /* In real life, we probably want to close connection if ret != 0 */ - // printf("Failed to verify peer certificate!\n"); + //printf("Verifying peer X.509 certificate...\n"); + ret = mbedtls_ssl_get_verify_result(&ssl_sock->ssl); + if (ret == 0) { + //printf("Certificate verified.\n"); + return 0; + } + // If no verification is needed the mbedtls_ssl_get_verify_result() returns with MBEDTLS_X509_BADCERT_SKIP_VERIFY + else if((ssl_verify == MBEDTLS_SSL_VERIFY_NONE) && (ret == MBEDTLS_X509_BADCERT_SKIP_VERIFY)) { + //printf("Certification validation skipped.\n"); + return 0; + } + else { + /* In real life, we probably want to close connection in this case */ + //printf("Failed to verify peer certificate!\n"); return -1; - } else { - // printf("Certificate verified.\n"); } } return 0; } -static char *mod_ssl_read_file (const char *file_path, vstr_t *vstr) { - vstr_init(vstr, FILE_READ_SIZE); - char *filebuf = vstr->buf; - mp_uint_t actualsize; - mp_uint_t totalsize = 0; - static const TCHAR *path_relative; - - if(isLittleFs(file_path)) - { - vfs_lfs_struct_t* littlefs = lookup_path_littlefs(file_path, &path_relative); - if (littlefs == NULL) { - return NULL; - } - - lfs_file_t fp; - - xSemaphoreTake(littlefs->mutex, portMAX_DELAY); - - int res = lfs_file_open(&littlefs->lfs, &fp, path_relative, LFS_O_RDONLY); - if(res < LFS_ERR_OK) - { - return NULL; - } - - while (true) { - actualsize = lfs_file_read(&littlefs->lfs, &fp, filebuf, FILE_READ_SIZE); - if (actualsize < LFS_ERR_OK) { - return NULL; - } - totalsize += actualsize; - if (actualsize < FILE_READ_SIZE) { - break; - } else { - filebuf = vstr_extend(vstr, FILE_READ_SIZE); - } - } - lfs_file_close(&littlefs->lfs, &fp); - - xSemaphoreGive(littlefs->mutex); - - } - else - { - FATFS *fs = lookup_path_fatfs(file_path, &path_relative); - if (fs == NULL) { - return NULL; - } - FIL fp; - FRESULT res = f_open(fs, &fp, path_relative, FA_READ); - if (res != FR_OK) { - return NULL; - } - - while (true) { - FRESULT res = f_read(&fp, filebuf, FILE_READ_SIZE, (UINT *)&actualsize); - if (res != FR_OK) { - f_close(&fp); - return NULL; - } - totalsize += actualsize; - if (actualsize < FILE_READ_SIZE) { - break; - } else { - filebuf = vstr_extend(vstr, FILE_READ_SIZE); - } - } - f_close(&fp); - } - - vstr->len = totalsize; - vstr_null_terminated_str(vstr); - return vstr->buf; -} /******************************************************************************/ // Micro Python bindings; SSL class @@ -276,6 +217,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(mp_uint_t n_args, const mp_obj_t *pos_args, { MP_QSTR_ssl_version, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_ca_certs, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_server_hostname, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_saved_session, 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} }, }; @@ -304,6 +246,21 @@ STATIC mp_obj_t mod_ssl_wrap_socket(mp_uint_t n_args, const mp_obj_t *pos_args, goto arg_error; } + // socket type check + if (!mp_obj_is_type(args[0].u_obj, &socket_type)) { + goto arg_error; + } + + // saved_session type check + if (args[8].u_obj != mp_const_none) { + if (!mp_obj_is_type(args[8].u_obj, &mod_ssl_session_type)) { + goto arg_error; + } + } + + // Retrieve previously saved session + const mbedtls_ssl_session *saved_session = (args[8].u_obj == mp_const_none) ? NULL : &((mp_obj_ssl_session_t *)args[8].u_obj)->saved_session; + // create the ssl socket mp_obj_ssl_socket_t *ssl_sock = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); // ssl sockets inherit all properties from the original socket @@ -312,18 +269,40 @@ STATIC mp_obj_t mod_ssl_wrap_socket(mp_uint_t n_args, const mp_obj_t *pos_args, ssl_sock->o_sock = args[0].u_obj; // this is needed so that the GC doesnt collect the socket //Read timeout - if(args[8].u_obj == mp_const_none) + if(args[9].u_obj == mp_const_none) { ssl_sock->read_timeout = DEFAULT_SSL_READ_TIMEOUT; } else { - ssl_sock->read_timeout = mp_obj_get_int(args[8].u_obj); + ssl_sock->read_timeout = mp_obj_get_int(args[9].u_obj); } + const char *ca_cert = NULL; + if (cafile_path) { + ca_cert = pycom_util_read_file(cafile_path, &ssl_sock->vstr_ca); + if(ca_cert == NULL) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "CA file not found")); + } + } + + const char *client_cert = NULL; + const char *client_key = NULL; + if (certfile_path && keyfile_path) { + client_cert = pycom_util_read_file(certfile_path, &ssl_sock->vstr_ca); + if(client_cert == NULL) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "certificate file not found")); + } + client_key = pycom_util_read_file(keyfile_path, &ssl_sock->vstr_ca); + if(client_key == NULL) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "key file not found")); + } + } + + MP_THREAD_GIL_EXIT(); - _error = mod_ssl_setup_socket(ssl_sock, host_name, cafile_path, certfile_path, keyfile_path, + _error = mod_ssl_setup_socket(ssl_sock, saved_session, host_name, ca_cert, client_cert, client_key, verify_type, server_side ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT); MP_THREAD_GIL_ENTER(); @@ -339,9 +318,42 @@ STATIC mp_obj_t mod_ssl_wrap_socket(mp_uint_t n_args, const mp_obj_t *pos_args, } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_wrap_socket_obj, 0, mod_ssl_wrap_socket); +STATIC mp_obj_t mod_ssl_save_session(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + STATIC const mp_arg_t allowed_args[] = { + { MP_QSTR_ssl_sock, MP_ARG_REQUIRED | MP_ARG_OBJ, }, + }; + + int32_t _error; + + // 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); + + mp_obj_ssl_socket_t *ssl_sock = args[0].u_obj; + + // Create the SSL session obj + mp_obj_ssl_session_t *ssl_session = m_new_obj_with_finaliser(mp_obj_ssl_session_t); + ssl_session->base.type = &mod_ssl_session_type; + memset(&ssl_session->saved_session, 0, sizeof(mbedtls_ssl_session)); + + MP_THREAD_GIL_EXIT(); + + _error = mbedtls_ssl_get_session(&ssl_sock->ssl, &ssl_session->saved_session); + + MP_THREAD_GIL_ENTER(); + + if (_error) { + mp_raise_OSError(_error); + } + + return ssl_session; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_KW(mod_ssl_save_session_obj, 0, mod_ssl_save_session); + STATIC const mp_map_elem_t mp_module_ussl_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_ussl) }, { MP_OBJ_NEW_QSTR(MP_QSTR_wrap_socket), (mp_obj_t)&mod_ssl_wrap_socket_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_save_session), (mp_obj_t)&mod_ssl_save_session_obj }, // class exceptions { MP_OBJ_NEW_QSTR(MP_QSTR_SSLError), (mp_obj_t)&mp_type_OSError }, @@ -365,4 +377,3 @@ const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, .globals = (mp_obj_dict_t*)&mp_module_ussl_globals, }; - diff --git a/esp32/mods/modussl.h b/esp32/mods/modussl.h index af04e9db65..9784311eb4 100644 --- a/esp32/mods/modussl.h +++ b/esp32/mods/modussl.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -45,4 +45,9 @@ typedef struct _mp_obj_ssl_socket_t { uint8_t read_timeout; } mp_obj_ssl_socket_t; +typedef struct _mp_obj_ssl_session_t { + mp_obj_base_t base; + mbedtls_ssl_session saved_session; +} mp_obj_ssl_session_t; + #endif /* MODUSSL_H_ */ diff --git a/esp32/mods/modutime.c b/esp32/mods/modutime.c index 39fe282118..3341d58b29 100644 --- a/esp32/mods/modutime.c +++ b/esp32/mods/modutime.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/mods/modwlan.c b/esp32/mods/modwlan.c index af8a1554c9..64a0ecc321 100644 --- a/esp32/mods/modwlan.c +++ b/esp32/mods/modwlan.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -29,9 +29,6 @@ #include "esp_wifi.h" #include "esp_wifi_types.h" #include "esp_event_loop.h" -#include "ff.h" -#include "lfs.h" -#include "vfs_littlefs.h" #include "esp_wpa2.h" #include "esp_smartconfig.h" @@ -58,6 +55,7 @@ #include "mpirq.h" #include "mptask.h" #include "pycom_config.h" +#include "pycom_general_util.h" /****************************************************************************** DEFINE TYPES @@ -67,7 +65,6 @@ DEFINE CONSTANTS ******************************************************************************/ -#define FILE_READ_SIZE 256 #define BSSID_MAX_SIZE 6 #define MAX_WLAN_KEY_SIZE 65 #define MAX_AP_CONNECTED_STA 4 @@ -164,7 +161,6 @@ STATIC void wlan_set_antenna (uint8_t antenna); static esp_err_t wlan_event_handler(void *ctx, system_event_t *event); STATIC void wlan_do_connect (const char* ssid, const char* bssid, const wifi_auth_mode_t auth, const char* key, int32_t timeout, const wlan_wpa2_ent_obj_t * const wpa2_ent, const char *hostname, uint8_t channel); static void wlan_init_wlan_recover_params(void); -static char *wlan_read_file (const char *file_path, vstr_t *vstr); static void wlan_timer_callback( TimerHandle_t xTimer ); static void wlan_validate_country(const char * country); static void wlan_validate_country_policy(uint8_t policy); @@ -286,6 +282,7 @@ void wlan_setup (wlan_internal_setup_t *config) { { case WIFI_MODE_AP: MP_THREAD_GIL_EXIT(); + // wlan_setup_ap must be called only when GIL is not locked wlan_setup_ap (config->ssid_ap, config->auth, config->key_ap, config->channel, config->add_mac, config->hidden); // Start Wifi esp_wifi_start(); @@ -294,15 +291,33 @@ void wlan_setup (wlan_internal_setup_t *config) { break; case WIFI_MODE_APSTA: case WIFI_MODE_STA: + MP_THREAD_GIL_EXIT(); if(config->mode == WIFI_MODE_APSTA) { + // wlan_setup_ap must be called only when GIL is not locked wlan_setup_ap (config->ssid_ap, config->auth, config->key_ap, config->channel, config->add_mac, config->hidden); } - MP_THREAD_GIL_EXIT(); // Start Wifi esp_wifi_start(); wlan_obj.started = true; if (config->ssid_sta != NULL) { + if (config->auth == WIFI_AUTH_WPA2_ENTERPRISE) { + + // Take back the GIL as the pycom_util_read_file() uses MicroPython APIs (allocates memory with GC) + MP_THREAD_GIL_ENTER(); + + if (wlan_wpa2_ent.ca_certs_path != NULL) { + pycom_util_read_file(wlan_wpa2_ent.ca_certs_path, &wlan_obj.vstr_ca); + } + + if (wlan_wpa2_ent.client_key_path != NULL && wlan_wpa2_ent.client_cert_path != NULL) { + pycom_util_read_file(wlan_wpa2_ent.client_key_path, &wlan_obj.vstr_key); + pycom_util_read_file(wlan_wpa2_ent.client_cert_path, &wlan_obj.vstr_cert); + } + + MP_THREAD_GIL_EXIT(); + } + // connect to the requested access point wlan_do_connect (config->ssid_sta, NULL, config->auth, config->key_sta, 30000, &wlan_wpa2_ent, NULL, 0); } @@ -504,6 +519,7 @@ STATIC void wlan_servers_stop (void) { } } +// Must be called only when GIL is not locked STATIC void wlan_setup_ap (const char *ssid, uint32_t auth, const char *key, uint32_t channel, bool add_mac, bool hidden) { uint32_t ssid_len = wlan_set_ssid_internal (ssid, strlen(ssid), add_mac); wlan_set_security_internal(auth, key); @@ -523,7 +539,10 @@ STATIC void wlan_setup_ap (const char *ssid, uint32_t auth, const char *key, uin //get mac of AP esp_wifi_get_mac(WIFI_IF_AP, wlan_obj.mac_ap); + // Need to take back the GIL as mod_network_register_nic() uses MicroPython API and wlan_setup_ap() is called when GIL is not locked + MP_THREAD_GIL_ENTER(); mod_network_register_nic(&wlan_obj); + MP_THREAD_GIL_EXIT(); } STATIC void wlan_validate_mode (uint mode) { @@ -743,10 +762,11 @@ STATIC void wlan_do_connect (const char* ssid, const char* bssid, const wifi_aut goto os_error; } + // The certificate files are already read at this point because this function runs outside of GIL, and the file_read functions uses MicroPython APIs if (auth == WIFI_AUTH_WPA2_ENTERPRISE) { // CA Certificate is not mandatory if (wpa2_ent->ca_certs_path != NULL) { - if (wlan_read_file(wpa2_ent->ca_certs_path, &wlan_obj.vstr_ca)) { + if (wlan_obj.vstr_ca.buf != NULL) { if (ESP_OK != esp_wifi_sta_wpa2_ent_set_ca_cert((unsigned char*)wlan_obj.vstr_ca.buf, (int)wlan_obj.vstr_ca.len)) { goto os_error; } @@ -757,7 +777,7 @@ STATIC void wlan_do_connect (const char* ssid, const char* bssid, const wifi_aut // client certificate is necessary only in EAP-TLS method, this is ensured by wlan_validate_certificates() function if (wpa2_ent->client_key_path != NULL && wpa2_ent->client_cert_path != NULL) { - if (wlan_read_file(wpa2_ent->client_key_path, &wlan_obj.vstr_key) && wlan_read_file(wpa2_ent->client_cert_path, &wlan_obj.vstr_cert)) { + if ((wlan_obj.vstr_cert.buf != NULL) && (wlan_obj.vstr_key.buf != NULL)) { if (ESP_OK != esp_wifi_sta_wpa2_ent_set_cert_key((unsigned char*)wlan_obj.vstr_cert.buf, (int)wlan_obj.vstr_cert.len, (unsigned char*)wlan_obj.vstr_key.buf, (int)wlan_obj.vstr_key.len, NULL, 0)) { goto os_error; @@ -822,78 +842,6 @@ STATIC void wlan_do_connect (const char* ssid, const char* bssid, const wifi_aut nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_operation_failed)); } -STATIC char *wlan_read_file (const char *file_path, vstr_t *vstr) { - vstr_init(vstr, FILE_READ_SIZE); - char *filebuf = vstr->buf; - mp_uint_t actualsize; - mp_uint_t totalsize = 0; - static const TCHAR *path_relative; - - if(isLittleFs(file_path)) - { - vfs_lfs_struct_t* littlefs = lookup_path_littlefs(file_path, &path_relative); - if (littlefs == NULL) { - return NULL; - } - - xSemaphoreTake(littlefs->mutex, portMAX_DELAY); - - lfs_file_t fp; - int res = lfs_file_open(&littlefs->lfs, &fp, path_relative, LFS_O_RDONLY); - if(res < LFS_ERR_OK) - { - return NULL; - } - - while (true) { - actualsize = lfs_file_read(&littlefs->lfs, &fp, filebuf, FILE_READ_SIZE); - if (actualsize < LFS_ERR_OK) { - return NULL; - } - totalsize += actualsize; - if (actualsize < FILE_READ_SIZE) { - break; - } else { - filebuf = vstr_extend(vstr, FILE_READ_SIZE); - } - } - lfs_file_close(&littlefs->lfs, &fp); - - xSemaphoreGive(littlefs->mutex); - - } - else - { - FATFS *fs = lookup_path_fatfs(file_path, &path_relative); - if (fs == NULL) { - return NULL; - } - FIL fp; - FRESULT res = f_open(fs, &fp, path_relative, FA_READ); - if (res != FR_OK) { - return NULL; - } - - while (true) { - FRESULT res = f_read(&fp, filebuf, FILE_READ_SIZE, (UINT *)&actualsize); - if (res != FR_OK) { - f_close(&fp); - return NULL; - } - totalsize += actualsize; - if (actualsize < FILE_READ_SIZE) { - break; - } else { - filebuf = vstr_extend(vstr, FILE_READ_SIZE); - } - } - f_close(&fp); - } - - vstr->len = totalsize; - vstr_null_terminated_str(vstr); - return vstr->buf; -} static void wlan_init_wlan_recover_params(void) { @@ -1496,7 +1444,7 @@ STATIC mp_obj_t wlan_scan(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t * esp_wifi_scan_get_ap_num(&ap_num); // get the number of scanned APs if (ap_num > 0) { - ap_record_buffer = pvPortMalloc(ap_num * sizeof(wifi_ap_record_t)); + ap_record_buffer = malloc(ap_num * sizeof(wifi_ap_record_t)); if (ap_record_buffer == NULL) { mp_raise_OSError(MP_ENOMEM); } @@ -1516,7 +1464,7 @@ STATIC mp_obj_t wlan_scan(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t * mp_obj_list_append(nets, mp_obj_new_attrtuple(wlan_scan_info_fields, 5, tuple)); } } - vPortFree(ap_record_buffer); + free(ap_record_buffer); } return nets; @@ -2023,6 +1971,40 @@ STATIC mp_obj_t wlan_ap_sta_list (mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_ap_sta_list_obj, wlan_ap_sta_list); +STATIC mp_obj_t wlan_ap_tcpip_sta_list (mp_obj_t self_in) { + STATIC const qstr wlan_sta_ifo_fields[] = { + MP_QSTR_mac, MP_QSTR_IP + }; + uint8_t index; + wifi_sta_list_t wifi_sta_list; + esp_wifi_ap_get_sta_list(&wifi_sta_list); + tcpip_adapter_sta_list_t sta_list; + wlan_obj_t * self = self_in; + + mp_obj_t sta_out_list = mp_obj_new_list(0, NULL); + /* Check if AP mode is enabled */ + if (self->mode == WIFI_MODE_AP || self->mode == WIFI_MODE_APSTA) { + tcpip_adapter_get_sta_list(&wifi_sta_list, &sta_list); + + mp_obj_t tuple[2]; + for(index = 0; index < MAX_AP_CONNECTED_STA && index < sta_list.num; index++) + { + tuple[0] = mp_obj_new_bytes((const byte *)sta_list.sta[index].mac, 6); + tuple[1] = netutils_format_ipv4_addr((uint8_t *)&sta_list.sta[index].ip.addr, NETUTILS_BIG); + + /*insert tuple */ + mp_obj_list_append(sta_out_list, mp_obj_new_attrtuple(wlan_sta_ifo_fields, 2, tuple)); + } + } + else + { + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, mpexception_os_request_not_possible)); + } + + return sta_out_list; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(wlan_ap_tcpip_sta_list_obj, wlan_ap_tcpip_sta_list); + STATIC mp_obj_t wlan_joined_ap_info (mp_obj_t self_in) { STATIC const qstr wlan_sta_ifo_fields[] = { @@ -2706,6 +2688,7 @@ STATIC const mp_map_elem_t wlan_locals_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_antenna), (mp_obj_t)&wlan_antenna_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_mac), (mp_obj_t)&wlan_mac_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_ap_sta_list), (mp_obj_t)&wlan_ap_sta_list_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_ap_tcpip_sta_list), (mp_obj_t)&wlan_ap_tcpip_sta_list_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_max_tx_power), (mp_obj_t)&wlan_max_tx_power_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_country), (mp_obj_t)&wlan_country_obj }, { MP_OBJ_NEW_QSTR(MP_QSTR_joined_ap_info), (mp_obj_t)&wlan_joined_ap_info_obj }, diff --git a/esp32/mods/modwlan.h b/esp32/mods/modwlan.h index 8f030dcd88..585e0ef905 100644 --- a/esp32/mods/modwlan.h +++ b/esp32/mods/modwlan.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/pybadc.c b/esp32/mods/pybadc.c index 2aefa797c1..1f442fe2c9 100644 --- a/esp32/mods/pybadc.c +++ b/esp32/mods/pybadc.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/pybadc.h b/esp32/mods/pybadc.h index f5a17643c0..53b6d885ad 100644 --- a/esp32/mods/pybadc.h +++ b/esp32/mods/pybadc.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/pybdac.c b/esp32/mods/pybdac.c index 9556517bff..ea809d1b78 100644 --- a/esp32/mods/pybdac.c +++ b/esp32/mods/pybdac.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/pybdac.h b/esp32/mods/pybdac.h index b4a02d1e58..7b537eea8b 100644 --- a/esp32/mods/pybdac.h +++ b/esp32/mods/pybdac.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/pybsd.c b/esp32/mods/pybsd.c index 007352d92a..c6b6c1bcf3 100644 --- a/esp32/mods/pybsd.c +++ b/esp32/mods/pybsd.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mods/pybsd.h b/esp32/mods/pybsd.h index d6ee2e23f6..130a51af49 100644 --- a/esp32/mods/pybsd.h +++ b/esp32/mods/pybsd.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mpconfigport.h b/esp32/mpconfigport.h index 03da7ba524..9870415bd2 100644 --- a/esp32/mpconfigport.h +++ b/esp32/mpconfigport.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence @@ -250,7 +250,6 @@ extern const struct _mp_obj_module_t mp_module_uqueue; mp_obj_list_t btc_conn_list; \ mp_obj_list_t bts_srv_list; \ mp_obj_list_t bts_attr_list; \ - char* lfs_cwd; \ mp_obj_t coap_ptr; \ // we need to provide a declaration/definition of alloca() diff --git a/esp32/mptask.c b/esp32/mptask.c index 61c3a6059c..77bc0d58f4 100644 --- a/esp32/mptask.c +++ b/esp32/mptask.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -174,12 +174,12 @@ void TASK_Micropython (void *pvParameters) { if (esp32_get_chip_rev() > 0) { gc_pool_size = GC_POOL_SIZE_BYTES_PSRAM; - gc_pool_upy = heap_caps_malloc(GC_POOL_SIZE_BYTES_PSRAM, MALLOC_CAP_SPIRAM); } else { gc_pool_size = GC_POOL_SIZE_BYTES; - gc_pool_upy = heap_caps_malloc(GC_POOL_SIZE_BYTES, MALLOC_CAP_INTERNAL); } + gc_pool_upy = malloc(gc_pool_size); + if (NULL == gc_pool_upy) { printf("GC pool malloc failed!\n"); for ( ; ; ); @@ -298,7 +298,16 @@ void TASK_Micropython (void *pvParameters) { if (!safeboot) { // execute the frozen main first + +#if (VARIANT == PYBYTES) + if (config_get_pybytes_autostart()) { + pyexec_frozen_module("_main_pybytes.py"); + } else { + pyexec_frozen_module("_main.py"); + } +#else pyexec_frozen_module("_main.py"); +#endif // run the main script from the current directory. if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) { @@ -525,11 +534,10 @@ STATIC void mptask_init_sflash_filesystem_littlefs(void) { MP_STATE_PORT(vfs_cur) = vfs; //Initialize the current working directory (cwd) - vfs_littlefs->fs.littlefs.cwd = (char*)m_malloc(2); + vfs_littlefs->fs.littlefs.cwd = (char*)malloc(2); vfs_littlefs->fs.littlefs.cwd[0] = '/'; vfs_littlefs->fs.littlefs.cwd[1] = '\0'; - MP_STATE_PORT(lfs_cwd) = vfs_littlefs->fs.littlefs.cwd; vfs_littlefs->fs.littlefs.mutex = xSemaphoreCreateMutex(); xSemaphoreTake(vfs_littlefs->fs.littlefs.mutex, portMAX_DELAY); diff --git a/esp32/mptask.h b/esp32/mptask.h index abb1026b20..f1ba4f870b 100644 --- a/esp32/mptask.h +++ b/esp32/mptask.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/mpthreadport.c b/esp32/mpthreadport.c index e98c706b08..de383be612 100644 --- a/esp32/mpthreadport.c +++ b/esp32/mpthreadport.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence @@ -171,15 +171,15 @@ void mp_thread_create_ex(void *(*entry)(void*), void *arg, size_t *stack_size, i // allocate TCB, stack and linked-list node (must be outside thread_mutex lock) if (mp_chip_revision > 0) { // for revision 1 devices we allocate from the internal memory of the malloc heap - tcb = heap_caps_malloc(sizeof(StaticTask_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + tcb = malloc(sizeof(StaticTask_t)); if (!tcb) { goto memory_error; } - stack = heap_caps_malloc(*stack_size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + stack = malloc(*stack_size); if (!stack) { goto memory_error; } - th = heap_caps_malloc(sizeof(thread_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + th = malloc(sizeof(thread_t)); if (!th) { goto memory_error; } @@ -280,6 +280,7 @@ void vPortCleanUpTCB (void *tcb) { mp_obj_thread_lock_t *mp_thread_new_thread_lock(void) { mp_obj_thread_lock_t *self = m_new_obj(mp_obj_thread_lock_t); + self->mutex = gc_alloc(sizeof(mp_thread_mutex_t), false); if (NULL == self->mutex) { nlr_raise(mp_obj_new_exception_msg(&mp_type_MemoryError, "can't create lock")); diff --git a/esp32/mpthreadport.h b/esp32/mpthreadport.h index 486716eb41..c54d0bc4a7 100644 --- a/esp32/mpthreadport.h +++ b/esp32/mpthreadport.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/pycom_config.c b/esp32/pycom_config.c index 8aa40dab0a..74c75b5752 100644 --- a/esp32/pycom_config.c +++ b/esp32/pycom_config.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -393,6 +393,18 @@ bool config_set_boot_fs_type (const uint8_t boot_fs_type) { return config_write(); } +bool config_set_pybytes_autostart (bool pybytes_autostart) { + if (pycom_config_block.pybytes_config.auto_start != (uint8_t)pybytes_autostart) { + pycom_config_block.pybytes_config.auto_start = (uint8_t)pybytes_autostart; + return config_write(); + } + return true; +} + +bool config_get_pybytes_autostart (void) { + return (bool)pycom_config_block.pybytes_config.auto_start; +} + static bool config_write (void) { // erase the block first if (ESP_OK == spi_flash_erase_sector(CONFIG_DATA_FLASH_BLOCK)) { diff --git a/esp32/pycom_config.h b/esp32/pycom_config.h index b8f5d8a2e8..9c23f5ae17 100644 --- a/esp32/pycom_config.h +++ b/esp32/pycom_config.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -11,7 +11,16 @@ #define PYCOM_CONFIG_H_ #include "py/mpconfig.h" +#include +/** + * pycom_config_block_t is written and read directly to the config partition + * (see ./esp32/lib/partitions_xMB.csv) + * When adding attributes to this config block, be sure to only add them *after* + * all existing attributes. + * + * the _Static_assert()'s below enforce that the memory layout doesn't change + */ /****************************************************************************** DEFINE CONSTANTS @@ -29,6 +38,7 @@ typedef struct { uint8_t sigfox_public_key[16]; uint8_t lora_region; } pycom_lpwan_config_t; +_Static_assert(sizeof(pycom_lpwan_config_t) == 53, "pycom_lpwan_config_t should have a size of 53 bytes"); typedef struct { uint8_t wifi_on_boot :1; @@ -37,16 +47,19 @@ typedef struct { uint8_t wifi_auth :3; uint8_t wifi_antenna :1; } pycom_wifi_config_t; +_Static_assert(sizeof(pycom_wifi_config_t) == 1, "pycom_wifi_config_t should have a size of 1 bytes"); typedef struct { uint8_t wifi_ssid[33]; uint8_t wifi_pwd[65]; } pycom_wifi_sta_config_t; +_Static_assert(sizeof(pycom_wifi_sta_config_t) == 98, "pycom_wifi_sta_config_t should have a size of 98 bytes"); typedef struct { uint8_t wifi_ssid[33]; uint8_t wifi_pwd[65]; } pycom_wifi_ap_config_t; +_Static_assert(sizeof(pycom_wifi_ap_config_t) == 98, "pycom_wifi_ap_config_t should have a size of 98 bytes"); typedef struct { uint8_t heartbeat_on_boot :1; @@ -54,6 +67,7 @@ typedef struct { uint8_t rgb_safeboot_color[3]; uint8_t rgb_heartbeat_color[3]; } pycom_rgbled_config_t; +_Static_assert(sizeof(pycom_rgbled_config_t) == 10, "pycom_rgbled_config_t should have a size of 10 bytes"); typedef struct { uint8_t device_token[40]; @@ -62,8 +76,10 @@ typedef struct { uint8_t network_preferences[55]; uint8_t extra_preferences[100]; uint8_t force_update; - uint8_t reserved[12]; + uint8_t auto_start; + uint8_t reserved[11]; } pycom_pybytes_config_t; +_Static_assert(sizeof(pycom_pybytes_config_t) == 348, "pycom_pybytes_config_t should have a size of 348 bytes"); typedef struct { uint8_t sw_version[12]; @@ -71,38 +87,44 @@ typedef struct { uint8_t boot_partition; uint8_t hw_type; } pycom_config_t; +_Static_assert(sizeof(pycom_config_t) == 15, "pycom_config_t should have a size of 15 bytes"); typedef struct { - uint8_t wdt_on_boot; + uint8_t wdt_on_boot; // 1byte + 3bytes padding uint32_t wdt_on_boot_timeout; } pycom_wdt_config_t; +_Static_assert(sizeof(pycom_wdt_config_t) == 8, "pycom_wdt_config_t should have a size of 8 bytes"); typedef struct { uint8_t lte_modem_en_on_boot; } pycom_lte_config_t; +_Static_assert(sizeof(pycom_lte_config_t) == 1, "pycom_lte_config_t should have a size of 1 bytes"); typedef struct { - uint8_t carrier[129]; - uint8_t apn[129]; - uint8_t type[17]; - uint8_t cid; - uint8_t band; - uint8_t reset; + uint8_t carrier[129]; + uint8_t apn[129]; + uint8_t type[17]; + uint8_t cid; + uint8_t band; + uint8_t reset; } pycom_pybytes_lte_config_t; - -typedef struct { - pycom_lpwan_config_t lpwan_config; - pycom_wifi_config_t wifi_config; - pycom_wifi_sta_config_t wifi_sta_config; - pycom_rgbled_config_t rgbled_config; - pycom_pybytes_config_t pybytes_config; - pycom_wdt_config_t wdt_config; - pycom_lte_config_t lte_config; - pycom_config_t pycom_config; - pycom_wifi_ap_config_t wifi_ap_config; - pycom_pybytes_lte_config_t pycom_pybytes_lte_config; - uint8_t pycom_reserved[112]; -} pycom_config_block_t; +// pycom_pybytes_lte_config_t is the last used member of pycom_config_block_t, so no _Static_assert(sizeof()) needed + +typedef struct { // size + pycom_lpwan_config_t lpwan_config; // 53 + pycom_wifi_config_t wifi_config; // 1 + pycom_wifi_sta_config_t wifi_sta_config; // 98 + pycom_rgbled_config_t rgbled_config; // 10 + pycom_pybytes_config_t pybytes_config; // 348 + uint8_t pycom_unused[2]; // 2 since wdt_config has 4byte-alignment, there are currently two bytes of padding before it + pycom_wdt_config_t wdt_config; // 8 since wdt_config contains a uint32_t, it has 4byte-alignment + pycom_lte_config_t lte_config; // 1 + pycom_config_t pycom_config; // 15 + pycom_wifi_ap_config_t wifi_ap_config; // 98 + pycom_pybytes_lte_config_t pycom_pybytes_lte_config; // 278 + uint8_t pycom_reserved[112]; // 112 +} pycom_config_block_t; // 1024 +_Static_assert(sizeof(pycom_config_block_t) == 1024, "pycom_config_block_t should have a size of 1024 bytes"); // partition is 4Kb, I think multiples of 1Kb <= 4Kb are ok typedef enum { @@ -219,4 +241,8 @@ bool config_set_lte_modem_enable_on_boot (bool lte_modem_en_on_boot); bool config_get_lte_modem_enable_on_boot (void); +bool config_set_pybytes_autostart (bool pybytes_autostart); + +bool config_get_pybytes_autostart (void); + #endif /* PYCOM_CONFIG_H_ */ diff --git a/esp32/pycom_version.h b/esp32/pycom_version.h index 9bc0d36232..1a6333107d 100644 --- a/esp32/pycom_version.h +++ b/esp32/pycom_version.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -10,14 +10,14 @@ #ifndef VERSION_H_ #define VERSION_H_ -#define SW_VERSION_NUMBER "1.20.1.r3" +#define SW_VERSION_NUMBER "1.20.2.r0" #define LORAWAN_VERSION_NUMBER "1.0.2" #define SIGFOX_VERSION_NUMBER "1.0.1" #if (VARIANT == PYBYTES) -#define PYBYTES_VERSION_NUMBER "1.3.0" +#define PYBYTES_VERSION_NUMBER "1.5.1" #endif #endif /* VERSION_H_ */ diff --git a/esp32/qstrdefsport.h b/esp32/qstrdefsport.h index 0bb9204764..63a2b5d304 100644 --- a/esp32/qstrdefsport.h +++ b/esp32/qstrdefsport.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/sdkconfig.h b/esp32/sdkconfig.h index 3960eaef97..fabbc160b4 100644 --- a/esp32/sdkconfig.h +++ b/esp32/sdkconfig.h @@ -8,9 +8,11 @@ #define CONFIG_ESP32_PHY_MAX_TX_POWER 20 #define CONFIG_TRACEMEM_RESERVE_DRAM 0x0 #define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16 +#define CONFIG_SECURE_BOOT_SIGNING_KEY "secure_boot_signing_key.pem" #define CONFIG_BLE_SMP_ENABLE 1 #define CONFIG_FATFS_LFN_NONE 1 #define CONFIG_SPIRAM_TYPE_AUTO 1 +#define CONFIG_SMP_SLAVE_CON_PARAMS_UPD_ENABLE 1 #define CONFIG_MB_SERIAL_TASK_PRIO 10 #define CONFIG_TCP_RECVMBOX_SIZE 6 #define CONFIG_FATFS_CODEPAGE_437 1 @@ -23,6 +25,7 @@ #define CONFIG_SPIFFS_USE_MAGIC_LENGTH 1 #define CONFIG_ESPTOOLPY_FLASHSIZE_4MB 1 #define CONFIG_IPC_TASK_STACK_SIZE 1024 +#define CONFIG_WIFI_PROV_SCAN_MAX_ENTRIES 16 #define CONFIG_FATFS_PER_FILE_CACHE 1 #define CONFIG_BT_BLE_DYNAMIC_ENV_MEMORY 1 #define CONFIG_ESPTOOLPY_FLASHFREQ "80m" @@ -55,6 +58,7 @@ #define CONFIG_MBEDTLS_SSL_ALPN 1 #define CONFIG_MBEDTLS_PEM_WRITE_C 1 #define CONFIG_BT_RESERVE_DRAM 0xdb5c +#define CONFIG_APP_COMPILE_TIME_DATE 1 #define CONFIG_SECURE_SIGNED_ON_BOOT 1 #define CONFIG_D2WD_PSRAM_CLK_IO 9 #define CONFIG_FATFS_FS_LOCK 0 @@ -71,18 +75,20 @@ #define CONFIG_LWIP_MAX_SOCKETS 10 #define CONFIG_LWIP_NETIF_LOOPBACK 1 #define CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL 16384 +#define CONFIG_ESP32_PTHREAD_TASK_NAME_DEFAULT "pthread" #define CONFIG_EMAC_TASK_PRIORITY 20 #define CONFIG_TIMER_TASK_STACK_DEPTH 2560 #define CONFIG_TCP_MSS 1436 #define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1 +#define CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR 1 #define CONFIG_BTDM_CONTROLLER_BLE_MAX_CONN_EFF 3 +#define CONFIG_EFUSE_CODE_SCHEME_COMPAT_3_4 1 #define CONFIG_TCPIP_TASK_AFFINITY_CPU0 1 #define CONFIG_FATFS_CODEPAGE 437 #define CONFIG_ESP32_DEFAULT_CPU_FREQ_160 1 #define CONFIG_ULP_COPROC_RESERVE_MEM 0 #define CONFIG_SECURE_SIGNED_APPS 1 #define CONFIG_LWIP_MAX_UDP_PCBS 16 -#define CONFIG_SMP_ENABLE 1 #define CONFIG_ESPTOOLPY_BAUD 921600 #define CONFIG_ADC_CAL_LUT_ENABLE 1 #define CONFIG_WIFI_FAST_SCAN 1 @@ -107,11 +113,13 @@ #define CONFIG_TIMER_TASK_STACK_SIZE 2560 #define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1 #define CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC 1 +#define CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER 1 #define CONFIG_HTTPD_PURGE_BUF_LEN 32 #define CONFIG_SCAN_DUPLICATE_BY_DEVICE_ADDR 1 #define CONFIG_MB_SERIAL_TASK_STACK_SIZE 768 #define CONFIG_GATTS_SEND_SERVICE_CHANGE_AUTO 1 #define CONFIG_LWIP_DHCPS_LEASE_UNIT 60 +#define CONFIG_EFUSE_MAX_BLK_LEN 192 #define CONFIG_SPIFFS_USE_MAGIC 1 #define CONFIG_TCPIP_TASK_STACK_SIZE 3072 #define CONFIG_BLUEDROID_PINNED_TO_CORE_0 1 @@ -146,9 +154,11 @@ #define CONFIG_ESP32_WIFI_TX_BA_WIN 6 #define CONFIG_ESP32_WIFI_NVS_ENABLED 1 #define CONFIG_MDNS_MAX_SERVICES 10 +#define CONFIG_IDF_TARGET_ESP32 1 #define CONFIG_EMAC_CHECK_LINK_PERIOD_MS 2000 #define CONFIG_BTDM_LPCLK_SEL_MAIN_XTAL 1 #define CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED 1 +#define CONFIG_LWIP_SNTP_UPDATE_DELAY 3600000 #define CONFIG_LIBSODIUM_USE_MBEDTLS_SHA 1 #define CONFIG_DMA_RX_BUF_NUM 10 #define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1 @@ -213,10 +223,13 @@ #define CONFIG_MBEDTLS_TLS_ENABLED 1 #define CONFIG_LWIP_MAX_RAW_PCBS 16 #define CONFIG_SPIRAM_IGNORE_NOTFOUND 1 +#define CONFIG_BTU_TASK_STACK_SIZE 4096 +#define CONFIG_SMP_ENABLE 1 #define CONFIG_SPIRAM_SIZE -1 #define CONFIG_FAST_SCAN_MINIMUM_SIGNAL -127 #define CONFIG_MBEDTLS_SSL_SESSION_TICKETS 1 #define CONFIG_SPIFFS_MAX_PARTITIONS 3 +#define CONFIG_ESP32_CORE_DUMP_MAX_TASKS_NUM 64 #define CONFIG_BTDM_CONTROLLER_PINNED_TO_CORE_0 1 #define CONFIG_BLE_HOST_QUEUE_CONGESTION_CHECK 1 #define CONFIG_MBEDTLS_SSL_RENEGOTIATION 1 @@ -249,34 +262,39 @@ #define CONFIG_PPP_PAP_SUPPORT 1 #define CONFIG_MBEDTLS_TLS_CLIENT 1 #define CONFIG_BTDM_CONTROLLER_HCI_MODE_VHCI 1 -#define CONFIG_BTDM_CONTROLLER_BR_EDR_SCO_DATA_PATH_EFF 0 #define CONFIG_BT_ENABLED 1 +#define CONFIG_ESP32_DEFAULT_PTHREAD_CORE_NO_AFFINITY 1 #define CONFIG_D0WD_PSRAM_CLK_IO 17 #define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1 #define CONFIG_MONITOR_BAUD 115200 +#define CONFIG_ESP32_PTHREAD_TASK_CORE_DEFAULT -1 #define CONFIG_BLE_ESTABLISH_LINK_CONNECTION_TIMEOUT 30 #define CONFIG_TCPIP_LWIP 1 #define CONFIG_ESP_TCP_KEEP_CONNECTION_WHEN_IP_CHANGES 1 #define CONFIG_WIFI_LWIP_ALLOCATION_FROM_SPIRAM_FIRST 1 #define CONFIG_FREERTOS_CORETIMER_0 1 #define CONFIG_IDF_FIRMWARE_CHIP_ID 0x0000 +#define CONFIG_PARTITION_TABLE_CUSTOM_FILENAME "partitions.csv" #define CONFIG_MBEDTLS_HAVE_TIME 1 #define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1 #define CONFIG_TCP_QUEUE_OOSEQ 1 -#define CONFIG_ESP32_CORE_DUMP_LOG_LEVEL 1 +#define CONFIG_FATFS_ALLOC_PREFER_EXTRAM 1 #define CONFIG_GATTS_ENABLE 1 #define CONFIG_ADC_CAL_EFUSE_VREF_ENABLE 1 #define CONFIG_MBEDTLS_TLS_SERVER 1 #define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1 +#define CONFIG_APP_EXCLUDE_PROJECT_VER_VAR 1 #define CONFIG_SPIRAM_BOOT_INIT 1 #define CONFIG_ESPTOOLPY_AFTER_NORESET 1 #define CONFIG_BLE_ADV_REPORT_FLOW_CONTROL_SUPPORTED 1 #define CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL 16384 #define CONFIG_FREERTOS_ISR_STACKSIZE 2560 #define CONFIG_OPENSSL_ASSERT_DO_NOTHING 1 +#define CONFIG_IDF_TARGET "esp32" #define CONFIG_WL_SECTOR_SIZE_4096 1 #define CONFIG_FREERTOS_NO_AFFINITY 0x7FFFFFFF #define CONFIG_ESP32_WIFI_AMPDU_TX_ENABLED 1 +#define CONFIG_HTTPD_ERR_RESP_NO_DELAY 1 #define CONFIG_SCAN_DUPLICATE_TYPE 0 #define CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED 1 #define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1 @@ -304,6 +322,7 @@ #define CONFIG_NEWLIB_STDOUT_LINE_ENDING_CRLF 1 #define CONFIG_ESPTOOLPY_PORT "/dev/ttyUSB0" #define CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ABORTS 1 +#define CONFIG_BTDM_CTRL_BR_EDR_SCO_DATA_PATH_EFF 0 #define CONFIG_OPTIMIZATION_LEVEL_RELEASE 1 #define CONFIG_BLE_ADV_REPORT_DISCARD_THRSHOLD 20 #define CONFIG_BLUEDROID_PINNED_TO_CORE 0 diff --git a/esp32/serverstask.c b/esp32/serverstask.c index 13030f2594..d3da8e2894 100644 --- a/esp32/serverstask.c +++ b/esp32/serverstask.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/serverstask.h b/esp32/serverstask.h index 3a34718bf5..5762acbd28 100644 --- a/esp32/serverstask.h +++ b/esp32/serverstask.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/sigfox.mk b/esp32/sigfox.mk new file mode 100644 index 0000000000..7cb17d6cb2 --- /dev/null +++ b/esp32/sigfox.mk @@ -0,0 +1,24 @@ +ifeq ($(BOARD), $(filter $(BOARD), SIPY)) +SFX_OBJ += $(addprefix $(BUILD)/, $(APP_SIGFOX_SRC_SIPY_C:.c=.o) $(APP_SIGFOX_TARGET_SRC_C:.c=.o) $(APP_SIGFOX_SPI_SRC_C:.c=.o)) +endif +ifeq ($(BOARD), $(filter $(BOARD), LOPY4 FIPY)) +SFX_OBJ += $(addprefix $(BUILD)/, $(APP_SIGFOX_SRC_FIPY_LOPY4_C:.c=.o) $(APP_SIGFOX_SPI_SRC_C:.c=.o)) +endif + +OBJ += $(SFX_OBJ) + +# the build process generates .d files and expects the same directory structure in $(BUILD) as it is in the sources, so we need to mkdir them +SFX_DEP_DIRS := $(BUILD)/sigfox $(BUILD)/sigfox/src $(BUILD)/sigfox/src/targets $(BUILD)/lora +$(SFX_DEP_DIRS): + $(MKDIR) -p $@ + +all: $(SFX_DEP_DIRS) $(BUILD)/sigfox/sigfox.a + +# $(SFX_OBJ): | CHECK_DEP +# $(SFX_OBJ): | $(GEN_PINS_HDR) +$(SFX_OBJ): | $(HEADER_BUILD)/qstrdefs.generated.h $(HEADER_BUILD)/mpversion.h + +$(BUILD)/sigfox/sigfox.a: $(SFX_OBJ) + $(ECHO) "AR $@" + $(Q) rm -f $@ + $(Q) $(AR) cru $@ $^ diff --git a/esp32/sigfox/.gitignore b/esp32/sigfox/.gitignore new file mode 100644 index 0000000000..8eba6c8dd4 --- /dev/null +++ b/esp32/sigfox/.gitignore @@ -0,0 +1 @@ +src/ diff --git a/esp32/sigfox/README b/esp32/sigfox/README new file mode 100644 index 0000000000..80418deb3d --- /dev/null +++ b/esp32/sigfox/README @@ -0,0 +1,26 @@ +This directory contains the sigfox support. + +There are three prebuilt libraries for SIPY, LOPY4, and FIPY. + +@Pycom In order to build these libraries execute the following steps using the private pyupython repository: + +git clone -b sigfox git@github.com:pycom/pyupython.git src +cd src +git checkout 9a5e7a9b +cd ../.. +make BOARD=LOPY4 TARGET=sigfox +make BOARD=FIPY TARGET=sigfox +make BOARD=SIPY TARGET=sigfox +./get_sigfox_libs.py + +Now you see the updated .a files with + +git status sigfox + +which can be PR-ed in parallel with any sigfox code changes. + +If you update the sigfox code, be sure to: + +a) PR your sigfox changes to pyupython +b) PR the .a files to Firmware-Development and +c) update the git hash further up in this README file, so it is clear from which commit the libraries were built diff --git a/esp32/sigfox/modsigfox.h b/esp32/sigfox/modsigfox.h index 3e5f63d69b..eee2292b42 100644 --- a/esp32/sigfox/modsigfox.h +++ b/esp32/sigfox/modsigfox.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/sigfox/modsigfox_FIPY.a b/esp32/sigfox/modsigfox_FIPY.a new file mode 100644 index 0000000000..d579f9a157 Binary files /dev/null and b/esp32/sigfox/modsigfox_FIPY.a differ diff --git a/esp32/sigfox/modsigfox_LOPY4.a b/esp32/sigfox/modsigfox_LOPY4.a new file mode 100644 index 0000000000..34c56ab98e Binary files /dev/null and b/esp32/sigfox/modsigfox_LOPY4.a differ diff --git a/esp32/sigfox/modsigfox_SIPY.a b/esp32/sigfox/modsigfox_SIPY.a new file mode 100644 index 0000000000..948e803688 Binary files /dev/null and b/esp32/sigfox/modsigfox_SIPY.a differ diff --git a/esp32/sigfox/modsigfox_fipy.a b/esp32/sigfox/modsigfox_fipy.a deleted file mode 100644 index 6a1f684a9b..0000000000 Binary files a/esp32/sigfox/modsigfox_fipy.a and /dev/null differ diff --git a/esp32/sigfox/modsigfox_lopy4.a b/esp32/sigfox/modsigfox_lopy4.a deleted file mode 100644 index 9f16878e0a..0000000000 Binary files a/esp32/sigfox/modsigfox_lopy4.a and /dev/null differ diff --git a/esp32/sigfox/modsigfox_sipy.a b/esp32/sigfox/modsigfox_sipy.a deleted file mode 100644 index fd2eaf3536..0000000000 Binary files a/esp32/sigfox/modsigfox_sipy.a and /dev/null differ diff --git a/esp32/telnet/telnet.c b/esp32/telnet/telnet.c index f26c9d5a84..91972ecdfe 100644 --- a/esp32/telnet/telnet.c +++ b/esp32/telnet/telnet.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -154,7 +154,7 @@ static void telnet_reset_buffer (void); ******************************************************************************/ void telnet_init (void) { // allocate memory for the receive buffer (from the RTOS heap) - telnet_data.rxBuffer = heap_caps_malloc(TELNET_RX_BUFFER_SIZE, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); + telnet_data.rxBuffer = malloc(TELNET_RX_BUFFER_SIZE); telnet_data.state = E_TELNET_STE_DISABLED; } diff --git a/esp32/telnet/telnet.h b/esp32/telnet/telnet.h index 89f8a0e5b4..754f69b7e9 100644 --- a/esp32/telnet/telnet.h +++ b/esp32/telnet/telnet.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/tools/appsign.sh b/esp32/tools/appsign.sh index 0828d4d1b0..ba85a3091a 100644 --- a/esp32/tools/appsign.sh +++ b/esp32/tools/appsign.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/flasher.py b/esp32/tools/flasher.py index 94d8bcaebd..420223bd7d 100644 --- a/esp32/tools/flasher.py +++ b/esp32/tools/flasher.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/fw_updater/pypic.py b/esp32/tools/fw_updater/pypic.py index a35469885e..d0701a4637 100755 --- a/esp32/tools/fw_updater/pypic.py +++ b/esp32/tools/fw_updater/pypic.py @@ -1,4 +1,11 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python + +# Copyright (c) 2016-2020, Pycom Limited. +# +# This software is licensed under the GNU GPL version 3 or any +# later version, with permitted additional terms. For more information +# see the Pycom Licence v1.0 document supplied with this file, or +# available at https://www.pycom.io/opensource/licensing from __future__ import print_function @@ -13,7 +20,7 @@ from local_settings import DEBUG except: DEBUG = False -__version__ = '0.9.2' +__version__ = '0.9.3' CMD_PEEK = (0x0) CMD_POKE = (0x01) @@ -45,6 +52,7 @@ ADRESL_ADDR = (0x09B) ADRESH_ADDR = (0x09C) +TRISA_ADDR = (0x08C) TRISC_ADDR = (0x08E) PORTA_ADDR = (0x00C) @@ -77,7 +85,7 @@ def exit_with_error(code, msg): def warn(msg): eprint('warning:', msg) - + def print_debug(msg): if DEBUG: eprint(msg) @@ -89,12 +97,11 @@ def __init__(self, port): # we need bytesize to be 5 bits in order for the PIC to process the commands try: self.serial = serial.Serial(port, baudrate=115200, bytesize=serial.FIVEBITS, timeout=0.25, exclusive=True) - print_debug("Connected in exclusive mode") connected = True except Exception as e: connected = False - if not connected: print_debug("Not connecting in exclusive mode because: %s" % str(e)) + if not connected: try: self.serial = serial.Serial(port, baudrate=115200, bytesize=serial.FIVEBITS, timeout=0.25) except Exception as e: @@ -109,31 +116,43 @@ def __init__(self, port): except Exception: pass - def _write(self, data, read=True): + def _write(self, data, read=True, num_read_bytes=1): self.serial.write(data) if read: r_data = self.serial.read(2) if not r_data: raise Exception('Timeout while waiting for Rx data') - return struct.unpack('B', r_data[0])[0] + if num_read_bytes == 2: + (b1, b2) = struct.unpack('BB', r_data) + return 256 * b2 + b1 + else: + if sys.version_info[0] < 3: + return struct.unpack('B', r_data[0])[0] + else: + return r_data[0] + + def _flush(self, num_read_bytes=10): + r_data = self.serial.read(num_read_bytes) + # print(r_data) + return - def _send_cmd(self, cmd): - return self._write(bytearray([cmd])) + def _send_cmd(self, cmd, num_read_bytes=1): + return self._write(bytearray([cmd]), True, num_read_bytes) def read_hw_version(self): - return self._send_cmd(CMD_HW_VER) + return self._send_cmd(CMD_HW_VER, 2) def read_fw_version(self): - return self._send_cmd(CMD_FW_VER) + return self._send_cmd(CMD_FW_VER, 2) def read_product_id(self): - return self._send_cmd(CMD_PROD_ID) + return self._send_cmd(CMD_PROD_ID, 2) def peek_memory(self, addr): return self._write(bytearray([CMD_PEEK, addr & 0xFF, (addr >> 8) & 0xFF])) def poke_memory(self, addr, value): - self._write(bytearray([CMD_POKE, addr & 0xFF, (addr >> 8) & 0xFF, value & 0xFF]), False) + self._write(bytearray([CMD_POKE, addr & 0xFF, (addr >> 8) & 0xFF, value & 0xFF]), False) def magic_write_read(self, addr, _and=0xFF, _or=0, _xor=0): return self._write(bytearray([CMD_MAGIC, addr & 0xFF, (addr >> 8) & 0xFF, _and & 0xFF, _or & 0xFF, _xor & 0xFF])) @@ -163,6 +182,11 @@ def reset_pycom_module(self): self.set_bits_in_memory(TRISC_ADDR, 1 << 5) def enter_pycom_programming_mode(self, reset=True): + print_debug("Entering programming mode with reset={}".format(reset)) + # make RA5 an output + self.mask_bits_in_memory(TRISA_ADDR, ~(1 << 5)) + # drive RA5 low + self.mask_bits_in_memory(PORTA_ADDR, ~(1 << 5)) # make RC0 an output self.mask_bits_in_memory(TRISC_ADDR, ~(1 << 0)) # set RC0 low @@ -173,13 +197,20 @@ def enter_pycom_programming_mode(self, reset=True): # We should keep RC0 low at this point in case someone # presses the reset button before the firmware upgrade # as this is mandatory for the regular expansion board + self._flush() def exit_pycom_programming_mode(self, reset=True): + print_debug("Leaving programming mode with reset={}".format(reset)) + # make RA5 an output + self.mask_bits_in_memory(TRISA_ADDR, ~(1 << 5)) + # drive RA5 high + self.set_bits_in_memory(PORTA_ADDR, 1 << 5) # make RC0 an input # This will prevent issues with the RGB LED self.set_bits_in_memory(TRISC_ADDR, 1 << 0) if reset: self.reset_pycom_module() + self._flush() def isdetected(self): return self.detected @@ -210,6 +241,11 @@ def main(args): elif args.exit: pic.exit_pycom_programming_mode(not args.noreset) + # print debug info about current PIC product + print_debug("read_product_id(): 0x%X" % pic.read_product_id()) + print_debug("read_hw_version(): 0x%X" % pic.read_hw_version()) + print_debug("read_fw_version(): 0x%X" % pic.read_fw_version()) + pic.close() diff --git a/esp32/tools/fw_updater/updater.py b/esp32/tools/fw_updater/updater.py index 40525beffd..401330c2cd 100755 --- a/esp32/tools/fw_updater/updater.py +++ b/esp32/tools/fw_updater/updater.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python -# Copyright (c) 2016-2019, Pycom Limited. +# Copyright (c) 2016-2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information @@ -12,7 +12,7 @@ import argparse import base64 import binascii -import cStringIO +from io import BytesIO, StringIO import json import os import re @@ -43,9 +43,9 @@ FAST_BAUD_RATE = 921600 MAXPICREAD_BAUD_RATE = 230400 -LORA_REGIONS = ["EU868", "US915", "AS923", "AU915"] +LORA_REGIONS = ["EU868", "US915", "AS923", "AU915", "IN865"] -PIC_BOARDS = ["04D8:F013", "04D8:F012", "04D8:EF98", "04D8:EF38"] +PIC_BOARDS = ["04D8:F013", "04D8:F012", "04D8:EF98", "04D8:EF38", "04D8:ED14"] PARTITIONS = { 'secureboot' : ["0x0", "0x8000"], 'bootloader' : ["0x1000", "0x7000"], @@ -97,11 +97,18 @@ def eprint(*args, **kwargs): def print_exception(e): if DEBUG: - print_exc(e) + try: + if sys.version_info[0] < 3: + print_exc(e) + else: + print_exc() + except Exception as ex: + print_debug('Exception: {}'.format(e)) + print_debug('Exception exception: {}'.format(ex)) def print_debug(msg, show=DEBUG): - if show: + if show: eprint(msg) @@ -114,7 +121,7 @@ def print_debug(msg, show=DEBUG): def hr_size(size): - + if humanfriendly_available: return humanfriendly.format_size(size, binary=True) else: @@ -152,26 +159,27 @@ def load_tar(fileobj, prog, secure=False): if fsize == 0x800000: try: if secure: - script_file = json.load(tar.extractfile("script_8MB_enc")) + script_file = json.loads(tar.extractfile("script_8MB_enc").read().decode('UTF-8')) else: - script_file = json.load(tar.extractfile("script_8MB")) + script_file = json.loads(tar.extractfile("script_8MB").read().decode('UTF-8')) except: print_debug("Error Loading script_8MB ... defaulting to legacy script2!", True) legacy = True elif fsize == 0x400000: try: if secure: - script_file = json.load(tar.extractfile("script_4MB_enc")) + script_file = json.load(tar.extractfile("script_4MB_enc").read().decode('UTF-8')) else: - script_file = json.load(tar.extractfile("script_4MB")) - except: + script_file = json.load(tar.extractfile("script_4MB").read().decode('UTF-8')) + except Exception as e: + print_exception(e) print_debug("Error Loading script_4MB ... defaulting to legacy script2!", True) legacy = True else: - return RuntimeError("Cannot Detect Flash Size! .. Aborting") + return RuntimeError("Cannot detect flash size! .. Aborting") if legacy: - script_file = json.load(tar.extractfile("script2")) + script_file = json.loads(tar.extractfile("script2").read().decode('UTF-8')) version = script_file.get('version') if version is not None: @@ -182,7 +190,10 @@ def load_tar(fileobj, prog, secure=False): else: raise ValueError('version not found in script2') - script = script_file.get('script') + try: + script = script_file.get('script') + except Exception as e: + print_exception(e) if script is None: raise ValueError('script not found in script2') @@ -191,10 +202,11 @@ def load_tar(fileobj, prog, secure=False): return e except: try: - script = json.load(tar.extractfile("script")) + script = json.loads(tar.extractfile("script").read().decode('UTF-8')) except Exception as e: script = e print_exception(e) + raise ValueError("Your board is not supported by this firmware package") try: for i in range(len(script)): if script[i][0] == 'w' or script[i][0] == 'o': @@ -203,14 +215,14 @@ def load_tar(fileobj, prog, secure=False): except Exception as e: script = e print_exception(e) - + tar.close() return script class NPyProgrammer(object): - def __init__(self, port, baudrate, continuation=False, pypic=False, debug=False, reset=False, resultUpdateList = None, connect_read = False): + def __init__(self, port, baudrate, continuation=False, pypic=False, debug=False, reset=False, resultUpdateList=None, connect_read=False): self.__debug = debug self.__current_baudrate = self.__baudrate = baudrate self.__pypic = pypic @@ -222,9 +234,9 @@ def __init__(self, port, baudrate, continuation=False, pypic=False, debug=False, self.esp_port = port.lower() else: self.esp_port = port - + print_debug("Connecting to ESP32 with baudrate: %d" % self.__baudrate, self.__debug) - + if continuation == False: if (self.__pypic): self.enter_pycom_programming_mode() @@ -246,10 +258,10 @@ def __init__(self, port, baudrate, continuation=False, pypic=False, debug=False, def is_pypic(self): return self.__pypic - + def get_resultUpdateList(self): return self.__resultUpdateList - + def get_baudrate(self, read=False): if self.__pypic and read and self.__baudrate > MAXPICREAD_BAUD_RATE: return MAXPICREAD_BAUD_RATE @@ -269,13 +281,13 @@ def read(self, offset, size): ret_val = self.esp.read_flash(offset, size, resultUpdateList=self.__resultUpdateList, partition=self.partition_name(offset)) self.set_baudrate(False) return ret_val - + def check_partition(self, partition): if PARTITIONS.get(partition) is None: return False else: return True - + def partition_name(self, offset): if offset > 0: for partition in PARTITIONS.keys(): @@ -291,7 +303,7 @@ def int_flash_size(self): args.compress = True args.verify = False args.no_stub = False - + if args.flash_size == 'detect': esptool.detect_flash_size(self.esp, args) self.__flash_size = args.flash_size @@ -303,20 +315,20 @@ def int_flash_size(self): return int_flash_size def erase(self, offset, section_size, ui_label=None, updateList=False): - msg = "Erasing %s at address 0x%08X" % (hr_size(section_size), offset) + msg = "Erasing %s at address 0x%08X" % (hr_size(section_size), int(offset)) if ui_label is None: print(msg) else: ui_label.setText(msg) if updateList and self.__resultUpdateList is not None: self.__resultUpdateList.append("Erased %s at address 0x%08X" % (hr_size(section_size), offset)) - + MAX_SECTION_SIZE = 0x380000 - offset = (offset // 4096) * 4096 - iterations = (section_size + MAX_SECTION_SIZE - 1) // MAX_SECTION_SIZE + offset = int((offset // 4096) * 4096) + iterations = int((section_size + MAX_SECTION_SIZE - 1) // MAX_SECTION_SIZE) for x in range(iterations): s = min(section_size, MAX_SECTION_SIZE) - s = ((s + 4095) // 4096) * 4096 + s = int(((s + 4095) // 4096) * 4096) # We'll give it 3 attempts, if it still fails we lost the connection try: self.esp.erase_region(offset, s, progress_fs=self.__progress_fs) @@ -365,7 +377,7 @@ def write(self, offset, contents, compress=True, flash_size='detect', std_out=No self.__flash_size = args.flash_size self.set_baudrate(False) - fmap = cStringIO.StringIO(contents) + fmap = BytesIO(contents) args.addr_filename = [[offset, fmap]] if std_out is not None: sys.stdout = std_out @@ -385,7 +397,7 @@ def write(self, offset, contents, compress=True, flash_size='detect', std_out=No fmap.close() if first_exception is not None: raise first_exception - + def detect_flash_size(self): args = Args() args.flash_size = 'detect' @@ -396,7 +408,7 @@ def detect_flash_size(self): args.no_stub = False esptool.detect_flash_size(self.esp, args) return args.flash_size - + def write_script(self, offset, contents, config_block, overwrite=False, size=None, ui_label=None, file_name=None): if overwrite or size is None: self.write(offset, contents, ui_label=ui_label, file_name=file_name) @@ -412,7 +424,7 @@ def write_script(self, offset, contents, config_block, overwrite=False, size=Non args.compress = True args.verify = False args.no_stub = False - + if args.flash_size == 'detect': esptool.detect_flash_size(self.esp, args) self.__flash_size = args.flash_size @@ -423,7 +435,7 @@ def write_script(self, offset, contents, config_block, overwrite=False, size=Non int_flash_size = int(str_flash_size.replace('MB', '')) * 0x100000 except: int_flash_size = (4 * 0x100000) if args.flash_size != '8MB' else (8 * 0x100000) - + cb_start = int(PARTITIONS.get('config')[0], 16) cb_len = int(PARTITIONS.get('config')[1], 16) cb_end = cb_start + cb_len @@ -437,7 +449,7 @@ def write_script(self, offset, contents, config_block, overwrite=False, size=Non elif offset < cb_end and finish_addr > cb_start: if offset >= cb_start and finish_addr <= cb_end: print_debug("Offset[0x%X] until finish_addr[0x%X] would only write within the CB! Skipping..." % (offset, finish_addr), self.__debug) - else: + else: print_debug("Offset[0x%X] + Content[%s] would overwrite CB! It ends at: 0x%X" % (offset, hr_size(len(contents)), finish_addr), self.__debug) if config_block is None: print_debug("I need to read the config block because I didn't receive it as a parameter", self.__debug) @@ -453,21 +465,20 @@ def write_script(self, offset, contents, config_block, overwrite=False, size=Non else: print_debug("Offset[0x%X] + Content[%s] finish at: 0x%X" % (offset, hr_size(len(contents)), finish_addr), self.__debug) self.write(offset, contents.ljust(size, b'\xFF'), flash_size=args.flash_size, ui_label=ui_label, file_name=file_name) - + def write_remote(self, contents): cb_start = int(PARTITIONS.get('config')[0], 16) cb_len = int(PARTITIONS.get('config')[1], 16) config_block = self.read(cb_start, cb_len) self.write(cb_start, contents[0:52] + config_block[52:]) - - def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui_label=None, progress_fs=None): + + def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui_label=None, progress_fs=None, erase_nvs=False): self.__progress_fs = progress_fs - print_debug('script type: {}'.format(type(script))) if script is None: raise ValueError('Invalid or no script file in firmware package!') if DEBUG: for instruction in script: - print_debug('Instruction: {} {}'.format(instruction[0],instruction[1])) + print_debug('Instruction: {} {}'.format(instruction[0], instruction[1])) ota_updated = False ota = None img_size = 0xffffffff @@ -475,10 +486,12 @@ def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui for instruction in script: if instruction[1] == 'fs' or instruction[1] == 'fs1': erase_fs = (instruction[0] == 'e') + elif instruction[1] == 'nvs': + erase_nvs = (instruction[0] == 'e') elif instruction[1] == 'all': erase_fs = False + erase_nvs = False no_erase = not (instruction[0] == 'e') - start_time = time.time() total_size = 0 for instruction in script: @@ -489,7 +502,6 @@ def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui if instruction[1] == 'fs' or instruction[1] == 'fs1': continue if instruction[1] == 'all': - print_debug("Erasing all...", self.__debug) self.erase_all(ui_label=ui_label) ota_updated = True continue @@ -512,7 +524,7 @@ def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui if instruction1 <= int(PARTITIONS.get('otadata')[0], 16) and instruction1 + instruction2 >= int(PARTITIONS.get('otadata')[0], 16) + int(PARTITIONS.get('otadata')[1], 16): ota_updated = True if ota_updated: - print_debug("OTA partition has been erased.", self.__debug) + print_debug("OTA partition has been erased.", self.__debug) total_size += instruction2 self.erase(instruction1, instruction2, ui_label=ui_label) @@ -521,9 +533,11 @@ def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui self.__resultUpdateList.append('Erased {} in {}'.format(humanfriendly.format_size(total_size, binary=True), humanfriendly.format_timespan(time.time() - start_time))) else: self.__resultUpdateList.append('Erased {} in {0:.2f} seconds'.format(hr_size(total_size), time.time() - start_time)) - + if erase_fs: self.erase_fs(chip_id, ui_label=ui_label) + if erase_nvs: + self.erase(int(PARTITIONS.get('nvs')[0], 16), int(PARTITIONS.get('nvs')[1], 16), ui_label=ui_label, updateList = True) for instruction in script: if instruction[0].split(':', 2)[0] == 'w' or instruction[0].split(':', 2)[0] == 'o': @@ -544,7 +558,7 @@ def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui ota = False img_size = len(instruction[2]) psize = int(PARTITIONS.get(instruction[1])[1], 16) - if instruction[1] == "all": + if instruction[1] == "all": psize = self.int_flash_size() instruction1 = PARTITIONS.get(instruction[1])[0] elif instruction[1] == 'cb': @@ -561,15 +575,15 @@ def run_script(self, script, config_block=None, erase_fs=False, chip_id=None, ui self.write_script(int_instr1, instruction[2], config_block, instruction[0].split(':', 2)[0] == 'o', size=psize, ui_label=ui_label, file_name=file_name) if (int_instr1 <= int(PARTITIONS.get('otadata')[0], 16)) and (int_instr1 + (len(instruction[2]) if psize is None else psize) >= int(PARTITIONS.get('otadata')[0], 16) + int(PARTITIONS.get('otadata')[1], 16)): ota_updated = True - print_debug("OTA partition has been written.", self.__debug) + print_debug("OTA partition has been written.", self.__debug) elif instruction[0] != 'e': raise ValueError('Invalid script command %s' % instruction[0].split(':', 2)[0]) if ota is not None and not ota_updated: self.set_ota(ota, img_size, ui_label=ui_label) - + def set_ota(self, ota, image_size, ui_label=None): - ota_signature = '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' - crc32_header = '\xff\xff\xff\xff' + ota_signature = b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' + crc32_header = b'\xff\xff\xff\xff' if ota: ota_data = struct.pack('<5I16s', 1, 0, 0, image_size, 0, ota_signature) ota_crc32 = (binascii.crc32(crc32_header + ota_data) % (1 << 32)) @@ -579,7 +593,7 @@ def set_ota(self, ota, image_size, ui_label=None): if self.__resultUpdateList is not None: self.__resultUpdateList.append("Booting from partition: ota_0") print_debug("Setting otadata partition to boot from ota_0", self.__debug) - self.write(int(PARTITIONS.get('otadata')[0], 16), ota_part.ljust(int(PARTITIONS.get('otadata')[1], 16), '\xff')) + self.write(int(PARTITIONS.get('otadata')[0], 16), ota_part.ljust(int(PARTITIONS.get('otadata')[1], 16), b'\xff')) else: ota_data = struct.pack('<5I16s', 0, 1, 0, image_size, 0, ota_signature) ota_crc32 = (binascii.crc32(crc32_header + ota_data) % (1 << 32)) @@ -589,8 +603,8 @@ def set_ota(self, ota, image_size, ui_label=None): if self.__resultUpdateList is not None: self.__resultUpdateList.append("Booting from partition: factory") print_debug("Setting otadata partition to boot from factory", self.__debug) - self.write(int(PARTITIONS.get('otadata')[0], 16), ota_part.ljust(int(PARTITIONS.get('otadata')[1], 16), '\xff')) - + self.write(int(PARTITIONS.get('otadata')[0], 16), ota_part.ljust(int(PARTITIONS.get('otadata')[1], 16), b'\xff')) + def erase_sytem_mem(self): # Erase first 3.5Mb (this way fs and MAC address will be untouched) self.erase(0, 0x3100000) @@ -602,7 +616,7 @@ def erase_fs(self, chip_id=None, ui_label=None, progress_fs=None): print_debug('chip_id = {}'.format(chip_id)) if self.int_flash_size() == 0x800000: print_debug("Erasing 8MB device flash fs", self.__debug) - #self.erase(int(PARTITIONS.get('fs')[0], 16), int(PARTITIONS.get('fs')[1], 16), ui_label=ui_label, updateList=False) + # self.erase(int(PARTITIONS.get('fs')[0], 16), int(PARTITIONS.get('fs')[1], 16), ui_label=ui_label, updateList=False) section_size = int(PARTITIONS.get('fs1')[1], 16) / 8 for x in range(0, 8): self.erase(int(PARTITIONS.get('fs1')[0], 16) + (x * section_size), section_size, ui_label=ui_label, updateList=False) @@ -619,7 +633,7 @@ def erase_fs(self, chip_id=None, ui_label=None, progress_fs=None): self.__resultUpdateList.append("Erased {} flash fs in {}".format(humanfriendly.format_size(int(PARTITIONS.get('fs')[1], 16), binary=True), humanfriendly.format_timespan(time.time() - start_time))) else: self.__resultUpdateList.append("Erased {} flash fs in {0:.2f} seconds".format(hr_size(int(PARTITIONS.get('fs')[1], 16)), time.time() - start_time)) - + def get_chip_id(self): try: return self.esp.get_chip_description() @@ -642,7 +656,7 @@ def flash_bin(self, dest_and_file_pairs, ui_label=None, file_name=None, progress if args.flash_size == 'detect': esptool.detect_flash_size(self.esp, args) self.__flash_size = args.flash_size - + dest_and_file = list(dest_and_file_pairs) for i, el in enumerate(dest_and_file): @@ -656,18 +670,21 @@ def set_wifi_config(self, config_block, wifi_ssid=None, wifi_pwd=None, wifi_on_b config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00') if wifi_on_boot is not None: if wifi_on_boot == True: - wob = b'\xff' + wob = b'\xbb' else: - wob = b'\xfe' + wob = b'\xba' else: - wob = config_block[53] + if sys.version_info[0] < 3: + wob = config_block[53] + else: + wob = config_block[53].to_bytes(1, byteorder='little') if wifi_ssid is not None: - ssid = wifi_ssid.ljust(33, b'\x00') + ssid = wifi_ssid.encode().ljust(33, b'\x00') else: ssid = config_block[54:87] if wifi_pwd is not None: - pwd = wifi_pwd.ljust(65, b'\x00') + pwd = wifi_pwd.encode().ljust(65, b'\x00') else: pwd = config_block[87:152] @@ -678,6 +695,49 @@ def set_wifi_config(self, config_block, wifi_ssid=None, wifi_pwd=None, wifi_on_b +config_block[152:] return self.set_pybytes_config(new_config_block, force_update=True) + def set_lte_config(self, config_block, carrier=None, apn=None, lte_type=None, cid=None, band=None, reset=None): + config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00') + + if carrier is not None: + cb_carrier = str(carrier[0:128]).ljust(129, b'\x00') + else: + cb_carrier = config_block[634:763] + + if apn is not None: + cb_apn = str(apn[0:128]).ljust(129, b'\x00') + else: + cb_apn = config_block[763:892] + + if lte_type is not None: + cb_lte_type = str(lte_type[0:16]).ljust(17, b'\x00') + else: + cb_lte_type = config_block[892:909] + + if cid is not None: + cb_cid = struct.pack('>B', int(cid)) + else: + cb_cid = config_block[909] + + if band is not None: + cb_band = struct.pack('>B', int(band)) + else: + cb_band = config_block[910] + + if reset is not None: + cb_reset = struct.pack('>B', int(reset == 'True')) + else: + cb_reset = config_block[911] + + new_config_block = config_block[0:634] \ + +cb_carrier \ + +cb_apn \ + +cb_lte_type \ + +cb_cid \ + +cb_band \ + +cb_reset \ + +config_block[912:] + return self.set_pybytes_config(new_config_block, force_update=True) + def set_pycom_config(self, config_block, boot_fs_type=None): print_debug('This is set_pycom_config with boot_fs_type={} [{}]'.format(boot_fs_type, type(boot_fs_type))) config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00') @@ -702,10 +762,11 @@ def set_pycom_config(self, config_block, boot_fs_type=None): return self.set_pybytes_config(new_config_block, force_update=True) def print_cb(self, config_block): - for x in range(0, 20): - print(binascii.hexlify(config_block[x * 32:x * 32 + 32])) - - def set_pybytes_config(self, config_block, userid=None, device_token=None, mqttServiceAddress=None, network_preferences=None, extra_preferences=None, force_update=None): + if DEBUG: + for x in range(0, 30): + print(binascii.hexlify(config_block[x * 32:x * 32 + 32]).decode('UTF-8')) + + def set_pybytes_config(self, config_block, userid=None, device_token=None, mqttServiceAddress=None, network_preferences=None, extra_preferences=None, force_update=None, auto_start=None): config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00') if device_token is not None: token = str(device_token)[0:39].ljust(40, b'\x00') @@ -726,19 +787,33 @@ def set_pybytes_config(self, config_block, userid=None, device_token=None, mqttS nwp = str(network_preferences)[0:54].ljust(55, b'\x00') else: nwp = config_block[342:397] - + if extra_preferences is not None: ep = str(extra_preferences)[0:99].ljust(100, b'\x00') else: ep = config_block[397:497] - + if force_update is not None: if force_update: fu = b'\x01' else: fu = b'\x00' else: - fu = config_block[497] + if sys.version_info[0] < 3: + fu = config_block[497] + else: + fu = config_block[497].to_bytes(1, byteorder='little') + + if auto_start is not None: + if auto_start: + asf = b'\x01' + else: + asf = b'\x00' + else: + if sys.version_info[0] < 3: + asf = config_block[498] + else: + asf = config_block[498].to_bytes(1, byteorder='little') new_config_block = config_block[0:162] \ +token \ @@ -747,11 +822,12 @@ def set_pybytes_config(self, config_block, userid=None, device_token=None, mqttS +nwp \ +ep \ +fu \ - +config_block[498:] + +asf \ + +config_block[499:] # self.print_cb(new_config_block) return new_config_block - + def str2region(self, lora_region_str): if lora_region_str is not None: return { @@ -761,8 +837,8 @@ def str2region(self, lora_region_str): 'AS923' : LORAMAC_REGION_AS923 }.get(lora_region_str, 0xff) else: - return 0xff - + return 0xff + def region2str(self, lora_region_int): if lora_region_int is not None: return { @@ -773,19 +849,64 @@ def region2str(self, lora_region_int): }.get(lora_region_int, 'NONE') else: return None - + def set_lpwan_config(self, config_block, lora_region=None): config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00') if lora_region is not None: - region = chr(self.str2region(lora_region)) + if sys.version_info[0] < 3: + region = chr(self.str2region(lora_region)) + else: + region = self.str2region(lora_region).to_bytes(1, byteorder='little') else: - region = config_block[52] + if sys.version_info[0] < 3: + region = config_block[52] + else: + region = config_block[52].to_bytes(1, byteorder='little') new_config_block = config_block[0:52] \ +region \ +config_block[53:] return new_config_block + def set_sigfox_config(self, config_block, sid=None, pac=None, pubkey=None, privkey=None): + config_block = config_block.ljust(int(PARTITIONS.get('config')[1], 16), b'\x00') + if sid is not None: + if not len(sid)==8: + raise ValueError('ID must be 8 HEX characters') + sigid = bytearray.fromhex(sid).ljust(4, b'\x00') + else: + sigid = config_block[8:12] + + if pac is not None: + if not len(pac)==16: + raise ValueError('PAC must be 16 HEX characters') + spac = bytearray.fromhex(pac).ljust(8, b'\x00') + else: + spac = config_block[12:20] + + if privkey is not None: + if not len(privkey)==32: + raise ValueError('private key must be 32 HEX characters') + sprivkey = bytearray.fromhex(privkey).ljust(16, b'\x00') + else: + sprivkey = config_block[20:36] + + if pubkey is not None: + if not len(pubkey)==32: + raise ValueError('public key must be 32 HEX characters') + spubkey = bytearray.fromhex(pubkey).ljust(16, b'\x00') + else: + spubkey = config_block[36:52] + + new_config_block = config_block[0:8] \ + +sigid \ + +spac \ + + sprivkey \ + + spubkey \ + +config_block[52:] + return new_config_block + + def read_mac(self): # returns a tuple with (wifi_mac, bluetooth_mac) return self.esp.read_mac() @@ -836,7 +957,7 @@ def check_partition(partition): return False else: return True - + def check_lora_region(region): if region in LORA_REGIONS: @@ -874,17 +995,24 @@ def process_arguments(): subparsers.add_parser('chip_id', help='Show ESP32 chip_id') subparsers.add_parser('wmac', help='Show WiFi MAC') subparsers.add_parser('smac', help='Show LPWAN MAC') - subparsers.add_parser('sigfox', help='Show sigfox details') subparsers.add_parser('exit', help='Exit firmware update mode') if DEBUG: cmd_parser_bootpart = subparsers.add_parser('boot_part', add_help=False) # , help='Check / Set active boot partition') cmd_parser_bootpart.add_argument('-p', '--partition', default=None, help="Set the activate boot partition [factory or ota_0]") - + + cmd_parser_pycom = subparsers.add_parser('pycom', help='Check / Set pycom parameters') + cmd_parser_pycom.add_argument('--fs_type', default=None, help="Set the file system type ['FatFS' or 'LittleFS']") + cmd_parser_sigfox = subparsers.add_parser('sigfox', help='Show/Update sigfox details') + cmd_parser_sigfox.add_argument('--id', default=None, help='Update Sigfox id') + cmd_parser_sigfox.add_argument('--pac', default=None, help='Update Sigfox pac') + cmd_parser_sigfox.add_argument('--pubkey', default=None, help='Update Sigfox public key') + cmd_parser_sigfox.add_argument('--privkey', default=None, help='Update Sigfox private key') + cmd_parser_flash = subparsers.add_parser('flash', help='Write firmware image to flash') cmd_parser_flash.add_argument('-t', '--tar', default=None, help='perform the upgrade from a tar[.gz] file') cmd_parser_flash.add_argument('-f', '--file', default=None, help='flash binary file to a single partition') - cmd_parser_flash.add_argument('--secureboot', action='store_true', help='Flash Encrypted binaries if avialable') + cmd_parser_flash.add_argument('--secureboot', action='store_true', help='Flash Encrypted binaries if available') help_msg = 'The partition to flash (' for partition in PARTITIONS.keys(): help_msg += (partition + ", ") @@ -910,7 +1038,8 @@ def process_arguments(): cmd_parser_wifi = subparsers.add_parser('wifi', help='Get/Set default WIFI parameters') cmd_parser_wifi.add_argument('--ssid', default=None, help='Set Wifi SSID') cmd_parser_wifi.add_argument('--pwd', default=None, help='Set Wifi PWD') - cmd_parser_wifi.add_argument('--wob', type=str2bool, nargs='?', const=True, help='Set Wifi on boot') + # This doesn't really work as we updated the field to a bitfield + #cmd_parser_wifi.add_argument('--wob', type=str2bool, nargs='?', const=True, help='Set Wifi on boot') cmd_parser_pybytes = subparsers.add_parser('pybytes', help='Read/Write pybytes configuration') cmd_parser_pybytes.add_argument('--token', default=None, help='Set Device Token') @@ -918,6 +1047,13 @@ def process_arguments(): cmd_parser_pybytes.add_argument('--uid', default=None, help='Set userId') cmd_parser_pybytes.add_argument('--nwprefs', default=None, help='Set network preferences') cmd_parser_pybytes.add_argument('--extraprefs', default=None, help='Set extra preferences') + cmd_parser_pybytes.add_argument('--carrier', default=None, help='Set LTE carrier') + cmd_parser_pybytes.add_argument('--apn', default=None, help='Set LTE apn') + cmd_parser_pybytes.add_argument('--type', default=None, help='Set LTE type') + cmd_parser_pybytes.add_argument('--cid', default=None, help='Set LTE cid') + cmd_parser_pybytes.add_argument('--band', default=None, help='Set LTE band') + cmd_parser_pybytes.add_argument('--lte_reset', default=None, type=str2bool, nargs='?', const=True, help='Set LTE reset') + cmd_parser_pybytes.add_argument('--auto_start', default=None, type=str2bool, nargs='?', const=True, help='Set Pybytes auto_start') cmd_parser_cb = subparsers.add_parser('cb', help='Read/Write config block') cmd_parser_cb.add_argument('-f', '--file', default=None, help='name of the backup file (default: .cb)') @@ -954,7 +1090,7 @@ def process_arguments(): # except Exception as e: # print_exception(e) # raise e -# +# try: if args.command == 'boot_part' and args.partition is not None: if args.partition != 'factory' and args.partition != 'ota_0': @@ -981,19 +1117,19 @@ def process_arguments(): raise ValueError('Cannot backup and restore at the same time') if (hasattr(args, "command") and args.command == 'lpwan' and hasattr(args, "region") and args.region is not None): if (not check_lora_region(args.region)): - err_msg = 'Invalid LoRa region ' + args.region + ' must be one of:' + err_msg = 'Invalid LoRa region ' + args.region + ' must be one of:' for region in LORA_REGIONS: err_msg += " " + region raise ValueError(err_msg) if (args.command == 'copy' and (not hasattr(args, "partition") or args.partition is None)): - err_msg = 'partition must be one of:' + err_msg = 'partition must be one of:' for partition in PARTITIONS.keys(): err_msg += " " + partition raise ValueError(err_msg) - + if (args.command == 'copy' and hasattr(args, "partition") and args.partition is not None): if (not check_partition(args.partition)): - err_msg = 'Invalid partition ' + args.partition + ' must be one of:' + err_msg = 'Invalid partition ' + args.partition + ' must be one of:' for partition in PARTITIONS.keys(): err_msg += " " + partition raise ValueError(err_msg) @@ -1025,11 +1161,14 @@ def print_result(result): def main(): try: args = process_arguments() - + if args.command == 'list': list_usbid() sys.exit(0) - new_stream = cStringIO.StringIO() + if sys.version_info[0] < 3: + new_stream = BytesIO() + else: + new_stream = StringIO() old_stdout = sys.stdout if (args.ftdi): pypic = False @@ -1042,14 +1181,14 @@ def main(): if not args.quiet: if (pypic): print("Running in PIC mode") - else: + else: print("Running in FTDI mode") if args.command == 'erase_all' and not args.quiet: print("Erasing the board can take up to 40 seconds.") if pypic == True: args.continuation = False - + if not (DEBUG or args.debug) and (args.verbose == False): sys.stdout = new_stream nPy = NPyProgrammer(args.port, args.speed, args.continuation, pypic, args.debug, args.reset) @@ -1064,13 +1203,13 @@ def progress_fs(msg): padding = '\b' * len(msg) sys.stderr.write(msg + padding) sys.stderr.flush() - + if args.tar is not None: try: tar_file = open(args.tar, "rb") script = load_tar(tar_file, nPy, args.secureboot) if not args.quiet: - #sys.stdout = old_stdout + # sys.stdout = old_stdout sys.stderr.flush() nPy.run_script(script, progress_fs=progress_fs) else: @@ -1114,13 +1253,13 @@ def progress_fs(msg): if not args.quiet: sys.stdout = old_stdout print("Board programmed successfully") - + elif args.command == 'write_remote': nPy.write_remote(base64.b64decode(args.contents)) if not args.quiet: sys.stdout = old_stdout print("Board configuration programmed successfully") - + elif args.command == 'chip_id': sys.stdout = old_stdout print(nPy.get_chip_id()) @@ -1142,7 +1281,22 @@ def progress_fs(msg): ota_data = nPy.read(int(PARTITIONS.get('otadata')[0], 16), int(PARTITIONS.get('otadata')[1], 16)) eprint(binascii.hexlify(ota_data[0:25])) - elif args.command == 'lpwan' or args.command == 'sigfox': + elif args.command == 'sigfox': + config_block = nPy.read(int(PARTITIONS.get('config')[0], 16), int(PARTITIONS.get('config')[1], 16)) + if args.id is not None or args.pac is not None or args.pubkey is not None or args.privkey is not None: + new_config_block = nPy.set_sigfox_config(config_block, args.id, args.pac, args.pubkey, args.privkey) + nPy.write(int(PARTITIONS.get('config')[0], 16), new_config_block) + sys.stdout = old_stdout + if not args.quiet: + print("Sigfox credentials programmed successfully") + else: + sys.stdout = old_stdout + sid = binascii.hexlify(config_block[8:12]).decode('UTF-8').upper() + pac = binascii.hexlify(config_block[12:20]).decode('UTF-8').upper() + print("SID: %s" % sid) + print("PAC: %s" % pac) + + elif args.command == 'lpwan': config_block = nPy.read(int(PARTITIONS.get('config')[0], 16), int(PARTITIONS.get('config')[1], 16)) if hasattr(args, "region") and args.region is not None: new_config_block = nPy.set_lpwan_config(config_block, args.region) @@ -1159,24 +1313,24 @@ def progress_fs(msg): else: sys.stdout = old_stdout smac = mac_to_string(config_block[:8]) - sid = str(binascii.hexlify(config_block[8:12]).upper()) - pac = str(binascii.hexlify(config_block[12:20]).upper()) + sid = binascii.hexlify(config_block[8:12]).decode('UTF-8').upper() + pac = binascii.hexlify(config_block[12:20]).decode('UTF-8').upper() if hasattr(args, "lora_region") and args.lora_region: try: region = config_block[52] print(nPy.region2str(ord(region))) except: print("NONE") - elif args.command == 'sigfox': - print("SID: %s" % sid) - print("PAC: %s" % pac) else: print("SMAC: %s" % smac) print("SID: %s" % sid) print("PAC: %s" % pac) try: region = config_block[52] - print("LORA REGION=%s" % nPy.region2str(ord(region))) + if sys.version_info[0] < 3: + print("LORA REGION=%s" % nPy.region2str(ord(region))) + else: + print("LORA REGION=%s" % nPy.region2str(region)) except: print("LORA REGION=[not set]") @@ -1192,6 +1346,7 @@ def progress_fs(msg): if args.quiet: flash_progress = None else: + def flash_progress(progress, length): if humanfriendly_available: msg = 'Read %s from %s (%d %%)%s' % (humanfriendly.format_size(progress, keep_width=(progress > 1024000), binary=True), args.partition, progress * 100.0 / length, ' ' * 15) @@ -1215,7 +1370,7 @@ def flash_progress(progress, length): if not args.quiet: print('\rRead %d bytes at 0x%x in %.1f seconds (%.1f kbit/s)...' % (len(data), int(PARTITIONS.get(args.partition)[0], 16), t, len(data) / t * 8 / 1000)) - print('Partition saved to %s' % fname) + print('Partition saved to %s' % fname) except Exception as e: print_exception(e) raise e @@ -1223,11 +1378,13 @@ def flash_progress(progress, length): if partf is not None: partf.close() else: + def progress_fs(msg): msg = ' ' + msg + ' ' * 15 padding = '\b' * len(msg) sys.stderr.write(msg + padding) sys.stderr.flush() + try: t = time.time() partf = open(fname, "rb") @@ -1247,7 +1404,7 @@ def progress_fs(msg): except Exception as e: print_exception(e) raise e - + elif (args.command == 'cb'): if not (hasattr(args, 'file') and args.file is not None): wmac = mac_to_string(nPy.read_mac()) @@ -1264,7 +1421,7 @@ def progress_fs(msg): cbf.close() if not args.quiet: sys.stdout = old_stdout - print('Config block saved to %s' % fname) + print('Config block saved to %s' % fname) else: sys.stdout = old_stdout print(binascii.b2a_base64(config_block)) @@ -1331,7 +1488,7 @@ def progress_fs(msg): if not fname == '-': otaf = open(fname, "wb") ota = nPy.read(int(PARTITIONS.get('otadata')[0], 16), int(PARTITIONS.get('otadata')[1], 16)) - if not fname == '-': + if not fname == '-': otaf.write(binascii.b2a_base64(ota)) otaf.close() if not args.quiet: @@ -1375,22 +1532,57 @@ def progress_fs(msg): except: print("WIFI_PWD=[not set]") try: - wob = config_block[53] - if (wob == (b'\xfe')): + if sys.version_info[0] < 3: + wob = config_block[53] + else: + wob = config_block[53].to_bytes(1, byteorder='little') + print_debug('wob: {}'.format(wob)) + if (wob == (b'\xfe') or wob == (b'\xba')): print("WIFI_ON_BOOT=OFF") else: print("WIFI_ON_BOOT=ON") except: print("WIFI_ON_BOOT=[not set]") + elif args.command == 'pycom': + config_block = nPy.read(int(PARTITIONS.get('config')[0], 16), int(PARTITIONS.get('config')[1], 16)) + nPy.print_cb(config_block) + if (args.fs_type is not None): + new_config_block = nPy.set_pycom_config(config_block, args.fs_type) + nPy.print_cb(new_config_block) + nPy.write(int(PARTITIONS.get('config')[0], 16), new_config_block) + else: + sys.stdout = old_stdout + try: + if sys.version_info[0] < 3: + fs_type = config_block[533] + else: + fs_type = config_block[533].to_bytes(1, byteorder='little') + if fs_type == (b'\x00'): + print("fs_type=FatFS") + if fs_type == (b'\x01'): + print("fs_type=LittleFS") + if fs_type == (b'\xff'): + print("fs_type=[not set]") + except: + print("fs_type=[not set]") + elif args.command == 'pybytes': config_block = nPy.read(int(PARTITIONS.get('config')[0], 16), int(PARTITIONS.get('config')[1], 16)) if (hasattr(args, "token") and args.token is not None) \ or (hasattr(args, "mqtt") and args.mqtt is not None) \ or (hasattr(args, "uid") and args.uid is not None) \ or (hasattr(args, "nwprefs") and args.nwprefs is not None) \ + or (hasattr(args, "auto_start") and args.auto_start is not None) \ + or (hasattr(args, "carrier") and args.carrier is not None) \ + or (hasattr(args, "apn") and args.apn is not None) \ + or (hasattr(args, "type") and args.type is not None) \ + or (hasattr(args, "cid") and args.cid is not None) \ + or (hasattr(args, "band") and args.band is not None) \ + or (hasattr(args, "lte_reset") and args.lte_reset is not None) \ or (hasattr(args, "extraprefs") and args.extraprefs is not None): - new_config_block = nPy.set_pybytes_config(config_block, args.uid, args.token, args.mqtt, args.nwprefs, args.extraprefs, True) + new_config_block = nPy.set_pybytes_config(config_block, args.uid, args.token, args.mqtt, args.nwprefs, args.extraprefs, True, args.auto_start) + new_config_block = nPy.set_lte_config(new_config_block, args.carrier, args.apn, args.type, args.cid, args.band, args.reset) nPy.write(int(PARTITIONS.get('config')[0], 16), new_config_block) sys.stdout = old_stdout else: @@ -1422,11 +1614,13 @@ def progress_fs(msg): print("EXTRAPREFS=[not set]") elif args.command == 'erase_fs': + def progress_fs(msg): msg = msg + ' ' * 10 padding = '\b' * len(msg) sys.stderr.write(msg + padding) sys.stderr.flush() + try: nPy.erase_fs(progress_fs=progress_fs) if not args.quiet: @@ -1435,14 +1629,14 @@ def progress_fs(msg): except Exception as e: print_exception(e) raise e - + if (not (args.command == "list" or (hasattr(args, 'noexit') and args.noexit == True))) or args.command == 'exit': nPy.exit_pycom_programming_mode() except ValueError as e: print_exception(e) eprint(format(e)) - + except Exception as e: if DEBUG: print_exc(e) diff --git a/esp32/tools/idfVerCheck.sh b/esp32/tools/idfVerCheck.sh index 1ac3e3231b..3323cb8e0e 100644 --- a/esp32/tools/idfVerCheck.sh +++ b/esp32/tools/idfVerCheck.sh @@ -1,6 +1,6 @@ #!/bin/bash # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information @@ -8,26 +8,26 @@ # available at https://www.pycom.io/opensource/licensing # -IDF_VER="idf_v"$2 -CURR_VER="$(git --git-dir=$1/.git branch | grep \* | cut -d ' ' -f2)" +IDF_HASH=$2 +IDF_PATH=$1 +CURR_HASH=$(git -c core.abbrev=7 --git-dir=$IDF_PATH/.git rev-parse --short HEAD) -if [ "${CURR_VER}" = "${IDF_VER}" ]; then - echo "IDF Version OK!" +if [ "${CURR_HASH}" = "${IDF_HASH}" ]; then + echo "IDF Version OK! $IDF_HASH" exit 0 else - echo "Incompatible IDF version...Checking out IDF version $2!" - if ! git --git-dir=$1/.git --work-tree=$1 checkout ${IDF_VER} ; then - echo "Cannot checkout IDF version ${IDF_VER}!...Please make sure latest idf_v${IDF_VER} branch is fetched" >&2 - exit 1 - fi - cd ${IDF_PATH} - if ! git submodule sync ; then - echo "Cannot checkout IDF version ${IDF_VER}!...Please make sure latest idf_v${IDF_VER} branch is fetched" >&2 - exit 1 - fi - if ! git submodule update --init ; then - echo "Cannot checkout IDF version ${IDF_VER}!...Please make sure latest idf_v${IDF_VER} branch is fetched" >&2 - exit 1 - fi - exit 0 -fi \ No newline at end of file + echo " +Incompatible IDF git hash: + +$IDF_HASH is expected from IDF_HASH from Makefile, but +$CURR_HASH is what IDF_PATH=$IDF_PATH is pointing at. + +You should probably update one (or multiple) of: + * IDF_PATH environment variable + * IDF_HASH variable in esp32/Makefile + * IDF commit, e.g. +cd \$IDF_PATH && git checkout $IDF_HASH && git submodule sync && git submodule update --init --recursive && cd - + +" + exit 1 +fi diff --git a/esp32/tools/lopy_final_test_board_script.py b/esp32/tools/lopy_final_test_board_script.py index 810c24bf89..63e5a5be05 100644 --- a/esp32/tools/lopy_final_test_board_script.py +++ b/esp32/tools/lopy_final_test_board_script.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/lopy_initial_test_board_script.py b/esp32/tools/lopy_initial_test_board_script.py index 4507c1ac7f..0f47f653fa 100644 --- a/esp32/tools/lopy_initial_test_board_script.py +++ b/esp32/tools/lopy_initial_test_board_script.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/lopy_qa_test_board_script.py b/esp32/tools/lopy_qa_test_board_script.py index 278b30c5ce..144c972b5e 100644 --- a/esp32/tools/lopy_qa_test_board_script.py +++ b/esp32/tools/lopy_qa_test_board_script.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/lora/actility/actility.py b/esp32/tools/lora/actility/actility.py index 3ae8fa3b6c..bd98eb3232 100644 --- a/esp32/tools/lora/actility/actility.py +++ b/esp32/tools/lora/actility/actility.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/lora/certification/certification.py b/esp32/tools/lora/certification/certification.py index b132df1240..8c68811730 100644 --- a/esp32/tools/lora/certification/certification.py +++ b/esp32/tools/lora/certification/certification.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/mpy-build-check.sh b/esp32/tools/mpy-build-check.sh index 507822910d..5556936d2d 100644 --- a/esp32/tools/mpy-build-check.sh +++ b/esp32/tools/mpy-build-check.sh @@ -1,4 +1,7 @@ #!/bin/bash +# Check whether we should rebuild the frozen Micro Python code + +set -e BOARD="$1" RELEASE_TYP="$2" @@ -7,49 +10,50 @@ PY_PATH="./frozen" PY_DIRS="$(ls ${PY_PATH})" OS="$(uname)" if [ ${VARIANT} != "BASE" ] ; then - BUILD_DIR="build-${VARIANT}" + BUILD_DIR="build-${VARIANT}/${BOARD}/${RELEASE_TYP}" else - BUILD_DIR="build" + BUILD_DIR="build/${BOARD}/${RELEASE_TYP}" fi -#Script Has to be called from esp32 Dir +# Script has to be called from esp32 dir if ! [ $0 = "tools/mpy-build-check.sh" ]; then echo "Need to run as tools/mpy-build-check.sh!" >&2 exit 1 fi -#Check Board Type +# Check board type if [ "${BOARD}" != "WIPY" -a "${BOARD}" != "SIPY" -a "${BOARD}" != "LOPY" -a "${BOARD}" != "LOPY4" -a "${BOARD}" != "GPY" -a "${BOARD}" != "FIPY" ] ; then echo "Invalid Board name for MPY build!" >&2 exit 1 fi -BUILD_TIMESTAMP=./"${BUILD_DIR}"/${BOARD}"/"${RELEASE_TYP}"/"mpy_last_build_timestamp.TS - -#If Last mpy Build Timestamp Not avialable create it -if [ ! -d ${BUILD_DIR}/${BOARD}/${RELEASE_TYP} ] ; then - exit 0 -else - if [ ! -f ${BUILD_TIMESTAMP} ] ; then - $(touch ${BUILD_TIMESTAMP}) - fi -fi -#Get Current Timestamp +# Get current timestamp CURR_TS="$(date +"%s")" -MPY_PATH=./"${BUILD_DIR}"/"${BOARD}"/"${RELEASE_TYP}"/frozen_mpy +BUILD_TIMESTAMP="${BUILD_DIR}/mpy_last_build_timestamp.TS" + + +MPY_PATH="${BUILD_DIR}/frozen_mpy" if ! [ -d ${MPY_PATH} ] ; then - #Build Directory not created yet - #Update Last Build Timestamp - $(echo ${CURR_TS} > ${BUILD_TIMESTAMP}) + # Build directory does not exist + # Update last build timestamp + mkdir -p ${BUILD_DIR} + echo ${CURR_TS} > ${BUILD_TIMESTAMP} exit 0 fi -LAST_BUILD=$(<${BUILD_TIMESTAMP}) -#Check if any of Frozen Directorys has been updated.. Rebuild out Mpy files +# Get last build timestamp +if [ ! -f ${BUILD_TIMESTAMP} ] ; then + LAST_BUILD=0 +else + LAST_BUILD=$(<${BUILD_TIMESTAMP}) +fi + + +# Remove Mpy build directory if any of the frozen directories have been updated for dir in ${PY_DIRS} do if [[ "${dir}" =~ ^\\.* ]] ; then @@ -65,14 +69,14 @@ do if [[ ${TS} -gt ${LAST_BUILD} ]] ; then echo "Rebuilding frozen Code!" >&2 - #Remove all MPY out files to be rubuild again by Makefile - $(rm -rf ${MPY_PATH}) - #Update Last Build Timestamp - $(echo ${CURR_TS} > ${BUILD_TIMESTAMP}) + # Remove the build directory to trigger a rebuild from the Makefile + rm -rf ${MPY_PATH} + # Update last build timestamp + echo ${CURR_TS} > ${BUILD_TIMESTAMP} exit 0 fi done -#Update Last Build Timestamp -$(echo ${CURR_TS} > ${BUILD_TIMESTAMP}) +# Update last build timestamp +echo ${CURR_TS} > ${BUILD_TIMESTAMP} exit 0 diff --git a/esp32/tools/run_final_lopy_test.py b/esp32/tools/run_final_lopy_test.py index 905939871a..f16f1047c0 100644 --- a/esp32/tools/run_final_lopy_test.py +++ b/esp32/tools/run_final_lopy_test.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/run_initial_lopy_test.py b/esp32/tools/run_initial_lopy_test.py index ab7bf52099..ade3c20b4a 100644 --- a/esp32/tools/run_initial_lopy_test.py +++ b/esp32/tools/run_initial_lopy_test.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/run_initial_wipy_test.py b/esp32/tools/run_initial_wipy_test.py index 367240b0e2..c7769718f0 100644 --- a/esp32/tools/run_initial_wipy_test.py +++ b/esp32/tools/run_initial_wipy_test.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/run_qa_lopy_test.py b/esp32/tools/run_qa_lopy_test.py index b05e0fd4bb..6cca6ff692 100644 --- a/esp32/tools/run_qa_lopy_test.py +++ b/esp32/tools/run_qa_lopy_test.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/run_qa_wipy_test.py b/esp32/tools/run_qa_wipy_test.py index 5bbb192f44..75a95056dd 100644 --- a/esp32/tools/run_qa_wipy_test.py +++ b/esp32/tools/run_qa_wipy_test.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/wipy_initial_test_board_script.py b/esp32/tools/wipy_initial_test_board_script.py index 3e5102d926..61b79825d4 100644 --- a/esp32/tools/wipy_initial_test_board_script.py +++ b/esp32/tools/wipy_initial_test_board_script.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/tools/wipy_qa_test_board_script.py b/esp32/tools/wipy_qa_test_board_script.py index b7bb425480..c29e547300 100644 --- a/esp32/tools/wipy_qa_test_board_script.py +++ b/esp32/tools/wipy_qa_test_board_script.py @@ -1,5 +1,5 @@ # -# Copyright (c) 2019, Pycom Limited. +# Copyright (c) 2020, Pycom Limited. # # This software is licensed under the GNU GPL version 3 or any # later version, with permitted additional terms. For more information diff --git a/esp32/util/antenna.c b/esp32/util/antenna.c index 76539c3520..8b884081de 100644 --- a/esp32/util/antenna.c +++ b/esp32/util/antenna.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/antenna.h b/esp32/util/antenna.h index 13aa28269f..b5e9c7dcf2 100644 --- a/esp32/util/antenna.h +++ b/esp32/util/antenna.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/esp32chipinfo.c b/esp32/util/esp32chipinfo.c index 74e0c2fe9f..627e39f7e0 100644 --- a/esp32/util/esp32chipinfo.c +++ b/esp32/util/esp32chipinfo.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/esp32chipinfo.h b/esp32/util/esp32chipinfo.h index b6176b19a9..97957e6a86 100644 --- a/esp32/util/esp32chipinfo.h +++ b/esp32/util/esp32chipinfo.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/fifo.c b/esp32/util/fifo.c index dd3a00d47f..5c4592b36d 100644 --- a/esp32/util/fifo.c +++ b/esp32/util/fifo.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/fifo.h b/esp32/util/fifo.h index c06971be87..79fec735b3 100644 --- a/esp32/util/fifo.h +++ b/esp32/util/fifo.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/gccollect.c b/esp32/util/gccollect.c index 68cd326c1e..3446bcf923 100644 --- a/esp32/util/gccollect.c +++ b/esp32/util/gccollect.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/util/gccollect.h b/esp32/util/gccollect.h index c488034dd5..673c66f3c5 100644 --- a/esp32/util/gccollect.h +++ b/esp32/util/gccollect.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/util/help.c b/esp32/util/help.c index f1c7d48fa4..ed8ab8fbff 100644 --- a/esp32/util/help.c +++ b/esp32/util/help.c @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/esp32/util/mperror.c b/esp32/util/mperror.c index a501160abb..b963b45a18 100644 --- a/esp32/util/mperror.c +++ b/esp32/util/mperror.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/mperror.h b/esp32/util/mperror.h index 25b27e953c..98b2b89f9e 100644 --- a/esp32/util/mperror.h +++ b/esp32/util/mperror.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/mpexception.c b/esp32/util/mpexception.c index 7b3bd89a80..d30db8c483 100644 --- a/esp32/util/mpexception.c +++ b/esp32/util/mpexception.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/mpexception.h b/esp32/util/mpexception.h index 5f67feb892..547263810a 100644 --- a/esp32/util/mpexception.h +++ b/esp32/util/mpexception.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/mpirq.c b/esp32/util/mpirq.c index 841006b66f..dc378506a3 100644 --- a/esp32/util/mpirq.c +++ b/esp32/util/mpirq.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -148,7 +148,20 @@ mp_obj_tuple_t *mp_irq_find (mp_obj_t parent) { void IRAM_ATTR mp_irq_queue_interrupt(void (* handler)(void *), void *arg) { mp_callback_obj_t cb = {.handler = handler, .arg = arg}; - xQueueSendFromISR(InterruptsQueue, &cb, NULL); + + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + + xQueueSendFromISR(InterruptsQueue, &cb, &xHigherPriorityTaskWoken); + + if( xHigherPriorityTaskWoken) + { + portYIELD_FROM_ISR(); + } +} + +void mp_irq_queue_interrupt_non_ISR(void (* handler)(void *), void *arg) { + mp_callback_obj_t cb = {.handler = handler, .arg = arg}; + (void)xQueueSend(InterruptsQueue, &cb, 0); } void IRAM_ATTR mp_irq_queue_interrupt_immediate_thread_delete(TaskHandle_t id) { diff --git a/esp32/util/mpirq.h b/esp32/util/mpirq.h index a0930c3e03..8f4af32f08 100644 --- a/esp32/util/mpirq.h +++ b/esp32/util/mpirq.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -49,6 +49,7 @@ void mp_irq_add (mp_obj_t parent, mp_obj_t handler); void mp_irq_remove (mp_obj_t parent); mp_obj_tuple_t *mp_irq_find (mp_obj_t parent); void mp_irq_queue_interrupt(void (* handler)(void *), void *arg); +void mp_irq_queue_interrupt_non_ISR(void (* handler)(void *), void *arg); void mp_irq_queue_interrupt_immediate_thread_delete(TaskHandle_t id); void mp_irq_kill(void); #endif /* MPIRQ_H_ */ diff --git a/esp32/util/mpsleep.c b/esp32/util/mpsleep.c index 8f79983c27..e14e5d8da1 100644 --- a/esp32/util/mpsleep.c +++ b/esp32/util/mpsleep.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/mpsleep.h b/esp32/util/mpsleep.h index a60fbc5b22..ab838a228d 100644 --- a/esp32/util/mpsleep.h +++ b/esp32/util/mpsleep.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/pycom_general_util.c b/esp32/util/pycom_general_util.c new file mode 100644 index 0000000000..38c891c038 --- /dev/null +++ b/esp32/util/pycom_general_util.c @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2020, Pycom Limited. + * + * This software is licensed under the GNU GPL version 3 or any + * later version, with permitted additional terms. For more information + * see the Pycom Licence v1.0 document supplied with this file, or + * available at https://www.pycom.io/opensource/licensing + */ + +#include + +#include "freertos/FreeRTOS.h" + +#include "py/mpconfig.h" +#include "py/runtime.h" +#include "mptask.h" +#include "pycom_general_util.h" + + +/****************************************************************************** + DEFINE CONSTANTS + ******************************************************************************/ +#define FILE_READ_SIZE 256 + +/****************************************************************************** + DEFINE PUBLIC FUNCTIONS + ******************************************************************************/ +char *pycom_util_read_file (const char *file_path, vstr_t *vstr) { + vstr_init(vstr, FILE_READ_SIZE); + char *filebuf = vstr->buf; + mp_uint_t actualsize; + mp_uint_t totalsize = 0; + static const TCHAR *path_relative; + // THis is needed to be able to clean the VSTR if any error occurred + bool error = false; + + if(isLittleFs(file_path)) { + + vfs_lfs_struct_t* littlefs = lookup_path_littlefs(file_path, &path_relative); + if (littlefs == NULL) { + error = true; + } + else { + + lfs_file_t fp; + + xSemaphoreTake(littlefs->mutex, portMAX_DELAY); + + int res = lfs_file_open(&littlefs->lfs, &fp, path_relative, LFS_O_RDONLY); + if(res < LFS_ERR_OK) { + error = true; + } + else { + while (error == false) { + actualsize = lfs_file_read(&littlefs->lfs, &fp, filebuf, FILE_READ_SIZE); + if (actualsize < LFS_ERR_OK) { + error = true; + } + else { + totalsize += actualsize; + if (actualsize < FILE_READ_SIZE) { + break; + } else { + filebuf = vstr_extend(vstr, FILE_READ_SIZE); + } + } + } + + lfs_file_close(&littlefs->lfs, &fp); + } + + xSemaphoreGive(littlefs->mutex); + } + } + else + { + FATFS *fs = lookup_path_fatfs(file_path, &path_relative); + if (fs == NULL) { + error = true; + } + else { + FIL fp; + FRESULT res = f_open(fs, &fp, path_relative, FA_READ); + if (res != FR_OK) { + error = true; + } + else { + while (error == false) { + FRESULT res = f_read(&fp, filebuf, FILE_READ_SIZE, (UINT *)&actualsize); + if (res != FR_OK) { + f_close(&fp); + error = true; + } + else { + totalsize += actualsize; + if (actualsize < FILE_READ_SIZE) { + break; + } else { + filebuf = vstr_extend(vstr, FILE_READ_SIZE); + } + } + } + f_close(&fp); + } + } + } + + if(error == true) { + vstr_clear(vstr); + return NULL; + } + else { + vstr->len = totalsize; + vstr_null_terminated_str(vstr); + return vstr->buf; + } +} diff --git a/esp32/util/pycom_general_util.h b/esp32/util/pycom_general_util.h new file mode 100644 index 0000000000..97cd1e3d14 --- /dev/null +++ b/esp32/util/pycom_general_util.h @@ -0,0 +1,17 @@ +/* + * Copyright (c) 2020, Pycom Limited. + * + * This software is licensed under the GNU GPL version 3 or any + * later version, with permitted additional terms. For more information + * see the Pycom Licence v1.0 document supplied with this file, or + * available at https://www.pycom.io/opensource/licensing + */ + +#ifndef ESP32_UTIL_PYCOM_GENERAL_UTIL_H_ +#define ESP32_UTIL_PYCOM_GENERAL_UTIL_H_ + +#include "py/obj.h" + +char *pycom_util_read_file(const char *file_path, vstr_t *vstr); + +#endif /* ESP32_UTIL_PYCOM_GENERAL_UTIL_H_ */ diff --git a/esp32/util/random.c b/esp32/util/random.c index 74f130c844..6516ea27b9 100644 --- a/esp32/util/random.c +++ b/esp32/util/random.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/random.h b/esp32/util/random.h index 03483907c8..0a651e6af8 100644 --- a/esp32/util/random.h +++ b/esp32/util/random.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/socketfifo.c b/esp32/util/socketfifo.c index 6935f8fcba..58169799b1 100644 --- a/esp32/util/socketfifo.c +++ b/esp32/util/socketfifo.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information @@ -62,7 +62,7 @@ void SOCKETFIFO_Flush (void) { SocketFifoElement_t element; while (SOCKETFIFO_Pop(&element)) { if (element.freedata) { - vPortFree(element.data); + free(element.data); } } } diff --git a/esp32/util/socketfifo.h b/esp32/util/socketfifo.h index e3091ebaa5..db7bfa4a7f 100644 --- a/esp32/util/socketfifo.h +++ b/esp32/util/socketfifo.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Pycom Limited. + * Copyright (c) 2020, Pycom Limited. * * This software is licensed under the GNU GPL version 3 or any * later version, with permitted additional terms. For more information diff --git a/esp32/util/str_utils.c b/esp32/util/str_utils.c new file mode 100644 index 0000000000..8702e75610 --- /dev/null +++ b/esp32/util/str_utils.c @@ -0,0 +1,20 @@ +#include "str_utils.h" +#include + +/** + * Create a string representation of a uint8 + */ +void sprint_binary_u8(char* s, uint8_t v){ + size_t len = 9; // eight bits plus '\0' + snprintf(s, len, "%u%u%u%u%u%u%u%u", + (v & 0b10000000) >> 7, + (v & 0b01000000) >> 6, + (v & 0b00100000) >> 5, + (v & 0b00010000) >> 4, + (v & 0b00001000) >> 3, + (v & 0b00000100) >> 2, + (v & 0b00000010) >> 1, + (v & 0b00000001) >> 0 + ); +} + diff --git a/esp32/util/str_utils.h b/esp32/util/str_utils.h new file mode 100644 index 0000000000..258b6d1dc0 --- /dev/null +++ b/esp32/util/str_utils.h @@ -0,0 +1,17 @@ +#ifndef STR_UTILS_H +#define STR_UTILS_H + +#include +#include + +/** + * Determine the length of str at compile time + * + * The length is excluding the terminating \0 just as strlen() + * make sure you pass a compile time constant + */ +#define strlen_const(string) (sizeof(string)-1) + +void sprint_binary_u8(char* s, uint8_t v); + +#endif diff --git a/extmod/vfs_fat.c b/extmod/vfs_fat.c index 9776f60aa9..f7cb095cbd 100644 --- a/extmod/vfs_fat.c +++ b/extmod/vfs_fat.c @@ -365,9 +365,9 @@ STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid t->items[6] = mp_obj_new_int_from_uint(fno.fsize); // st_size - t->items[7] = MP_OBJ_NEW_SMALL_INT(seconds); // st_atime - t->items[8] = MP_OBJ_NEW_SMALL_INT(seconds); // st_mtime - t->items[9] = MP_OBJ_NEW_SMALL_INT(seconds); // st_ctime + t->items[7] = mp_obj_new_int_from_uint(seconds); // st_atime + t->items[8] = mp_obj_new_int_from_uint(seconds); // st_mtime + t->items[9] = mp_obj_new_int_from_uint(seconds); // st_ctime return MP_OBJ_FROM_PTR(t); } diff --git a/lib/lora/mac/LoRaMac.h b/lib/lora/mac/LoRaMac.h index b53b5b41d1..2a77564b10 100644 --- a/lib/lora/mac/LoRaMac.h +++ b/lib/lora/mac/LoRaMac.h @@ -1715,6 +1715,11 @@ typedef enum eLoRaMacRegion_t * North american band on 915MHz with a maximum of 16 channels */ LORAMAC_REGION_US915_HYBRID, + + /*! + * Invalid region + */ + LORAMAC_REGION_MAX }LoRaMacRegion_t; /*! diff --git a/lib/lora/mac/region/Region.c b/lib/lora/mac/region/Region.c index b393c931cc..3d61b9b4d2 100644 --- a/lib/lora/mac/region/Region.c +++ b/lib/lora/mac/region/Region.c @@ -33,35 +33,34 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae // Setup regions #ifdef REGION_AS923 #include "RegionAS923.h" -#define AS923_CASE case LORAMAC_REGION_AS923: -#define AS923_IS_ACTIVE( ) AS923_CASE { return true; } -#define AS923_GET_PHY_PARAM( ) AS923_CASE { return RegionAS923GetPhyParam( getPhy ); } -#define AS923_SET_BAND_TX_DONE( ) AS923_CASE { RegionAS923SetBandTxDone( txDone ); break; } -#define AS923_INIT_DEFAULTS( ) AS923_CASE { RegionAS923InitDefaults( type ); break; } -#define AS923_VERIFY( ) AS923_CASE { return RegionAS923Verify( verify, phyAttribute ); } -#define AS923_APPLY_CF_LIST( ) AS923_CASE { RegionAS923ApplyCFList( applyCFList ); break; } -#define AS923_CHAN_MASK_SET( ) AS923_CASE { return RegionAS923ChanMaskSet( chanMaskSet ); } -#define AS923_ADR_NEXT( ) AS923_CASE { return RegionAS923AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define AS923_COMPUTE_RX_WINDOW_PARAMETERS( ) AS923_CASE { RegionAS923ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define AS923_RX_CONFIG( ) AS923_CASE { return RegionAS923RxConfig( rxConfig, datarate ); } -#define AS923_TX_CONFIG( ) AS923_CASE { return RegionAS923TxConfig( txConfig, txPower, txTimeOnAir ); } -#define AS923_LINK_ADR_REQ( ) AS923_CASE { return RegionAS923LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define AS923_RX_PARAM_SETUP_REQ( ) AS923_CASE { return RegionAS923RxParamSetupReq( rxParamSetupReq ); } -#define AS923_NEW_CHANNEL_REQ( ) AS923_CASE { return RegionAS923NewChannelReq( newChannelReq ); } -#define AS923_TX_PARAM_SETUP_REQ( ) AS923_CASE { return RegionAS923TxParamSetupReq( txParamSetupReq ); } -#define AS923_DL_CHANNEL_REQ( ) AS923_CASE { return RegionAS923DlChannelReq( dlChannelReq ); } -#define AS923_ALTERNATE_DR( ) AS923_CASE { return RegionAS923AlternateDr( alternateDr ); } -#define AS923_CALC_BACKOFF( ) AS923_CASE { RegionAS923CalcBackOff( calcBackOff ); break; } -#define AS923_NEXT_CHANNEL( ) AS923_CASE { return RegionAS923NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define AS923_CHANNEL_ADD( ) AS923_CASE { return RegionAS923ChannelAdd( channelAdd ); } -#define AS923_CHANNEL_REMOVE( ) AS923_CASE { return RegionAS923ChannelsRemove( channelRemove ); } -#define AS923_CHANNEL_MANUAL_ADD( ) AS923_CASE { return RegionAS923ChannelManualAdd( channelAdd ); } -#define AS923_CHANNEL_MANUAL_REMOVE( ) AS923_CASE { return RegionAS923ChannelsRemove( channelRemove ); } -#define AS923_SET_CONTINUOUS_WAVE( ) AS923_CASE { RegionAS923SetContinuousWave( continuousWave ); break; } -#define AS923_APPLY_DR_OFFSET( ) AS923_CASE { return RegionAS923ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define AS923_GET_CHANNELS( ) AS923_CASE { return RegionAS923GetChannels( channels, size ); } -#define AS923_GET_CHANNEL_MASK( ) AS923_CASE { return RegionAS923GetChannelMask( channelmask, size ); } -#define AS923_FORCE_JOIN_DATARATE( ) AS923_CASE { return RegionAS923ForceJoinDataRate( joinDr, alternateDr ); } +#define AS923_IS_ACTIVE( ) else if(region == LORAMAC_REGION_AS923) { return true; } +#define AS923_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923GetPhyParam( getPhy ); } +#define AS923_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_AS923) { RegionAS923SetBandTxDone( txDone );} +#define AS923_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_AS923) { RegionAS923InitDefaults( type );} +#define AS923_VERIFY( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923Verify( verify, phyAttribute ); } +#define AS923_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_AS923) { RegionAS923ApplyCFList( applyCFList );} +#define AS923_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ChanMaskSet( chanMaskSet ); } +#define AS923_ADR_NEXT( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define AS923_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_AS923) { RegionAS923ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define AS923_RX_CONFIG( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923RxConfig( rxConfig, datarate ); } +#define AS923_TX_CONFIG( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923TxConfig( txConfig, txPower, txTimeOnAir ); } +#define AS923_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define AS923_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923RxParamSetupReq( rxParamSetupReq ); } +#define AS923_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923NewChannelReq( newChannelReq ); } +#define AS923_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923TxParamSetupReq( txParamSetupReq ); } +#define AS923_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923DlChannelReq( dlChannelReq ); } +#define AS923_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923AlternateDr( alternateDr ); } +#define AS923_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_AS923) { RegionAS923CalcBackOff( calcBackOff );} +#define AS923_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define AS923_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ChannelAdd( channelAdd ); } +#define AS923_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ChannelsRemove( channelRemove ); } +#define AS923_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ChannelManualAdd( channelAdd ); } +#define AS923_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ChannelsRemove( channelRemove ); } +#define AS923_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_AS923) { RegionAS923SetContinuousWave( continuousWave );} +#define AS923_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define AS923_GET_CHANNELS( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923GetChannels( channels, size ); } +#define AS923_GET_CHANNEL_MASK( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923GetChannelMask( channelmask, size ); } +#define AS923_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_AS923) { return RegionAS923ForceJoinDataRate( joinDr, alternateDr ); } #else #define AS923_IS_ACTIVE( ) #define AS923_GET_PHY_PARAM( ) @@ -95,36 +94,35 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_AU915 #include "RegionAU915.h" -#define AU915_CASE case LORAMAC_REGION_AU915: -#define AU915_IS_ACTIVE( ) AU915_CASE { return true; } -#define AU915_GET_PHY_PARAM( ) AU915_CASE { return RegionAU915GetPhyParam( getPhy ); } -#define AU915_SET_BAND_TX_DONE( ) AU915_CASE { RegionAU915SetBandTxDone( txDone ); break; } -#define AU915_INIT_DEFAULTS( ) AU915_CASE { RegionAU915InitDefaults( type ); break; } -#define AU915_VERIFY( ) AU915_CASE { return RegionAU915Verify( verify, phyAttribute ); } -#define AU915_APPLY_CF_LIST( ) AU915_CASE { RegionAU915ApplyCFList( applyCFList ); break; } -#define AU915_CHAN_MASK_SET( ) AU915_CASE { return RegionAU915ChanMaskSet( chanMaskSet ); } -#define AU915_ADR_NEXT( ) AU915_CASE { return RegionAU915AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define AU915_COMPUTE_RX_WINDOW_PARAMETERS( ) AU915_CASE { RegionAU915ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define AU915_RX_CONFIG( ) AU915_CASE { return RegionAU915RxConfig( rxConfig, datarate ); } -#define AU915_TX_CONFIG( ) AU915_CASE { return RegionAU915TxConfig( txConfig, txPower, txTimeOnAir ); } -#define AU915_LINK_ADR_REQ( ) AU915_CASE { return RegionAU915LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define AU915_RX_PARAM_SETUP_REQ( ) AU915_CASE { return RegionAU915RxParamSetupReq( rxParamSetupReq ); } -#define AU915_NEW_CHANNEL_REQ( ) AU915_CASE { return RegionAU915NewChannelReq( newChannelReq ); } -#define AU915_TX_PARAM_SETUP_REQ( ) AU915_CASE { return RegionAU915TxParamSetupReq( txParamSetupReq ); } -#define AU915_DL_CHANNEL_REQ( ) AU915_CASE { return RegionAU915DlChannelReq( dlChannelReq ); } -#define AU915_ALTERNATE_DR( ) AU915_CASE { return RegionAU915AlternateDr( alternateDr ); } -#define AU915_CALC_BACKOFF( ) AU915_CASE { RegionAU915CalcBackOff( calcBackOff ); break; } -#define AU915_NEXT_CHANNEL( ) AU915_CASE { return RegionAU915NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define AU915_CHANNEL_ADD( ) AU915_CASE { return RegionAU915ChannelAdd( channelAdd ); } -#define AU915_CHANNEL_REMOVE( ) AU915_CASE { return RegionAU915ChannelsRemove( channelRemove ); } -#define AU915_CHANNEL_MANUAL_ADD( ) AU915_CASE { return RegionAU915ChannelManualAdd( channelAdd ); } -#define AU915_CHANNEL_MANUAL_REMOVE( ) AU915_CASE { return RegionAU915ChannelsManualRemove( channelRemove ); } -#define AU915_SET_CONTINUOUS_WAVE( ) AU915_CASE { RegionAU915SetContinuousWave( continuousWave ); break; } -#define AU915_APPLY_DR_OFFSET( ) AU915_CASE { return RegionAU915ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define AU915_GET_CHANNELS( ) AU915_CASE { return RegionAU915GetChannels( channels, size ); } -#define AU915_GET_CHANNEL_MASK( ) AU915_CASE { return RegionAU915GetChannelMask( channelmask, size ); } -#define AU915_GET_CHANNEL_MASK_REMAINING( ) AU915_CASE { return RegionAU915GetChannelMaskRemaining( channelmask, size ); } -#define AU915_FORCE_JOIN_DATARATE( ) AU915_CASE { return RegionAU915ForceJoinDataRate( joinDr, alternateDr ); } +#define AU915_IS_ACTIVE( ) else if(region == LORAMAC_REGION_AU915) { return true; } +#define AU915_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915GetPhyParam( getPhy ); } +#define AU915_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_AU915) { RegionAU915SetBandTxDone( txDone );} +#define AU915_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_AU915) { RegionAU915InitDefaults( type );} +#define AU915_VERIFY( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915Verify( verify, phyAttribute ); } +#define AU915_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_AU915) { RegionAU915ApplyCFList( applyCFList );} +#define AU915_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ChanMaskSet( chanMaskSet ); } +#define AU915_ADR_NEXT( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define AU915_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_AU915) { RegionAU915ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define AU915_RX_CONFIG( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915RxConfig( rxConfig, datarate ); } +#define AU915_TX_CONFIG( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915TxConfig( txConfig, txPower, txTimeOnAir ); } +#define AU915_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define AU915_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915RxParamSetupReq( rxParamSetupReq ); } +#define AU915_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915NewChannelReq( newChannelReq ); } +#define AU915_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915TxParamSetupReq( txParamSetupReq ); } +#define AU915_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915DlChannelReq( dlChannelReq ); } +#define AU915_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915AlternateDr( alternateDr ); } +#define AU915_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_AU915) { RegionAU915CalcBackOff( calcBackOff );} +#define AU915_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define AU915_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ChannelAdd( channelAdd ); } +#define AU915_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ChannelsRemove( channelRemove ); } +#define AU915_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ChannelManualAdd( channelAdd ); } +#define AU915_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ChannelsManualRemove( channelRemove ); } +#define AU915_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_AU915) { RegionAU915SetContinuousWave( continuousWave );} +#define AU915_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define AU915_GET_CHANNELS( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915GetChannels( channels, size ); } +#define AU915_GET_CHANNEL_MASK( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915GetChannelMask( channelmask, size ); } +#define AU915_GET_CHANNEL_MASK_REMAINING( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915GetChannelMaskRemaining( channelmask, size ); } +#define AU915_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_AU915) { return RegionAU915ForceJoinDataRate( joinDr, alternateDr ); } #else #define AU915_IS_ACTIVE( ) #define AU915_GET_PHY_PARAM( ) @@ -159,33 +157,32 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_CN470 #include "RegionCN470.h" -#define CN470_CASE case LORAMAC_REGION_CN470: -#define CN470_IS_ACTIVE( ) CN470_CASE { return true; } -#define CN470_GET_PHY_PARAM( ) CN470_CASE { return RegionCN470GetPhyParam( getPhy ); } -#define CN470_SET_BAND_TX_DONE( ) CN470_CASE { RegionCN470SetBandTxDone( txDone ); break; } -#define CN470_INIT_DEFAULTS( ) CN470_CASE { RegionCN470InitDefaults( type ); break; } -#define CN470_VERIFY( ) CN470_CASE { return RegionCN470Verify( verify, phyAttribute ); } -#define CN470_APPLY_CF_LIST( ) CN470_CASE { RegionCN470ApplyCFList( applyCFList ); break; } -#define CN470_CHAN_MASK_SET( ) CN470_CASE { return RegionCN470ChanMaskSet( chanMaskSet ); } -#define CN470_ADR_NEXT( ) CN470_CASE { return RegionCN470AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define CN470_COMPUTE_RX_WINDOW_PARAMETERS( ) CN470_CASE { RegionCN470ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define CN470_RX_CONFIG( ) CN470_CASE { return RegionCN470RxConfig( rxConfig, datarate ); } -#define CN470_TX_CONFIG( ) CN470_CASE { return RegionCN470TxConfig( txConfig, txPower, txTimeOnAir ); } -#define CN470_LINK_ADR_REQ( ) CN470_CASE { return RegionCN470LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define CN470_RX_PARAM_SETUP_REQ( ) CN470_CASE { return RegionCN470RxParamSetupReq( rxParamSetupReq ); } -#define CN470_NEW_CHANNEL_REQ( ) CN470_CASE { return RegionCN470NewChannelReq( newChannelReq ); } -#define CN470_TX_PARAM_SETUP_REQ( ) CN470_CASE { return RegionCN470TxParamSetupReq( txParamSetupReq ); } -#define CN470_DL_CHANNEL_REQ( ) CN470_CASE { return RegionCN470DlChannelReq( dlChannelReq ); } -#define CN470_ALTERNATE_DR( ) CN470_CASE { return RegionCN470AlternateDr( alternateDr ); } -#define CN470_CALC_BACKOFF( ) CN470_CASE { RegionCN470CalcBackOff( calcBackOff ); break; } -#define CN470_NEXT_CHANNEL( ) CN470_CASE { return RegionCN470NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define CN470_CHANNEL_ADD( ) CN470_CASE { return RegionCN470ChannelAdd( channelAdd ); } -#define CN470_CHANNEL_REMOVE( ) CN470_CASE { return RegionCN470ChannelsRemove( channelRemove ); } -#define CN470_CHANNEL_MANUAL_ADD( ) CN470_CASE { return RegionCN470ChannelManualAdd( channelAdd ); } -#define CN470_CHANNEL_MANUAL_REMOVE( ) CN470_CASE { return RegionCN470ChannelsRemove( channelRemove ); } -#define CN470_SET_CONTINUOUS_WAVE( ) CN470_CASE { RegionCN470SetContinuousWave( continuousWave ); break; } -#define CN470_APPLY_DR_OFFSET( ) CN470_CASE { return RegionCN470ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define CN470_FORCE_JOIN_DATARATE( ) CN470_CASE { return RegionCN470ForceJoinDataRate( joinDr, alternateDr ); } +#define CN470_IS_ACTIVE( ) else if(region == LORAMAC_REGION_CN470) { return true; } +#define CN470_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470GetPhyParam( getPhy ); } +#define CN470_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_CN470) { RegionCN470SetBandTxDone( txDone );} +#define CN470_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_CN470) { RegionCN470InitDefaults( type );} +#define CN470_VERIFY( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470Verify( verify, phyAttribute ); } +#define CN470_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_CN470) { RegionCN470ApplyCFList( applyCFList );} +#define CN470_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ChanMaskSet( chanMaskSet ); } +#define CN470_ADR_NEXT( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define CN470_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_CN470) { RegionCN470ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define CN470_RX_CONFIG( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470RxConfig( rxConfig, datarate ); } +#define CN470_TX_CONFIG( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470TxConfig( txConfig, txPower, txTimeOnAir ); } +#define CN470_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define CN470_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470RxParamSetupReq( rxParamSetupReq ); } +#define CN470_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470NewChannelReq( newChannelReq ); } +#define CN470_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470TxParamSetupReq( txParamSetupReq ); } +#define CN470_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470DlChannelReq( dlChannelReq ); } +#define CN470_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470AlternateDr( alternateDr ); } +#define CN470_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_CN470) { RegionCN470CalcBackOff( calcBackOff );} +#define CN470_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define CN470_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ChannelAdd( channelAdd ); } +#define CN470_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ChannelsRemove( channelRemove ); } +#define CN470_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ChannelManualAdd( channelAdd ); } +#define CN470_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ChannelsRemove( channelRemove ); } +#define CN470_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_CN470) { RegionCN470SetContinuousWave( continuousWave );} +#define CN470_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define CN470_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_CN470) { return RegionCN470ForceJoinDataRate( joinDr, alternateDr ); } #else #define CN470_IS_ACTIVE( ) #define CN470_GET_PHY_PARAM( ) @@ -217,30 +214,29 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_CN779 #include "RegionCN779.h" -#define CN779_CASE case LORAMAC_REGION_CN779: -#define CN779_IS_ACTIVE( ) CN779_CASE { return true; } -#define CN779_GET_PHY_PARAM( ) CN779_CASE { return RegionCN779GetPhyParam( getPhy ); } -#define CN779_SET_BAND_TX_DONE( ) CN779_CASE { RegionCN779SetBandTxDone( txDone ); break; } -#define CN779_INIT_DEFAULTS( ) CN779_CASE { RegionCN779InitDefaults( type ); break; } -#define CN779_VERIFY( ) CN779_CASE { return RegionCN779Verify( verify, phyAttribute ); } -#define CN779_APPLY_CF_LIST( ) CN779_CASE { RegionCN779ApplyCFList( applyCFList ); break; } -#define CN779_CHAN_MASK_SET( ) CN779_CASE { return RegionCN779ChanMaskSet( chanMaskSet ); } -#define CN779_ADR_NEXT( ) CN779_CASE { return RegionCN779AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define CN779_COMPUTE_RX_WINDOW_PARAMETERS( ) CN779_CASE { RegionCN779ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define CN779_RX_CONFIG( ) CN779_CASE { return RegionCN779RxConfig( rxConfig, datarate ); } -#define CN779_TX_CONFIG( ) CN779_CASE { return RegionCN779TxConfig( txConfig, txPower, txTimeOnAir ); } -#define CN779_LINK_ADR_REQ( ) CN779_CASE { return RegionCN779LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define CN779_RX_PARAM_SETUP_REQ( ) CN779_CASE { return RegionCN779RxParamSetupReq( rxParamSetupReq ); } -#define CN779_NEW_CHANNEL_REQ( ) CN779_CASE { return RegionCN779NewChannelReq( newChannelReq ); } -#define CN779_TX_PARAM_SETUP_REQ( ) CN779_CASE { return RegionCN779TxParamSetupReq( txParamSetupReq ); } -#define CN779_DL_CHANNEL_REQ( ) CN779_CASE { return RegionCN779DlChannelReq( dlChannelReq ); } -#define CN779_ALTERNATE_DR( ) CN779_CASE { return RegionCN779AlternateDr( alternateDr ); } -#define CN779_CALC_BACKOFF( ) CN779_CASE { RegionCN779CalcBackOff( calcBackOff ); break; } -#define CN779_NEXT_CHANNEL( ) CN779_CASE { return RegionCN779NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define CN779_CHANNEL_ADD( ) CN779_CASE { return RegionCN779ChannelAdd( channelAdd ); } -#define CN779_CHANNEL_REMOVE( ) CN779_CASE { return RegionCN779ChannelsRemove( channelRemove ); } -#define CN779_SET_CONTINUOUS_WAVE( ) CN779_CASE { RegionCN779SetContinuousWave( continuousWave ); break; } -#define CN779_APPLY_DR_OFFSET( ) CN779_CASE { return RegionCN779ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define CN779_IS_ACTIVE( ) else if(region == LORAMAC_REGION_CN779) { return true; } +#define CN779_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779GetPhyParam( getPhy ); } +#define CN779_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_CN779) { RegionCN779SetBandTxDone( txDone );} +#define CN779_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_CN779) { RegionCN779InitDefaults( type );} +#define CN779_VERIFY( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779Verify( verify, phyAttribute ); } +#define CN779_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_CN779) { RegionCN779ApplyCFList( applyCFList );} +#define CN779_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779ChanMaskSet( chanMaskSet ); } +#define CN779_ADR_NEXT( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define CN779_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_CN779) { RegionCN779ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define CN779_RX_CONFIG( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779RxConfig( rxConfig, datarate ); } +#define CN779_TX_CONFIG( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779TxConfig( txConfig, txPower, txTimeOnAir ); } +#define CN779_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define CN779_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779RxParamSetupReq( rxParamSetupReq ); } +#define CN779_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779NewChannelReq( newChannelReq ); } +#define CN779_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779TxParamSetupReq( txParamSetupReq ); } +#define CN779_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779DlChannelReq( dlChannelReq ); } +#define CN779_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779AlternateDr( alternateDr ); } +#define CN779_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_CN779) { RegionCN779CalcBackOff( calcBackOff );} +#define CN779_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define CN779_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779ChannelAdd( channelAdd ); } +#define CN779_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779ChannelsRemove( channelRemove ); } +#define CN779_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_CN779) { RegionCN779SetContinuousWave( continuousWave );} +#define CN779_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_CN779) { return RegionCN779ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } #else #define CN779_IS_ACTIVE( ) #define CN779_GET_PHY_PARAM( ) @@ -269,30 +265,32 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_EU433 #include "RegionEU433.h" -#define EU433_CASE case LORAMAC_REGION_EU433: -#define EU433_IS_ACTIVE( ) EU433_CASE { return true; } -#define EU433_GET_PHY_PARAM( ) EU433_CASE { return RegionEU433GetPhyParam( getPhy ); } -#define EU433_SET_BAND_TX_DONE( ) EU433_CASE { RegionEU433SetBandTxDone( txDone ); break; } -#define EU433_INIT_DEFAULTS( ) EU433_CASE { RegionEU433InitDefaults( type ); break; } -#define EU433_VERIFY( ) EU433_CASE { return RegionEU433Verify( verify, phyAttribute ); } -#define EU433_APPLY_CF_LIST( ) EU433_CASE { RegionEU433ApplyCFList( applyCFList ); break; } -#define EU433_CHAN_MASK_SET( ) EU433_CASE { return RegionEU433ChanMaskSet( chanMaskSet ); } -#define EU433_ADR_NEXT( ) EU433_CASE { return RegionEU433AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define EU433_COMPUTE_RX_WINDOW_PARAMETERS( ) EU433_CASE { RegionEU433ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define EU433_RX_CONFIG( ) EU433_CASE { return RegionEU433RxConfig( rxConfig, datarate ); } -#define EU433_TX_CONFIG( ) EU433_CASE { return RegionEU433TxConfig( txConfig, txPower, txTimeOnAir ); } -#define EU433_LINK_ADR_REQ( ) EU433_CASE { return RegionEU433LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define EU433_RX_PARAM_SETUP_REQ( ) EU433_CASE { return RegionEU433RxParamSetupReq( rxParamSetupReq ); } -#define EU433_NEW_CHANNEL_REQ( ) EU433_CASE { return RegionEU433NewChannelReq( newChannelReq ); } -#define EU433_TX_PARAM_SETUP_REQ( ) EU433_CASE { return RegionEU433TxParamSetupReq( txParamSetupReq ); } -#define EU433_DL_CHANNEL_REQ( ) EU433_CASE { return RegionEU433DlChannelReq( dlChannelReq ); } -#define EU433_ALTERNATE_DR( ) EU433_CASE { return RegionEU433AlternateDr( alternateDr ); } -#define EU433_CALC_BACKOFF( ) EU433_CASE { RegionEU433CalcBackOff( calcBackOff ); break; } -#define EU433_NEXT_CHANNEL( ) EU433_CASE { return RegionEU433NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define EU433_CHANNEL_ADD( ) EU433_CASE { return RegionEU433ChannelAdd( channelAdd ); } -#define EU433_CHANNEL_REMOVE( ) EU433_CASE { return RegionEU433ChannelsRemove( channelRemove ); } -#define EU433_SET_CONTINUOUS_WAVE( ) EU433_CASE { RegionEU433SetContinuousWave( continuousWave ); break; } -#define EU433_APPLY_DR_OFFSET( ) EU433_CASE { return RegionEU433ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define EU433_IS_ACTIVE( ) else if(region == LORAMAC_REGION_EU433) { return true; } +#define EU433_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433GetPhyParam( getPhy ); } +#define EU433_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_EU433) { RegionEU433SetBandTxDone( txDone );} +#define EU433_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_EU433) { RegionEU433InitDefaults( type );} +#define EU433_VERIFY( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433Verify( verify, phyAttribute ); } +#define EU433_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_EU433) { RegionEU433ApplyCFList( applyCFList );} +#define EU433_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433ChanMaskSet( chanMaskSet ); } +#define EU433_ADR_NEXT( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define EU433_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_EU433) { RegionEU433ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define EU433_RX_CONFIG( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433RxConfig( rxConfig, datarate ); } +#define EU433_TX_CONFIG( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433TxConfig( txConfig, txPower, txTimeOnAir ); } +#define EU433_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define EU433_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433RxParamSetupReq( rxParamSetupReq ); } +#define EU433_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433NewChannelReq( newChannelReq ); } +#define EU433_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433TxParamSetupReq( txParamSetupReq ); } +#define EU433_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433DlChannelReq( dlChannelReq ); } +#define EU433_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433AlternateDr( alternateDr ); } +#define EU433_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_EU433) { RegionEU433CalcBackOff( calcBackOff );} +#define EU433_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define EU433_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433ChannelAdd( channelAdd ); } +#define EU433_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433ChannelsRemove( channelRemove ); } +#define EU433_CHANNEL_MANUAL_ADD( ) EU433_CASE { return RegionEU433ChannelManualAdd( channelAdd ); } +#define EU433_CHANNEL_MANUAL_REMOVE( ) EU433_CASE { return RegionEU433ChannelsRemove( channelRemove ); } +#define EU433_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_EU433) { RegionEU433SetContinuousWave( continuousWave );} +#define EU433_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_EU433) { return RegionEU433ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define EU433_FORCE_JOIN_DATARATE( ) EU433_CASE { return RegionEU433ForceJoinDataRate( joinDr, alternateDr ); } #else #define EU433_IS_ACTIVE( ) #define EU433_GET_PHY_PARAM( ) @@ -315,41 +313,43 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #define EU433_NEXT_CHANNEL( ) #define EU433_CHANNEL_ADD( ) #define EU433_CHANNEL_REMOVE( ) +#define EU433_CHANNEL_MANUAL_ADD( ) +#define EU433_CHANNEL_MANUAL_REMOVE( ) #define EU433_SET_CONTINUOUS_WAVE( ) #define EU433_APPLY_DR_OFFSET( ) +#define EU433_FORCE_JOIN_DATARATE( ) #endif #ifdef REGION_EU868 #include "RegionEU868.h" -#define EU868_CASE case LORAMAC_REGION_EU868: -#define EU868_IS_ACTIVE( ) EU868_CASE { return true; } -#define EU868_GET_PHY_PARAM( ) EU868_CASE { return RegionEU868GetPhyParam( getPhy ); } -#define EU868_SET_BAND_TX_DONE( ) EU868_CASE { RegionEU868SetBandTxDone( txDone ); break; } -#define EU868_INIT_DEFAULTS( ) EU868_CASE { RegionEU868InitDefaults( type ); break; } -#define EU868_VERIFY( ) EU868_CASE { return RegionEU868Verify( verify, phyAttribute ); } -#define EU868_APPLY_CF_LIST( ) EU868_CASE { RegionEU868ApplyCFList( applyCFList ); break; } -#define EU868_CHAN_MASK_SET( ) EU868_CASE { return RegionEU868ChanMaskSet( chanMaskSet ); } -#define EU868_ADR_NEXT( ) EU868_CASE { return RegionEU868AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define EU868_COMPUTE_RX_WINDOW_PARAMETERS( ) EU868_CASE { RegionEU868ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define EU868_RX_CONFIG( ) EU868_CASE { return RegionEU868RxConfig( rxConfig, datarate ); } -#define EU868_TX_CONFIG( ) EU868_CASE { return RegionEU868TxConfig( txConfig, txPower, txTimeOnAir ); } -#define EU868_LINK_ADR_REQ( ) EU868_CASE { return RegionEU868LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define EU868_RX_PARAM_SETUP_REQ( ) EU868_CASE { return RegionEU868RxParamSetupReq( rxParamSetupReq ); } -#define EU868_NEW_CHANNEL_REQ( ) EU868_CASE { return RegionEU868NewChannelReq( newChannelReq ); } -#define EU868_TX_PARAM_SETUP_REQ( ) EU868_CASE { return RegionEU868TxParamSetupReq( txParamSetupReq ); } -#define EU868_DL_CHANNEL_REQ( ) EU868_CASE { return RegionEU868DlChannelReq( dlChannelReq ); } -#define EU868_ALTERNATE_DR( ) EU868_CASE { return RegionEU868AlternateDr( alternateDr ); } -#define EU868_CALC_BACKOFF( ) EU868_CASE { RegionEU868CalcBackOff( calcBackOff ); break; } -#define EU868_NEXT_CHANNEL( ) EU868_CASE { return RegionEU868NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define EU868_CHANNEL_ADD( ) EU868_CASE { return RegionEU868ChannelAdd( channelAdd ); } -#define EU868_CHANNEL_REMOVE( ) EU868_CASE { return RegionEU868ChannelsRemove( channelRemove ); } -#define EU868_CHANNEL_MANUAL_ADD( ) EU868_CASE { return RegionEU868ChannelManualAdd( channelAdd ); } -#define EU868_CHANNEL_MANUAL_REMOVE( ) EU868_CASE { return RegionEU868ChannelsRemove( channelRemove ); } -#define EU868_SET_CONTINUOUS_WAVE( ) EU868_CASE { RegionEU868SetContinuousWave( continuousWave ); break; } -#define EU868_APPLY_DR_OFFSET( ) EU868_CASE { return RegionEU868ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define EU868_GET_CHANNELS( ) EU868_CASE { return RegionEU868GetChannels( channels, size ); } -#define EU868_GET_CHANNEL_MASK( ) EU868_CASE { return RegionEU868GetChannelMask( channelmask, size ); } -#define EU868_FORCE_JOIN_DATARATE( ) EU868_CASE { return RegionEU868ForceJoinDataRate( joinDr, alternateDr ); } +#define EU868_IS_ACTIVE( ) else if(region == LORAMAC_REGION_EU868) { return true; } +#define EU868_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868GetPhyParam( getPhy ); } +#define EU868_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_EU868) { RegionEU868SetBandTxDone( txDone );} +#define EU868_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_EU868) { RegionEU868InitDefaults( type );} +#define EU868_VERIFY( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868Verify( verify, phyAttribute ); } +#define EU868_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_EU868) { RegionEU868ApplyCFList( applyCFList );} +#define EU868_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ChanMaskSet( chanMaskSet ); } +#define EU868_ADR_NEXT( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define EU868_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_EU868) { RegionEU868ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define EU868_RX_CONFIG( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868RxConfig( rxConfig, datarate ); } +#define EU868_TX_CONFIG( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868TxConfig( txConfig, txPower, txTimeOnAir ); } +#define EU868_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define EU868_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868RxParamSetupReq( rxParamSetupReq ); } +#define EU868_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868NewChannelReq( newChannelReq ); } +#define EU868_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868TxParamSetupReq( txParamSetupReq ); } +#define EU868_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868DlChannelReq( dlChannelReq ); } +#define EU868_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868AlternateDr( alternateDr ); } +#define EU868_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_EU868) { RegionEU868CalcBackOff( calcBackOff );} +#define EU868_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define EU868_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ChannelAdd( channelAdd ); } +#define EU868_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ChannelsRemove( channelRemove ); } +#define EU868_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ChannelManualAdd( channelAdd ); } +#define EU868_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ChannelsRemove( channelRemove ); } +#define EU868_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_EU868) { RegionEU868SetContinuousWave( continuousWave );} +#define EU868_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define EU868_GET_CHANNELS( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868GetChannels( channels, size ); } +#define EU868_GET_CHANNEL_MASK( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868GetChannelMask( channelmask, size ); } +#define EU868_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_EU868) { return RegionEU868ForceJoinDataRate( joinDr, alternateDr ); } #else #define EU868_IS_ACTIVE( ) #define EU868_GET_PHY_PARAM( ) @@ -383,30 +383,29 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_KR920 #include "RegionKR920.h" -#define KR920_CASE case LORAMAC_REGION_KR920: -#define KR920_IS_ACTIVE( ) KR920_CASE { return true; } -#define KR920_GET_PHY_PARAM( ) KR920_CASE { return RegionKR920GetPhyParam( getPhy ); } -#define KR920_SET_BAND_TX_DONE( ) KR920_CASE { RegionKR920SetBandTxDone( txDone ); break; } -#define KR920_INIT_DEFAULTS( ) KR920_CASE { RegionKR920InitDefaults( type ); break; } -#define KR920_VERIFY( ) KR920_CASE { return RegionKR920Verify( verify, phyAttribute ); } -#define KR920_APPLY_CF_LIST( ) KR920_CASE { RegionKR920ApplyCFList( applyCFList ); break; } -#define KR920_CHAN_MASK_SET( ) KR920_CASE { return RegionKR920ChanMaskSet( chanMaskSet ); } -#define KR920_ADR_NEXT( ) KR920_CASE { return RegionKR920AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define KR920_COMPUTE_RX_WINDOW_PARAMETERS( ) KR920_CASE { RegionKR920ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define KR920_RX_CONFIG( ) KR920_CASE { return RegionKR920RxConfig( rxConfig, datarate ); } -#define KR920_TX_CONFIG( ) KR920_CASE { return RegionKR920TxConfig( txConfig, txPower, txTimeOnAir ); } -#define KR920_LINK_ADR_REQ( ) KR920_CASE { return RegionKR920LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define KR920_RX_PARAM_SETUP_REQ( ) KR920_CASE { return RegionKR920RxParamSetupReq( rxParamSetupReq ); } -#define KR920_NEW_CHANNEL_REQ( ) KR920_CASE { return RegionKR920NewChannelReq( newChannelReq ); } -#define KR920_TX_PARAM_SETUP_REQ( ) KR920_CASE { return RegionKR920TxParamSetupReq( txParamSetupReq ); } -#define KR920_DL_CHANNEL_REQ( ) KR920_CASE { return RegionKR920DlChannelReq( dlChannelReq ); } -#define KR920_ALTERNATE_DR( ) KR920_CASE { return RegionKR920AlternateDr( alternateDr ); } -#define KR920_CALC_BACKOFF( ) KR920_CASE { RegionKR920CalcBackOff( calcBackOff ); break; } -#define KR920_NEXT_CHANNEL( ) KR920_CASE { return RegionKR920NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define KR920_CHANNEL_ADD( ) KR920_CASE { return RegionKR920ChannelAdd( channelAdd ); } -#define KR920_CHANNEL_REMOVE( ) KR920_CASE { return RegionKR920ChannelsRemove( channelRemove ); } -#define KR920_SET_CONTINUOUS_WAVE( ) KR920_CASE { RegionKR920SetContinuousWave( continuousWave ); break; } -#define KR920_APPLY_DR_OFFSET( ) KR920_CASE { return RegionKR920ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define KR920_IS_ACTIVE( ) else if(region == LORAMAC_REGION_KR920) { return true; } +#define KR920_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920GetPhyParam( getPhy ); } +#define KR920_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_KR920) { RegionKR920SetBandTxDone( txDone );} +#define KR920_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_KR920) { RegionKR920InitDefaults( type );} +#define KR920_VERIFY( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920Verify( verify, phyAttribute ); } +#define KR920_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_KR920) { RegionKR920ApplyCFList( applyCFList );} +#define KR920_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920ChanMaskSet( chanMaskSet ); } +#define KR920_ADR_NEXT( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define KR920_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_KR920) { RegionKR920ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define KR920_RX_CONFIG( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920RxConfig( rxConfig, datarate ); } +#define KR920_TX_CONFIG( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920TxConfig( txConfig, txPower, txTimeOnAir ); } +#define KR920_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define KR920_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920RxParamSetupReq( rxParamSetupReq ); } +#define KR920_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920NewChannelReq( newChannelReq ); } +#define KR920_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920TxParamSetupReq( txParamSetupReq ); } +#define KR920_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920DlChannelReq( dlChannelReq ); } +#define KR920_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920AlternateDr( alternateDr ); } +#define KR920_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_KR920) { RegionKR920CalcBackOff( calcBackOff );} +#define KR920_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define KR920_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920ChannelAdd( channelAdd ); } +#define KR920_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920ChannelsRemove( channelRemove ); } +#define KR920_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_KR920) { RegionKR920SetContinuousWave( continuousWave );} +#define KR920_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_KR920) { return RegionKR920ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } #else #define KR920_IS_ACTIVE( ) #define KR920_GET_PHY_PARAM( ) @@ -435,35 +434,34 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_IN865 #include "RegionIN865.h" -#define IN865_CASE case LORAMAC_REGION_IN865: -#define IN865_IS_ACTIVE( ) IN865_CASE { return true; } -#define IN865_GET_PHY_PARAM( ) IN865_CASE { return RegionIN865GetPhyParam( getPhy ); } -#define IN865_SET_BAND_TX_DONE( ) IN865_CASE { RegionIN865SetBandTxDone( txDone ); break; } -#define IN865_INIT_DEFAULTS( ) IN865_CASE { RegionIN865InitDefaults( type ); break; } -#define IN865_VERIFY( ) IN865_CASE { return RegionIN865Verify( verify, phyAttribute ); } -#define IN865_APPLY_CF_LIST( ) IN865_CASE { RegionIN865ApplyCFList( applyCFList ); break; } -#define IN865_CHAN_MASK_SET( ) IN865_CASE { return RegionIN865ChanMaskSet( chanMaskSet ); } -#define IN865_ADR_NEXT( ) IN865_CASE { return RegionIN865AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define IN865_COMPUTE_RX_WINDOW_PARAMETERS( ) IN865_CASE { RegionIN865ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define IN865_RX_CONFIG( ) IN865_CASE { return RegionIN865RxConfig( rxConfig, datarate ); } -#define IN865_TX_CONFIG( ) IN865_CASE { return RegionIN865TxConfig( txConfig, txPower, txTimeOnAir ); } -#define IN865_LINK_ADR_REQ( ) IN865_CASE { return RegionIN865LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define IN865_RX_PARAM_SETUP_REQ( ) IN865_CASE { return RegionIN865RxParamSetupReq( rxParamSetupReq ); } -#define IN865_NEW_CHANNEL_REQ( ) IN865_CASE { return RegionIN865NewChannelReq( newChannelReq ); } -#define IN865_TX_PARAM_SETUP_REQ( ) IN865_CASE { return RegionIN865TxParamSetupReq( txParamSetupReq ); } -#define IN865_DL_CHANNEL_REQ( ) IN865_CASE { return RegionIN865DlChannelReq( dlChannelReq ); } -#define IN865_ALTERNATE_DR( ) IN865_CASE { return RegionIN865AlternateDr( alternateDr ); } -#define IN865_CALC_BACKOFF( ) IN865_CASE { RegionIN865CalcBackOff( calcBackOff ); break; } -#define IN865_NEXT_CHANNEL( ) IN865_CASE { return RegionIN865NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define IN865_CHANNEL_ADD( ) IN865_CASE { return RegionIN865ChannelAdd( channelAdd ); } -#define IN865_CHANNEL_REMOVE( ) IN865_CASE { return RegionIN865ChannelsRemove( channelRemove ); } -#define IN865_CHANNEL_MANUAL_ADD( ) IN865_CASE { return RegionIN865ChannelManualAdd( channelAdd ); } -#define IN865_CHANNEL_MANUAL_REMOVE( ) IN865_CASE { return RegionIN865ChannelsRemove( channelRemove ); } -#define IN865_SET_CONTINUOUS_WAVE( ) IN865_CASE { RegionIN865SetContinuousWave( continuousWave ); break; } -#define IN865_APPLY_DR_OFFSET( ) IN865_CASE { return RegionIN865ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define IN865_GET_CHANNELS( ) IN865_CASE { return RegionIN865GetChannels( channels, size ); } -#define IN865_GET_CHANNEL_MASK( ) IN865_CASE { return RegionIN865GetChannelMask( channelmask, size ); } -#define IN865_FORCE_JOIN_DATARATE( ) IN865_CASE { return RegionIN865ForceJoinDataRate( joinDr, alternateDr ); } +#define IN865_IS_ACTIVE( ) else if(region == LORAMAC_REGION_IN865) { return true; } +#define IN865_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865GetPhyParam( getPhy ); } +#define IN865_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_IN865) { RegionIN865SetBandTxDone( txDone );} +#define IN865_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_IN865) { RegionIN865InitDefaults( type );} +#define IN865_VERIFY( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865Verify( verify, phyAttribute ); } +#define IN865_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_IN865) { RegionIN865ApplyCFList( applyCFList );} +#define IN865_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ChanMaskSet( chanMaskSet ); } +#define IN865_ADR_NEXT( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define IN865_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_IN865) { RegionIN865ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define IN865_RX_CONFIG( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865RxConfig( rxConfig, datarate ); } +#define IN865_TX_CONFIG( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865TxConfig( txConfig, txPower, txTimeOnAir ); } +#define IN865_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define IN865_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865RxParamSetupReq( rxParamSetupReq ); } +#define IN865_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865NewChannelReq( newChannelReq ); } +#define IN865_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865TxParamSetupReq( txParamSetupReq ); } +#define IN865_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865DlChannelReq( dlChannelReq ); } +#define IN865_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865AlternateDr( alternateDr ); } +#define IN865_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_IN865) { RegionIN865CalcBackOff( calcBackOff );} +#define IN865_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define IN865_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ChannelAdd( channelAdd ); } +#define IN865_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ChannelsRemove( channelRemove ); } +#define IN865_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ChannelManualAdd( channelAdd ); } +#define IN865_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ChannelsRemove( channelRemove ); } +#define IN865_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_IN865) { RegionIN865SetContinuousWave( continuousWave );} +#define IN865_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define IN865_GET_CHANNELS( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865GetChannels( channels, size ); } +#define IN865_GET_CHANNEL_MASK( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865GetChannelMask( channelmask, size ); } +#define IN865_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_IN865) { return RegionIN865ForceJoinDataRate( joinDr, alternateDr ); } #else #define IN865_IS_ACTIVE( ) #define IN865_GET_PHY_PARAM( ) @@ -497,36 +495,35 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_US915 #include "RegionUS915.h" -#define US915_CASE case LORAMAC_REGION_US915: -#define US915_IS_ACTIVE( ) US915_CASE { return true; } -#define US915_GET_PHY_PARAM( ) US915_CASE { return RegionUS915GetPhyParam( getPhy ); } -#define US915_SET_BAND_TX_DONE( ) US915_CASE { RegionUS915SetBandTxDone( txDone ); break; } -#define US915_INIT_DEFAULTS( ) US915_CASE { RegionUS915InitDefaults( type ); break; } -#define US915_VERIFY( ) US915_CASE { return RegionUS915Verify( verify, phyAttribute ); } -#define US915_APPLY_CF_LIST( ) US915_CASE { RegionUS915ApplyCFList( applyCFList ); break; } -#define US915_CHAN_MASK_SET( ) US915_CASE { return RegionUS915ChanMaskSet( chanMaskSet ); } -#define US915_ADR_NEXT( ) US915_CASE { return RegionUS915AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define US915_COMPUTE_RX_WINDOW_PARAMETERS( ) US915_CASE { RegionUS915ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define US915_RX_CONFIG( ) US915_CASE { return RegionUS915RxConfig( rxConfig, datarate ); } -#define US915_TX_CONFIG( ) US915_CASE { return RegionUS915TxConfig( txConfig, txPower, txTimeOnAir ); } -#define US915_LINK_ADR_REQ( ) US915_CASE { return RegionUS915LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define US915_RX_PARAM_SETUP_REQ( ) US915_CASE { return RegionUS915RxParamSetupReq( rxParamSetupReq ); } -#define US915_NEW_CHANNEL_REQ( ) US915_CASE { return RegionUS915NewChannelReq( newChannelReq ); } -#define US915_TX_PARAM_SETUP_REQ( ) US915_CASE { return RegionUS915TxParamSetupReq( txParamSetupReq ); } -#define US915_DL_CHANNEL_REQ( ) US915_CASE { return RegionUS915DlChannelReq( dlChannelReq ); } -#define US915_ALTERNATE_DR( ) US915_CASE { return RegionUS915AlternateDr( alternateDr ); } -#define US915_CALC_BACKOFF( ) US915_CASE { RegionUS915CalcBackOff( calcBackOff ); break; } -#define US915_NEXT_CHANNEL( ) US915_CASE { return RegionUS915NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define US915_CHANNEL_ADD( ) US915_CASE { return RegionUS915ChannelAdd( channelAdd ); } -#define US915_CHANNEL_REMOVE( ) US915_CASE { return RegionUS915ChannelsRemove( channelRemove ); } -#define US915_CHANNEL_MANUAL_ADD( ) US915_CASE { return RegionUS915ChannelManualAdd( channelAdd ); } -#define US915_CHANNEL_MANUAL_REMOVE( ) US915_CASE { return RegionUS915ChannelsManualRemove( channelRemove ); } -#define US915_SET_CONTINUOUS_WAVE( ) US915_CASE { RegionUS915SetContinuousWave( continuousWave ); break; } -#define US915_APPLY_DR_OFFSET( ) US915_CASE { return RegionUS915ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define US915_GET_CHANNELS( ) US915_CASE { return RegionUS915GetChannels( channels, size ); } -#define US915_GET_CHANNEL_MASK( ) US915_CASE { return RegionUS915GetChannelMask( channelmask, size ); } -#define US915_GET_CHANNEL_MASK_REMAINING( ) US915_CASE { return RegionUS915GetChannelMaskRemaining( channelmask, size ); } -#define US915_FORCE_JOIN_DATARATE( ) US915_CASE { return RegionUS915ForceJoinDataRate( joinDr, alternateDr ); } +#define US915_IS_ACTIVE( ) else if(region == LORAMAC_REGION_US915) { return true; } +#define US915_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915GetPhyParam( getPhy ); } +#define US915_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_US915) { RegionUS915SetBandTxDone( txDone );} +#define US915_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_US915) { RegionUS915InitDefaults( type );} +#define US915_VERIFY( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915Verify( verify, phyAttribute ); } +#define US915_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_US915) { RegionUS915ApplyCFList( applyCFList );} +#define US915_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ChanMaskSet( chanMaskSet ); } +#define US915_ADR_NEXT( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915AdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define US915_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_US915) { RegionUS915ComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define US915_RX_CONFIG( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915RxConfig( rxConfig, datarate ); } +#define US915_TX_CONFIG( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915TxConfig( txConfig, txPower, txTimeOnAir ); } +#define US915_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915LinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define US915_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915RxParamSetupReq( rxParamSetupReq ); } +#define US915_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915NewChannelReq( newChannelReq ); } +#define US915_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915TxParamSetupReq( txParamSetupReq ); } +#define US915_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915DlChannelReq( dlChannelReq ); } +#define US915_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915AlternateDr( alternateDr ); } +#define US915_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_US915) { RegionUS915CalcBackOff( calcBackOff );} +#define US915_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915NextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define US915_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ChannelAdd( channelAdd ); } +#define US915_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ChannelsRemove( channelRemove ); } +#define US915_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ChannelManualAdd( channelAdd ); } +#define US915_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ChannelsManualRemove( channelRemove ); } +#define US915_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_US915) { RegionUS915SetContinuousWave( continuousWave );} +#define US915_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define US915_GET_CHANNELS( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915GetChannels( channels, size ); } +#define US915_GET_CHANNEL_MASK( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915GetChannelMask( channelmask, size ); } +#define US915_GET_CHANNEL_MASK_REMAINING( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915GetChannelMaskRemaining( channelmask, size ); } +#define US915_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_US915) { return RegionUS915ForceJoinDataRate( joinDr, alternateDr ); } #else #define US915_IS_ACTIVE( ) #define US915_GET_PHY_PARAM( ) @@ -561,36 +558,35 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #ifdef REGION_US915_HYBRID #include "RegionUS915-Hybrid.h" -#define US915_HYBRID_CASE case LORAMAC_REGION_US915_HYBRID: -#define US915_HYBRID_IS_ACTIVE( ) US915_HYBRID_CASE { return true; } -#define US915_HYBRID_GET_PHY_PARAM( ) US915_HYBRID_CASE { return RegionUS915HybridGetPhyParam( getPhy ); } -#define US915_HYBRID_SET_BAND_TX_DONE( ) US915_HYBRID_CASE { RegionUS915HybridSetBandTxDone( txDone ); break; } -#define US915_HYBRID_INIT_DEFAULTS( ) US915_HYBRID_CASE { RegionUS915HybridInitDefaults( type ); break; } -#define US915_HYBRID_VERIFY( ) US915_HYBRID_CASE { return RegionUS915HybridVerify( verify, phyAttribute ); } -#define US915_HYBRID_APPLY_CF_LIST( ) US915_HYBRID_CASE { RegionUS915HybridApplyCFList( applyCFList ); break; } -#define US915_HYBRID_CHAN_MASK_SET( ) US915_HYBRID_CASE { return RegionUS915HybridChanMaskSet( chanMaskSet ); } -#define US915_HYBRID_ADR_NEXT( ) US915_HYBRID_CASE { return RegionUS915HybridAdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } -#define US915_HYBRID_COMPUTE_RX_WINDOW_PARAMETERS( ) US915_HYBRID_CASE { RegionUS915HybridComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams ); break; } -#define US915_HYBRID_RX_CONFIG( ) US915_HYBRID_CASE { return RegionUS915HybridRxConfig( rxConfig, datarate ); } -#define US915_HYBRID_TX_CONFIG( ) US915_HYBRID_CASE { return RegionUS915HybridTxConfig( txConfig, txPower, txTimeOnAir ); } -#define US915_HYBRID_LINK_ADR_REQ( ) US915_HYBRID_CASE { return RegionUS915HybridLinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } -#define US915_HYBRID_RX_PARAM_SETUP_REQ( ) US915_HYBRID_CASE { return RegionUS915HybridRxParamSetupReq( rxParamSetupReq ); } -#define US915_HYBRID_NEW_CHANNEL_REQ( ) US915_HYBRID_CASE { return RegionUS915HybridNewChannelReq( newChannelReq ); } -#define US915_HYBRID_TX_PARAM_SETUP_REQ( ) US915_HYBRID_CASE { return RegionUS915HybridTxParamSetupReq( txParamSetupReq ); } -#define US915_HYBRID_DL_CHANNEL_REQ( ) US915_HYBRID_CASE { return RegionUS915HybridDlChannelReq( dlChannelReq ); } -#define US915_HYBRID_ALTERNATE_DR( ) US915_HYBRID_CASE { return RegionUS915HybridAlternateDr( alternateDr ); } -#define US915_HYBRID_CALC_BACKOFF( ) US915_HYBRID_CASE { RegionUS915HybridCalcBackOff( calcBackOff ); break; } -#define US915_HYBRID_NEXT_CHANNEL( ) US915_HYBRID_CASE { return RegionUS915HybridNextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } -#define US915_HYBRID_CHANNEL_ADD( ) US915_HYBRID_CASE { return RegionUS915HybridChannelAdd( channelAdd ); } -#define US915_HYBRID_CHANNEL_REMOVE( ) US915_HYBRID_CASE { return RegionUS915HybridChannelsRemove( channelRemove ); } -#define US915_HYBRID_CHANNEL_MANUAL_ADD( ) US915_HYBRID_CASE { return RegionUS915HybridChannelManualAdd( channelAdd ); } -#define US915_HYBRID_CHANNEL_MANUAL_REMOVE( ) US915_HYBRID_CASE { return RegionUS915HybridChannelsManualRemove( channelRemove ); } -#define US915_HYBRID_SET_CONTINUOUS_WAVE( ) US915_HYBRID_CASE { RegionUS915HybridSetContinuousWave( continuousWave ); break; } -#define US915_HYBRID_APPLY_DR_OFFSET( ) US915_HYBRID_CASE { return RegionUS915HybridApplyDrOffset( downlinkDwellTime, dr, drOffset ); } -#define US915_HYBRID_GET_CHANNELS( ) US915_HYBRID_CASE { return RegionUS915HybridGetChannels( channels, size ); } -#define US915_HYBRID_GET_CHANNEL_MASK( ) US915_HYBRID_CASE { return RegionUS915HybridGetChannelMask( channelmask, size ); } -#define US915_HYBRID_GET_CHANNEL_MASK_REMAINING( ) US915_HYBRID_CASE { return RegionUS915HybridGetChannelMaskRemaining( channelmask, size ); } -#define US915_HYBRID_FORCE_JOIN_DATARATE( ) US915_HYBRID_CASE { return RegionUS915HybridForceJoinDataRate( joinDr, alternateDr ); } +#define US915_HYBRID_IS_ACTIVE( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return true; } +#define US915_HYBRID_GET_PHY_PARAM( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridGetPhyParam( getPhy ); } +#define US915_HYBRID_SET_BAND_TX_DONE( ) else if(region == LORAMAC_REGION_US915_HYBRID) { RegionUS915HybridSetBandTxDone( txDone );} +#define US915_HYBRID_INIT_DEFAULTS( ) else if(region == LORAMAC_REGION_US915_HYBRID) { RegionUS915HybridInitDefaults( type );} +#define US915_HYBRID_VERIFY( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridVerify( verify, phyAttribute ); } +#define US915_HYBRID_APPLY_CF_LIST( ) else if(region == LORAMAC_REGION_US915_HYBRID) { RegionUS915HybridApplyCFList( applyCFList );} +#define US915_HYBRID_CHAN_MASK_SET( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridChanMaskSet( chanMaskSet ); } +#define US915_HYBRID_ADR_NEXT( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridAdrNext( adrNext, drOut, txPowOut, adrAckCounter ); } +#define US915_HYBRID_COMPUTE_RX_WINDOW_PARAMETERS( ) else if(region == LORAMAC_REGION_US915_HYBRID) { RegionUS915HybridComputeRxWindowParameters( datarate, minRxSymbols, rxError, rxConfigParams );} +#define US915_HYBRID_RX_CONFIG( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridRxConfig( rxConfig, datarate ); } +#define US915_HYBRID_TX_CONFIG( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridTxConfig( txConfig, txPower, txTimeOnAir ); } +#define US915_HYBRID_LINK_ADR_REQ( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridLinkAdrReq( linkAdrReq, drOut, txPowOut, nbRepOut, nbBytesParsed ); } +#define US915_HYBRID_RX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridRxParamSetupReq( rxParamSetupReq ); } +#define US915_HYBRID_NEW_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridNewChannelReq( newChannelReq ); } +#define US915_HYBRID_TX_PARAM_SETUP_REQ( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridTxParamSetupReq( txParamSetupReq ); } +#define US915_HYBRID_DL_CHANNEL_REQ( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridDlChannelReq( dlChannelReq ); } +#define US915_HYBRID_ALTERNATE_DR( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridAlternateDr( alternateDr ); } +#define US915_HYBRID_CALC_BACKOFF( ) else if(region == LORAMAC_REGION_US915_HYBRID) { RegionUS915HybridCalcBackOff( calcBackOff );} +#define US915_HYBRID_NEXT_CHANNEL( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridNextChannel( nextChanParams, channel, time, aggregatedTimeOff ); } +#define US915_HYBRID_CHANNEL_ADD( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridChannelAdd( channelAdd ); } +#define US915_HYBRID_CHANNEL_REMOVE( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridChannelsRemove( channelRemove ); } +#define US915_HYBRID_CHANNEL_MANUAL_ADD( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridChannelManualAdd( channelAdd ); } +#define US915_HYBRID_CHANNEL_MANUAL_REMOVE( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridChannelsManualRemove( channelRemove ); } +#define US915_HYBRID_SET_CONTINUOUS_WAVE( ) else if(region == LORAMAC_REGION_US915_HYBRID) { RegionUS915HybridSetContinuousWave( continuousWave );} +#define US915_HYBRID_APPLY_DR_OFFSET( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridApplyDrOffset( downlinkDwellTime, dr, drOffset ); } +#define US915_HYBRID_GET_CHANNELS( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridGetChannels( channels, size ); } +#define US915_HYBRID_GET_CHANNEL_MASK( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridGetChannelMask( channelmask, size ); } +#define US915_HYBRID_GET_CHANNEL_MASK_REMAINING( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridGetChannelMaskRemaining( channelmask, size ); } +#define US915_HYBRID_FORCE_JOIN_DATARATE( ) else if(region == LORAMAC_REGION_US915_HYBRID) { return RegionUS915HybridForceJoinDataRate( joinDr, alternateDr ); } #else #define US915_HYBRID_IS_ACTIVE( ) #define US915_HYBRID_GET_PHY_PARAM( ) @@ -625,584 +621,570 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae bool RegionIsActive( LoRaMacRegion_t region ) { - switch( region ) - { - AS923_IS_ACTIVE( ); - AU915_IS_ACTIVE( ); - CN470_IS_ACTIVE( ); - CN779_IS_ACTIVE( ); - EU433_IS_ACTIVE( ); - EU868_IS_ACTIVE( ); - KR920_IS_ACTIVE( ); - IN865_IS_ACTIVE( ); - US915_IS_ACTIVE( ); - US915_HYBRID_IS_ACTIVE( ); - default: - { - return false; - } + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_IS_ACTIVE( ) + AU915_IS_ACTIVE( ) + CN470_IS_ACTIVE( ) + CN779_IS_ACTIVE( ) + EU433_IS_ACTIVE( ) + EU868_IS_ACTIVE( ) + KR920_IS_ACTIVE( ) + IN865_IS_ACTIVE( ) + US915_IS_ACTIVE( ) + US915_HYBRID_IS_ACTIVE( ) + else { + return false; } } IRAM_ATTR PhyParam_t RegionGetPhyParam( LoRaMacRegion_t region, GetPhyParams_t* getPhy ) { PhyParam_t phyParam = { 0 }; - switch( region ) - { - AS923_GET_PHY_PARAM( ); - AU915_GET_PHY_PARAM( ); - CN470_GET_PHY_PARAM( ); - CN779_GET_PHY_PARAM( ); - EU433_GET_PHY_PARAM( ); - EU868_GET_PHY_PARAM( ); - KR920_GET_PHY_PARAM( ); - IN865_GET_PHY_PARAM( ); - US915_GET_PHY_PARAM( ); - US915_HYBRID_GET_PHY_PARAM( ); - default: - { - return phyParam; - } + + if(region >= LORAMAC_REGION_MAX) { + return phyParam; + } + AS923_GET_PHY_PARAM( ) + AU915_GET_PHY_PARAM( ) + CN470_GET_PHY_PARAM( ) + CN779_GET_PHY_PARAM( ) + EU433_GET_PHY_PARAM( ) + EU868_GET_PHY_PARAM( ) + KR920_GET_PHY_PARAM( ) + IN865_GET_PHY_PARAM( ) + US915_GET_PHY_PARAM( ) + US915_HYBRID_GET_PHY_PARAM( ) + else { + return phyParam; } } IRAM_ATTR void RegionSetBandTxDone( LoRaMacRegion_t region, SetBandTxDoneParams_t* txDone ) { - switch( region ) - { - AS923_SET_BAND_TX_DONE( ); - AU915_SET_BAND_TX_DONE( ); - CN470_SET_BAND_TX_DONE( ); - CN779_SET_BAND_TX_DONE( ); - EU433_SET_BAND_TX_DONE( ); - EU868_SET_BAND_TX_DONE( ); - KR920_SET_BAND_TX_DONE( ); - IN865_SET_BAND_TX_DONE( ); - US915_SET_BAND_TX_DONE( ); - US915_HYBRID_SET_BAND_TX_DONE( ); - default: - { - return; - } + if(region >= LORAMAC_REGION_MAX) { + return; } + AS923_SET_BAND_TX_DONE( ) + AU915_SET_BAND_TX_DONE( ) + CN470_SET_BAND_TX_DONE( ) + CN779_SET_BAND_TX_DONE( ) + EU433_SET_BAND_TX_DONE( ) + EU868_SET_BAND_TX_DONE( ) + KR920_SET_BAND_TX_DONE( ) + IN865_SET_BAND_TX_DONE( ) + US915_SET_BAND_TX_DONE( ) + US915_HYBRID_SET_BAND_TX_DONE( ) } void RegionInitDefaults( LoRaMacRegion_t region, InitType_t type ) { - switch( region ) - { - AS923_INIT_DEFAULTS( ); - AU915_INIT_DEFAULTS( ); - CN470_INIT_DEFAULTS( ); - CN779_INIT_DEFAULTS( ); - EU433_INIT_DEFAULTS( ); - EU868_INIT_DEFAULTS( ); - KR920_INIT_DEFAULTS( ); - IN865_INIT_DEFAULTS( ); - US915_INIT_DEFAULTS( ); - US915_HYBRID_INIT_DEFAULTS( ); - default: - { - break; - } + + if(region >= LORAMAC_REGION_MAX) { + return; } + AS923_INIT_DEFAULTS( ) + AU915_INIT_DEFAULTS( ) + CN470_INIT_DEFAULTS( ) + CN779_INIT_DEFAULTS( ) + EU433_INIT_DEFAULTS( ) + EU868_INIT_DEFAULTS( ) + KR920_INIT_DEFAULTS( ) + IN865_INIT_DEFAULTS( ) + US915_INIT_DEFAULTS( ) + US915_HYBRID_INIT_DEFAULTS( ) } bool RegionVerify( LoRaMacRegion_t region, VerifyParams_t* verify, PhyAttribute_t phyAttribute ) { - switch( region ) - { - AS923_VERIFY( ); - AU915_VERIFY( ); - CN470_VERIFY( ); - CN779_VERIFY( ); - EU433_VERIFY( ); - EU868_VERIFY( ); - KR920_VERIFY( ); - IN865_VERIFY( ); - US915_VERIFY( ); - US915_HYBRID_VERIFY( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_VERIFY( ) + AU915_VERIFY( ) + CN470_VERIFY( ) + CN779_VERIFY( ) + EU433_VERIFY( ) + EU868_VERIFY( ) + KR920_VERIFY( ) + IN865_VERIFY( ) + US915_VERIFY( ) + US915_HYBRID_VERIFY( ) + else { + return false; } } void RegionApplyCFList( LoRaMacRegion_t region, ApplyCFListParams_t* applyCFList ) { - switch( region ) - { - AS923_APPLY_CF_LIST( ); - AU915_APPLY_CF_LIST( ); - CN470_APPLY_CF_LIST( ); - CN779_APPLY_CF_LIST( ); - EU433_APPLY_CF_LIST( ); - EU868_APPLY_CF_LIST( ); - KR920_APPLY_CF_LIST( ); - IN865_APPLY_CF_LIST( ); - US915_APPLY_CF_LIST( ); - US915_HYBRID_APPLY_CF_LIST( ); - default: - { - break; - } + + if(region >= LORAMAC_REGION_MAX) { + return; } + AS923_APPLY_CF_LIST( ) + AU915_APPLY_CF_LIST( ) + CN470_APPLY_CF_LIST( ) + CN779_APPLY_CF_LIST( ) + EU433_APPLY_CF_LIST( ) + EU868_APPLY_CF_LIST( ) + KR920_APPLY_CF_LIST( ) + IN865_APPLY_CF_LIST( ) + US915_APPLY_CF_LIST( ) + US915_HYBRID_APPLY_CF_LIST( ) } bool RegionChanMaskSet( LoRaMacRegion_t region, ChanMaskSetParams_t* chanMaskSet ) { - switch( region ) - { - AS923_CHAN_MASK_SET( ); - AU915_CHAN_MASK_SET( ); - CN470_CHAN_MASK_SET( ); - CN779_CHAN_MASK_SET( ); - EU433_CHAN_MASK_SET( ); - EU868_CHAN_MASK_SET( ); - KR920_CHAN_MASK_SET( ); - IN865_CHAN_MASK_SET( ); - US915_CHAN_MASK_SET( ); - US915_HYBRID_CHAN_MASK_SET( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_CHAN_MASK_SET( ) + AU915_CHAN_MASK_SET( ) + CN470_CHAN_MASK_SET( ) + CN779_CHAN_MASK_SET( ) + EU433_CHAN_MASK_SET( ) + EU868_CHAN_MASK_SET( ) + KR920_CHAN_MASK_SET( ) + IN865_CHAN_MASK_SET( ) + US915_CHAN_MASK_SET( ) + US915_HYBRID_CHAN_MASK_SET( ) + else { + return false; } } bool RegionAdrNext( LoRaMacRegion_t region, AdrNextParams_t* adrNext, int8_t* drOut, int8_t* txPowOut, uint32_t* adrAckCounter ) { - switch( region ) - { - AS923_ADR_NEXT( ); - AU915_ADR_NEXT( ); - CN470_ADR_NEXT( ); - CN779_ADR_NEXT( ); - EU433_ADR_NEXT( ); - EU868_ADR_NEXT( ); - KR920_ADR_NEXT( ); - IN865_ADR_NEXT( ); - US915_ADR_NEXT( ); - US915_HYBRID_ADR_NEXT( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_ADR_NEXT( ) + AU915_ADR_NEXT( ) + CN470_ADR_NEXT( ) + CN779_ADR_NEXT( ) + EU433_ADR_NEXT( ) + EU868_ADR_NEXT( ) + KR920_ADR_NEXT( ) + IN865_ADR_NEXT( ) + US915_ADR_NEXT( ) + US915_HYBRID_ADR_NEXT( ) + else { + return false; } } void RegionComputeRxWindowParameters( LoRaMacRegion_t region, int8_t datarate, uint8_t minRxSymbols, uint32_t rxError, RxConfigParams_t *rxConfigParams ) { - switch( region ) - { - AS923_COMPUTE_RX_WINDOW_PARAMETERS( ); - AU915_COMPUTE_RX_WINDOW_PARAMETERS( ); - CN470_COMPUTE_RX_WINDOW_PARAMETERS( ); - CN779_COMPUTE_RX_WINDOW_PARAMETERS( ); - EU433_COMPUTE_RX_WINDOW_PARAMETERS( ); - EU868_COMPUTE_RX_WINDOW_PARAMETERS( ); - KR920_COMPUTE_RX_WINDOW_PARAMETERS( ); - IN865_COMPUTE_RX_WINDOW_PARAMETERS( ); - US915_COMPUTE_RX_WINDOW_PARAMETERS( ); - US915_HYBRID_COMPUTE_RX_WINDOW_PARAMETERS( ); - default: - { - break; - } + + if(region >= LORAMAC_REGION_MAX) { + return; } + AS923_COMPUTE_RX_WINDOW_PARAMETERS( ) + AU915_COMPUTE_RX_WINDOW_PARAMETERS( ) + CN470_COMPUTE_RX_WINDOW_PARAMETERS( ) + CN779_COMPUTE_RX_WINDOW_PARAMETERS( ) + EU433_COMPUTE_RX_WINDOW_PARAMETERS( ) + EU868_COMPUTE_RX_WINDOW_PARAMETERS( ) + KR920_COMPUTE_RX_WINDOW_PARAMETERS( ) + IN865_COMPUTE_RX_WINDOW_PARAMETERS( ) + US915_COMPUTE_RX_WINDOW_PARAMETERS( ) + US915_HYBRID_COMPUTE_RX_WINDOW_PARAMETERS( ) } bool RegionRxConfig( LoRaMacRegion_t region, RxConfigParams_t* rxConfig, int8_t* datarate ) { - switch( region ) - { - AS923_RX_CONFIG( ); - AU915_RX_CONFIG( ); - CN470_RX_CONFIG( ); - CN779_RX_CONFIG( ); - EU433_RX_CONFIG( ); - EU868_RX_CONFIG( ); - KR920_RX_CONFIG( ); - IN865_RX_CONFIG( ); - US915_RX_CONFIG( ); - US915_HYBRID_RX_CONFIG( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_RX_CONFIG( ) + AU915_RX_CONFIG( ) + CN470_RX_CONFIG( ) + CN779_RX_CONFIG( ) + EU433_RX_CONFIG( ) + EU868_RX_CONFIG( ) + KR920_RX_CONFIG( ) + IN865_RX_CONFIG( ) + US915_RX_CONFIG( ) + US915_HYBRID_RX_CONFIG( ) + else { + return false; } } bool RegionTxConfig( LoRaMacRegion_t region, TxConfigParams_t* txConfig, int8_t* txPower, TimerTime_t* txTimeOnAir ) { - switch( region ) - { - AS923_TX_CONFIG( ); - AU915_TX_CONFIG( ); - CN470_TX_CONFIG( ); - CN779_TX_CONFIG( ); - EU433_TX_CONFIG( ); - EU868_TX_CONFIG( ); - KR920_TX_CONFIG( ); - IN865_TX_CONFIG( ); - US915_TX_CONFIG( ); - US915_HYBRID_TX_CONFIG( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_TX_CONFIG( ) + AU915_TX_CONFIG( ) + CN470_TX_CONFIG( ) + CN779_TX_CONFIG( ) + EU433_TX_CONFIG( ) + EU868_TX_CONFIG( ) + KR920_TX_CONFIG( ) + IN865_TX_CONFIG( ) + US915_TX_CONFIG( ) + US915_HYBRID_TX_CONFIG( ) + else { + return false; } } uint8_t RegionLinkAdrReq( LoRaMacRegion_t region, LinkAdrReqParams_t* linkAdrReq, int8_t* drOut, int8_t* txPowOut, uint8_t* nbRepOut, uint8_t* nbBytesParsed ) { - switch( region ) - { - AS923_LINK_ADR_REQ( ); - AU915_LINK_ADR_REQ( ); - CN470_LINK_ADR_REQ( ); - CN779_LINK_ADR_REQ( ); - EU433_LINK_ADR_REQ( ); - EU868_LINK_ADR_REQ( ); - KR920_LINK_ADR_REQ( ); - IN865_LINK_ADR_REQ( ); - US915_LINK_ADR_REQ( ); - US915_HYBRID_LINK_ADR_REQ( ); - default: - { - return 0; - } + + if(region >= LORAMAC_REGION_MAX) { + return 0; + } + AS923_LINK_ADR_REQ( ) + AU915_LINK_ADR_REQ( ) + CN470_LINK_ADR_REQ( ) + CN779_LINK_ADR_REQ( ) + EU433_LINK_ADR_REQ( ) + EU868_LINK_ADR_REQ( ) + KR920_LINK_ADR_REQ( ) + IN865_LINK_ADR_REQ( ) + US915_LINK_ADR_REQ( ) + US915_HYBRID_LINK_ADR_REQ( ) + else { + return 0; } } uint8_t RegionRxParamSetupReq( LoRaMacRegion_t region, RxParamSetupReqParams_t* rxParamSetupReq ) { - switch( region ) - { - AS923_RX_PARAM_SETUP_REQ( ); - AU915_RX_PARAM_SETUP_REQ( ); - CN470_RX_PARAM_SETUP_REQ( ); - CN779_RX_PARAM_SETUP_REQ( ); - EU433_RX_PARAM_SETUP_REQ( ); - EU868_RX_PARAM_SETUP_REQ( ); - KR920_RX_PARAM_SETUP_REQ( ); - IN865_RX_PARAM_SETUP_REQ( ); - US915_RX_PARAM_SETUP_REQ( ); - US915_HYBRID_RX_PARAM_SETUP_REQ( ); - default: - { - return 0; - } + + if(region >= LORAMAC_REGION_MAX) { + return 0; + } + AS923_RX_PARAM_SETUP_REQ( ) + AU915_RX_PARAM_SETUP_REQ( ) + CN470_RX_PARAM_SETUP_REQ( ) + CN779_RX_PARAM_SETUP_REQ( ) + EU433_RX_PARAM_SETUP_REQ( ) + EU868_RX_PARAM_SETUP_REQ( ) + KR920_RX_PARAM_SETUP_REQ( ) + IN865_RX_PARAM_SETUP_REQ( ) + US915_RX_PARAM_SETUP_REQ( ) + US915_HYBRID_RX_PARAM_SETUP_REQ( ) + else { + return 0; } } uint8_t RegionNewChannelReq( LoRaMacRegion_t region, NewChannelReqParams_t* newChannelReq ) { - switch( region ) - { - AS923_NEW_CHANNEL_REQ( ); - AU915_NEW_CHANNEL_REQ( ); - CN470_NEW_CHANNEL_REQ( ); - CN779_NEW_CHANNEL_REQ( ); - EU433_NEW_CHANNEL_REQ( ); - EU868_NEW_CHANNEL_REQ( ); - KR920_NEW_CHANNEL_REQ( ); - IN865_NEW_CHANNEL_REQ( ); - US915_NEW_CHANNEL_REQ( ); - US915_HYBRID_NEW_CHANNEL_REQ( ); - default: - { - return 0; - } + + if(region >= LORAMAC_REGION_MAX) { + return 0; + } + AS923_NEW_CHANNEL_REQ( ) + AU915_NEW_CHANNEL_REQ( ) + CN470_NEW_CHANNEL_REQ( ) + CN779_NEW_CHANNEL_REQ( ) + EU433_NEW_CHANNEL_REQ( ) + EU868_NEW_CHANNEL_REQ( ) + KR920_NEW_CHANNEL_REQ( ) + IN865_NEW_CHANNEL_REQ( ) + US915_NEW_CHANNEL_REQ( ) + US915_HYBRID_NEW_CHANNEL_REQ( ) + else { + return 0; } } int8_t RegionTxParamSetupReq( LoRaMacRegion_t region, TxParamSetupReqParams_t* txParamSetupReq ) { - switch( region ) - { - AS923_TX_PARAM_SETUP_REQ( ); - AU915_TX_PARAM_SETUP_REQ( ); - CN470_TX_PARAM_SETUP_REQ( ); - CN779_TX_PARAM_SETUP_REQ( ); - EU433_TX_PARAM_SETUP_REQ( ); - EU868_TX_PARAM_SETUP_REQ( ); - KR920_TX_PARAM_SETUP_REQ( ); - IN865_TX_PARAM_SETUP_REQ( ); - US915_TX_PARAM_SETUP_REQ( ); - US915_HYBRID_TX_PARAM_SETUP_REQ( ); - default: - { - return 0; - } + + if(region >= LORAMAC_REGION_MAX) { + return 0; + } + AS923_TX_PARAM_SETUP_REQ( ) + AU915_TX_PARAM_SETUP_REQ( ) + CN470_TX_PARAM_SETUP_REQ( ) + CN779_TX_PARAM_SETUP_REQ( ) + EU433_TX_PARAM_SETUP_REQ( ) + EU868_TX_PARAM_SETUP_REQ( ) + KR920_TX_PARAM_SETUP_REQ( ) + IN865_TX_PARAM_SETUP_REQ( ) + US915_TX_PARAM_SETUP_REQ( ) + US915_HYBRID_TX_PARAM_SETUP_REQ( ) + else { + return 0; } } uint8_t RegionDlChannelReq( LoRaMacRegion_t region, DlChannelReqParams_t* dlChannelReq ) { - switch( region ) - { - AS923_DL_CHANNEL_REQ( ); - AU915_DL_CHANNEL_REQ( ); - CN470_DL_CHANNEL_REQ( ); - CN779_DL_CHANNEL_REQ( ); - EU433_DL_CHANNEL_REQ( ); - EU868_DL_CHANNEL_REQ( ); - KR920_DL_CHANNEL_REQ( ); - IN865_DL_CHANNEL_REQ( ); - US915_DL_CHANNEL_REQ( ); - US915_HYBRID_DL_CHANNEL_REQ( ); - default: - { - return 0; - } + + if(region >= LORAMAC_REGION_MAX) { + return 0; + } + AS923_DL_CHANNEL_REQ( ) + AU915_DL_CHANNEL_REQ( ) + CN470_DL_CHANNEL_REQ( ) + CN779_DL_CHANNEL_REQ( ) + EU433_DL_CHANNEL_REQ( ) + EU868_DL_CHANNEL_REQ( ) + KR920_DL_CHANNEL_REQ( ) + IN865_DL_CHANNEL_REQ( ) + US915_DL_CHANNEL_REQ( ) + US915_HYBRID_DL_CHANNEL_REQ( ) + else { + return 0; } } int8_t RegionAlternateDr( LoRaMacRegion_t region, AlternateDrParams_t* alternateDr ) { - switch( region ) - { - AS923_ALTERNATE_DR( ); - AU915_ALTERNATE_DR( ); - CN470_ALTERNATE_DR( ); - CN779_ALTERNATE_DR( ); - EU433_ALTERNATE_DR( ); - EU868_ALTERNATE_DR( ); - KR920_ALTERNATE_DR( ); - IN865_ALTERNATE_DR( ); - US915_ALTERNATE_DR( ); - US915_HYBRID_ALTERNATE_DR( ); - default: - { - return 0; - } + + if(region >= LORAMAC_REGION_MAX) { + return 0; + } + AS923_ALTERNATE_DR( ) + AU915_ALTERNATE_DR( ) + CN470_ALTERNATE_DR( ) + CN779_ALTERNATE_DR( ) + EU433_ALTERNATE_DR( ) + EU868_ALTERNATE_DR( ) + KR920_ALTERNATE_DR( ) + IN865_ALTERNATE_DR( ) + US915_ALTERNATE_DR( ) + US915_HYBRID_ALTERNATE_DR( ) + else { + return 0; } } void RegionCalcBackOff( LoRaMacRegion_t region, CalcBackOffParams_t* calcBackOff ) { - switch( region ) - { - AS923_CALC_BACKOFF( ); - AU915_CALC_BACKOFF( ); - CN470_CALC_BACKOFF( ); - CN779_CALC_BACKOFF( ); - EU433_CALC_BACKOFF( ); - EU868_CALC_BACKOFF( ); - KR920_CALC_BACKOFF( ); - IN865_CALC_BACKOFF( ); - US915_CALC_BACKOFF( ); - US915_HYBRID_CALC_BACKOFF( ); - default: - { - break; - } + + if(region >= LORAMAC_REGION_MAX) { + return; } + AS923_CALC_BACKOFF( ) + AU915_CALC_BACKOFF( ) + CN470_CALC_BACKOFF( ) + CN779_CALC_BACKOFF( ) + EU433_CALC_BACKOFF( ) + EU868_CALC_BACKOFF( ) + KR920_CALC_BACKOFF( ) + IN865_CALC_BACKOFF( ) + US915_CALC_BACKOFF( ) + US915_HYBRID_CALC_BACKOFF( ) } bool RegionNextChannel( LoRaMacRegion_t region, NextChanParams_t* nextChanParams, uint8_t* channel, TimerTime_t* time, TimerTime_t* aggregatedTimeOff ) { - switch( region ) - { - AS923_NEXT_CHANNEL( ); - AU915_NEXT_CHANNEL( ); - CN470_NEXT_CHANNEL( ); - CN779_NEXT_CHANNEL( ); - EU433_NEXT_CHANNEL( ); - EU868_NEXT_CHANNEL( ); - KR920_NEXT_CHANNEL( ); - IN865_NEXT_CHANNEL( ); - US915_NEXT_CHANNEL( ); - US915_HYBRID_NEXT_CHANNEL( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_NEXT_CHANNEL( ) + AU915_NEXT_CHANNEL( ) + CN470_NEXT_CHANNEL( ) + CN779_NEXT_CHANNEL( ) + EU433_NEXT_CHANNEL( ) + EU868_NEXT_CHANNEL( ) + KR920_NEXT_CHANNEL( ) + IN865_NEXT_CHANNEL( ) + US915_NEXT_CHANNEL( ) + US915_HYBRID_NEXT_CHANNEL( ) + else { + return false; } } LoRaMacStatus_t RegionChannelAdd( LoRaMacRegion_t region, ChannelAddParams_t* channelAdd ) { - switch( region ) - { - AS923_CHANNEL_ADD( ); - AU915_CHANNEL_ADD( ); - CN470_CHANNEL_ADD( ); - CN779_CHANNEL_ADD( ); - EU433_CHANNEL_ADD( ); - EU868_CHANNEL_ADD( ); - KR920_CHANNEL_ADD( ); - IN865_CHANNEL_ADD( ); - US915_CHANNEL_ADD( ); - US915_HYBRID_CHANNEL_ADD( ); - default: - { - return LORAMAC_STATUS_PARAMETER_INVALID; - } + + if(region >= LORAMAC_REGION_MAX) { + return LORAMAC_STATUS_PARAMETER_INVALID; + } + AS923_CHANNEL_ADD( ) + AU915_CHANNEL_ADD( ) + CN470_CHANNEL_ADD( ) + CN779_CHANNEL_ADD( ) + EU433_CHANNEL_ADD( ) + EU868_CHANNEL_ADD( ) + KR920_CHANNEL_ADD( ) + IN865_CHANNEL_ADD( ) + US915_CHANNEL_ADD( ) + US915_HYBRID_CHANNEL_ADD( ) + else { + return LORAMAC_STATUS_PARAMETER_INVALID; } } LoRaMacStatus_t RegionChannelManualAdd( LoRaMacRegion_t region, ChannelAddParams_t* channelAdd ) { - switch( region ) - { - AS923_CHANNEL_MANUAL_ADD( ); - AU915_CHANNEL_MANUAL_ADD( ); - EU868_CHANNEL_MANUAL_ADD( ); - US915_CHANNEL_MANUAL_ADD( ); - CN470_CHANNEL_MANUAL_ADD( ); - IN865_CHANNEL_MANUAL_ADD( ); - US915_HYBRID_CHANNEL_MANUAL_ADD( ); - default: - { - return LORAMAC_STATUS_PARAMETER_INVALID; - } + + if(region >= LORAMAC_REGION_MAX) { + return LORAMAC_STATUS_PARAMETER_INVALID; + } + AS923_CHANNEL_MANUAL_ADD( ) + AU915_CHANNEL_MANUAL_ADD( ) + EU868_CHANNEL_MANUAL_ADD( ) + US915_CHANNEL_MANUAL_ADD( ) + CN470_CHANNEL_MANUAL_ADD( ) + IN865_CHANNEL_MANUAL_ADD( ) + US915_HYBRID_CHANNEL_MANUAL_ADD( ) + else { + return LORAMAC_STATUS_PARAMETER_INVALID; } } bool RegionChannelsRemove( LoRaMacRegion_t region, ChannelRemoveParams_t* channelRemove ) { - switch( region ) - { - AS923_CHANNEL_REMOVE( ); - AU915_CHANNEL_REMOVE( ); - CN470_CHANNEL_REMOVE( ); - CN779_CHANNEL_REMOVE( ); - EU433_CHANNEL_REMOVE( ); - EU868_CHANNEL_REMOVE( ); - KR920_CHANNEL_REMOVE( ); - IN865_CHANNEL_REMOVE( ); - US915_CHANNEL_REMOVE( ); - US915_HYBRID_CHANNEL_REMOVE( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_CHANNEL_REMOVE( ) + AU915_CHANNEL_REMOVE( ) + CN470_CHANNEL_REMOVE( ) + CN779_CHANNEL_REMOVE( ) + EU433_CHANNEL_REMOVE( ) + EU868_CHANNEL_REMOVE( ) + KR920_CHANNEL_REMOVE( ) + IN865_CHANNEL_REMOVE( ) + US915_CHANNEL_REMOVE( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return false; } } bool RegionChannelsManualRemove( LoRaMacRegion_t region, ChannelRemoveParams_t* channelRemove ) { - switch( region ) - { - AS923_CHANNEL_MANUAL_REMOVE( ); - AU915_CHANNEL_MANUAL_REMOVE( ); - EU868_CHANNEL_MANUAL_REMOVE( ); - US915_CHANNEL_MANUAL_REMOVE( ); - CN470_CHANNEL_MANUAL_REMOVE( ); - IN865_CHANNEL_MANUAL_REMOVE( ); - US915_HYBRID_CHANNEL_MANUAL_REMOVE( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_CHANNEL_MANUAL_REMOVE( ) + AU915_CHANNEL_MANUAL_REMOVE( ) + EU868_CHANNEL_MANUAL_REMOVE( ) + US915_CHANNEL_MANUAL_REMOVE( ) + CN470_CHANNEL_MANUAL_REMOVE( ) + IN865_CHANNEL_MANUAL_REMOVE( ) + US915_HYBRID_CHANNEL_MANUAL_REMOVE( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return false; } } void RegionSetContinuousWave( LoRaMacRegion_t region, ContinuousWaveParams_t* continuousWave ) { - switch( region ) - { - AS923_SET_CONTINUOUS_WAVE( ); - AU915_SET_CONTINUOUS_WAVE( ); - CN470_SET_CONTINUOUS_WAVE( ); - CN779_SET_CONTINUOUS_WAVE( ); - EU433_SET_CONTINUOUS_WAVE( ); - EU868_SET_CONTINUOUS_WAVE( ); - KR920_SET_CONTINUOUS_WAVE( ); - IN865_SET_CONTINUOUS_WAVE( ); - US915_SET_CONTINUOUS_WAVE( ); - US915_HYBRID_SET_CONTINUOUS_WAVE( ); - default: - { - break; - } + + if(region >= LORAMAC_REGION_MAX) { + return; } + AS923_SET_CONTINUOUS_WAVE( ) + AU915_SET_CONTINUOUS_WAVE( ) + CN470_SET_CONTINUOUS_WAVE( ) + CN779_SET_CONTINUOUS_WAVE( ) + EU433_SET_CONTINUOUS_WAVE( ) + EU868_SET_CONTINUOUS_WAVE( ) + KR920_SET_CONTINUOUS_WAVE( ) + IN865_SET_CONTINUOUS_WAVE( ) + US915_SET_CONTINUOUS_WAVE( ) + US915_HYBRID_SET_CONTINUOUS_WAVE( ) } uint8_t RegionApplyDrOffset( LoRaMacRegion_t region, uint8_t downlinkDwellTime, int8_t dr, int8_t drOffset ) { - switch( region ) - { - AS923_APPLY_DR_OFFSET( ); - AU915_APPLY_DR_OFFSET( ); - CN470_APPLY_DR_OFFSET( ); - CN779_APPLY_DR_OFFSET( ); - EU433_APPLY_DR_OFFSET( ); - EU868_APPLY_DR_OFFSET( ); - KR920_APPLY_DR_OFFSET( ); - IN865_APPLY_DR_OFFSET( ); - US915_APPLY_DR_OFFSET( ); - US915_HYBRID_APPLY_DR_OFFSET( ); - default: - { - return dr; - } + + if(region >= LORAMAC_REGION_MAX) { + return dr; + } + AS923_APPLY_DR_OFFSET( ) + AU915_APPLY_DR_OFFSET( ) + CN470_APPLY_DR_OFFSET( ) + CN779_APPLY_DR_OFFSET( ) + EU433_APPLY_DR_OFFSET( ) + EU868_APPLY_DR_OFFSET( ) + KR920_APPLY_DR_OFFSET( ) + IN865_APPLY_DR_OFFSET( ) + US915_APPLY_DR_OFFSET( ) + US915_HYBRID_APPLY_DR_OFFSET( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return dr; } } bool RegionGetChannels( LoRaMacRegion_t region, ChannelParams_t** channels, uint32_t *size ) { - switch( region ) - { - AS923_GET_CHANNELS( ); - AU915_GET_CHANNELS( ); - EU868_GET_CHANNELS( ); - IN865_GET_CHANNELS( ); - US915_GET_CHANNELS( ); - US915_HYBRID_GET_CHANNELS( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_GET_CHANNELS( ) + AU915_GET_CHANNELS( ) + EU868_GET_CHANNELS( ) + IN865_GET_CHANNELS( ) + US915_GET_CHANNELS( ) + US915_HYBRID_GET_CHANNELS( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return false; } } bool RegionGetChannelMask(LoRaMacRegion_t region, uint16_t **channelmask, uint32_t *size ) { - switch( region ) - { - AS923_GET_CHANNEL_MASK( ); - AU915_GET_CHANNEL_MASK( ); - EU868_GET_CHANNEL_MASK( ); - IN865_GET_CHANNEL_MASK( ); - US915_GET_CHANNEL_MASK( ); - US915_HYBRID_GET_CHANNEL_MASK( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_GET_CHANNEL_MASK( ) + AU915_GET_CHANNEL_MASK( ) + EU868_GET_CHANNEL_MASK( ) + IN865_GET_CHANNEL_MASK( ) + US915_GET_CHANNEL_MASK( ) + US915_HYBRID_GET_CHANNEL_MASK( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return false; } } bool RegionGetChannelMaskRemaining(LoRaMacRegion_t region, uint16_t **channelmask, uint32_t *size ) { - switch( region ) - { - AU915_GET_CHANNEL_MASK_REMAINING( ); - US915_GET_CHANNEL_MASK_REMAINING( ); - US915_HYBRID_GET_CHANNEL_MASK_REMAINING( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AU915_GET_CHANNEL_MASK_REMAINING( ) + US915_GET_CHANNEL_MASK_REMAINING( ) + US915_HYBRID_GET_CHANNEL_MASK_REMAINING( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return false; } } bool RegionForceJoinDataRate( LoRaMacRegion_t region, int8_t joinDr, AlternateDrParams_t* alternateDr ) { - switch( region ) - { - AS923_FORCE_JOIN_DATARATE( ); - AU915_FORCE_JOIN_DATARATE( ); - EU868_FORCE_JOIN_DATARATE( ); - US915_FORCE_JOIN_DATARATE( ); - CN470_FORCE_JOIN_DATARATE( ); - IN865_FORCE_JOIN_DATARATE( ); - US915_HYBRID_FORCE_JOIN_DATARATE( ); - default: - { - return false; - } + + if(region >= LORAMAC_REGION_MAX) { + return false; + } + AS923_FORCE_JOIN_DATARATE( ) + AU915_FORCE_JOIN_DATARATE( ) + EU868_FORCE_JOIN_DATARATE( ) + US915_FORCE_JOIN_DATARATE( ) + CN470_FORCE_JOIN_DATARATE( ) + IN865_FORCE_JOIN_DATARATE( ) + US915_HYBRID_FORCE_JOIN_DATARATE( ) + US915_HYBRID_CHANNEL_REMOVE( ) + else { + return false; } } diff --git a/lib/lora/mac/region/RegionEU433.c b/lib/lora/mac/region/RegionEU433.c index f5838ee16d..71c023afa2 100644 --- a/lib/lora/mac/region/RegionEU433.c +++ b/lib/lora/mac/region/RegionEU433.c @@ -23,7 +23,7 @@ Maintainer: Miguel Luis ( Semtech ), Gregory Cristian ( Semtech ) and Daniel Jae #include #include "board.h" -#include "LoRaMac.h" +#include "lora/mac/LoRaMac.h" #include "esp_attr.h" #include "utilities.h" @@ -1007,6 +1007,76 @@ LoRaMacStatus_t RegionEU433ChannelAdd( ChannelAddParams_t* channelAdd ) return LORAMAC_STATUS_OK; } +LoRaMacStatus_t RegionEU433ChannelManualAdd( ChannelAddParams_t* channelAdd ) +{ + uint8_t band = 0; + bool drInvalid = false; + bool freqInvalid = false; + uint8_t id = channelAdd->ChannelId; + + if( id >= EU433_MAX_NB_CHANNELS ) + { + return LORAMAC_STATUS_PARAMETER_INVALID; + } + + // Validate the datarate range + if( RegionCommonValueInRange( channelAdd->NewChannel->DrRange.Fields.Min, EU433_TX_MIN_DATARATE, EU433_TX_MAX_DATARATE ) == false ) + { + drInvalid = true; + } + if( RegionCommonValueInRange( channelAdd->NewChannel->DrRange.Fields.Max, EU433_TX_MIN_DATARATE, EU433_TX_MAX_DATARATE ) == false ) + { + drInvalid = true; + } + if( channelAdd->NewChannel->DrRange.Fields.Min > channelAdd->NewChannel->DrRange.Fields.Max ) + { + drInvalid = true; + } + + // Default channels don't accept all values + if( id < EU433_NUMB_DEFAULT_CHANNELS ) + { + // Validate the datarate range for min: must be DR_0 + if( channelAdd->NewChannel->DrRange.Fields.Min > DR_0 ) + { + drInvalid = true; + } + // Validate the datarate range for max: must be DR_5 <= Max <= TX_MAX_DATARATE + if( RegionCommonValueInRange( channelAdd->NewChannel->DrRange.Fields.Max, DR_5, EU433_TX_MAX_DATARATE ) == false ) + { + drInvalid = true; + } + } + + // Check frequency + if( freqInvalid == false ) + { + if( VerifyTxFreq( channelAdd->NewChannel->Frequency ) == false ) + { + freqInvalid = true; + } + } + + // Check status + if( ( drInvalid == true ) && ( freqInvalid == true ) ) + { + return LORAMAC_STATUS_FREQ_AND_DR_INVALID; + } + if( drInvalid == true ) + { + return LORAMAC_STATUS_DATARATE_INVALID; + } + if( freqInvalid == true ) + { + return LORAMAC_STATUS_FREQUENCY_INVALID; + } + + memcpy( &(Channels[id]), channelAdd->NewChannel, sizeof( Channels[id] ) ); + Channels[id].Band = band; + ChannelsMask[0] |= ( 1 << id ); + return LORAMAC_STATUS_OK; +} + bool RegionEU433ChannelsRemove( ChannelRemoveParams_t* channelRemove ) { uint8_t id = channelRemove->ChannelId; @@ -1044,3 +1114,12 @@ uint8_t RegionEU433ApplyDrOffset( uint8_t downlinkDwellTime, int8_t dr, int8_t d } return datarate; } + +bool RegionEU433ForceJoinDataRate( int8_t joinDr, AlternateDrParams_t* alternateDr ) +{ + uint8_t DRToCounter[6] = { 48, 32, 24, 16, 8, 1 }; + if (joinDr < sizeof(DRToCounter)) { + alternateDr->NbTrials = DRToCounter[joinDr]; + } + return true; +} diff --git a/lib/lora/mac/region/RegionEU433.h b/lib/lora/mac/region/RegionEU433.h index 0af669d6cb..a66a0da4a1 100644 --- a/lib/lora/mac/region/RegionEU433.h +++ b/lib/lora/mac/region/RegionEU433.h @@ -441,6 +441,15 @@ LoRaMacStatus_t RegionEU433ChannelAdd( ChannelAddParams_t* channelAdd ); */ bool RegionEU433ChannelsRemove( ChannelRemoveParams_t* channelRemove ); +/*! + * \brief Adds a channel manually. + * + * \param [IN] channelAdd Pointer to the function parameters. + * + * \retval Status of the operation. + */ +LoRaMacStatus_t RegionEU433ChannelManualAdd( ChannelAddParams_t* channelAdd ); + /*! * \brief Sets the radio into continuous wave mode. * @@ -461,6 +470,8 @@ void RegionEU433SetContinuousWave( ContinuousWaveParams_t* continuousWave ); */ uint8_t RegionEU433ApplyDrOffset( uint8_t downlinkDwellTime, int8_t dr, int8_t drOffset ); +bool RegionCN470ForceJoinDataRate( int8_t joinDr, AlternateDrParams_t *alternateDr ); + /*! \} defgroup REGIONEU433 */ #endif // __REGION_EU433_H__ diff --git a/lib/lora/system/gpio.h b/lib/lora/system/gpio.h index c89d86aca0..95b13593c3 100644 --- a/lib/lora/system/gpio.h +++ b/lib/lora/system/gpio.h @@ -1,7 +1,7 @@ /* * This file is derived from the MicroPython project, http://micropython.org/ * - * Copyright (c) 2019, Pycom Limited and its licensors. + * Copyright (c) 2020, Pycom Limited and its licensors. * * This software is licensed under the GNU GPL version 3 or any later version, * with permitted additional terms. For more information see the Pycom Licence diff --git a/lib/lora/system/timer.c b/lib/lora/system/timer.c index f4f77554ea..26e6b358de 100644 --- a/lib/lora/system/timer.c +++ b/lib/lora/system/timer.c @@ -228,6 +228,7 @@ IRAM_ATTR void TimerIrqHandler( void ) if( elapsedTimer->Callback != NULL ) { + // Callback will be processed out of the Interrupt context in a Thread modlora_set_timer_callback(elapsedTimer->Callback); } } diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c index 78524035d4..66cb18a8c1 100644 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -43,6 +43,7 @@ #include "lib/utils/pyexec.h" #include "genhdr/mpversion.h" #include "esp32/pycom_version.h" +#include "esp32/pycom_config.h" pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; int pyexec_system_exit = 0; @@ -421,7 +422,9 @@ int pyexec_friendly_repl(void) { friendly_repl_reset: mp_hal_stdout_tx_str("Pycom MicroPython " SW_VERSION_NUMBER " [" MICROPY_GIT_TAG "] on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME "\r\n"); #if (VARIANT == PYBYTES) - mp_hal_stdout_tx_str("Pybytes Version: " PYBYTES_VERSION_NUMBER "\r\n"); + if (config_get_pybytes_autostart()) { + mp_hal_stdout_tx_str("Pybytes Version: " PYBYTES_VERSION_NUMBER "\r\n"); + } #endif #if MICROPY_PY_BUILTINS_HELP mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n"); @@ -489,7 +492,13 @@ int pyexec_friendly_repl(void) { // exit for a soft reset mp_hal_stdout_tx_str("\r\n"); #if (VARIANT == PYBYTES) - continue; + if (config_get_pybytes_autostart()) { + continue; + } + else { + vstr_clear(&line); + return PYEXEC_FORCED_EXIT; + } #else vstr_clear(&line); return PYEXEC_FORCED_EXIT; diff --git a/tests/thread/mutate_bytearray.py b/tests/thread/mutate_bytearray.py index f3276f1b2d..cbaf7691d0 100644 --- a/tests/thread/mutate_bytearray.py +++ b/tests/thread/mutate_bytearray.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time # the shared bytearray ba = bytearray() @@ -34,7 +35,7 @@ def th(n, lo, hi): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) # check bytearray has correct contents print(len(ba)) @@ -42,4 +43,3 @@ def th(n, lo, hi): for b in ba: count[b] += 1 print(count) - diff --git a/tests/thread/mutate_dict.py b/tests/thread/mutate_dict.py index c57d332d51..a1b308a032 100644 --- a/tests/thread/mutate_dict.py +++ b/tests/thread/mutate_dict.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time # the shared dict di = {'a':'A', 'b':'B', 'c':'C', 'd':'D'} @@ -36,7 +37,7 @@ def th(n, lo, hi): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) # check dict has correct contents print(sorted(di.items())) diff --git a/tests/thread/mutate_instance.py b/tests/thread/mutate_instance.py index a1ae428b54..b35d5299fc 100644 --- a/tests/thread/mutate_instance.py +++ b/tests/thread/mutate_instance.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time # the shared user class and instance class User: @@ -35,7 +36,7 @@ def th(n, lo, hi): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) # check user instance has correct contents print(user.a, user.b, user.c) diff --git a/tests/thread/mutate_list.py b/tests/thread/mutate_list.py index 764a9bd99e..f16d052cfc 100644 --- a/tests/thread/mutate_list.py +++ b/tests/thread/mutate_list.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time # the shared list li = list() @@ -37,7 +38,7 @@ def th(n, lo, hi): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) # check list has correct contents li.sort() diff --git a/tests/thread/mutate_set.py b/tests/thread/mutate_set.py index 5492d86313..cdedbb66cd 100644 --- a/tests/thread/mutate_set.py +++ b/tests/thread/mutate_set.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time # the shared set se = set([-1, -2, -3, -4]) @@ -31,7 +32,7 @@ def th(n, lo, hi): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) # check set has correct contents print(sorted(se)) diff --git a/tests/thread/stress_create.py b/tests/thread/stress_create.py index 2399746cca..cb9423ecc7 100644 --- a/tests/thread/stress_create.py +++ b/tests/thread/stress_create.py @@ -15,7 +15,7 @@ def thread_entry(n): _thread.start_new_thread(thread_entry, (thread_num,)) thread_num += 1 except MemoryError: - pass + time.sleep(0.01) # wait for the last threads to terminate time.sleep(1) diff --git a/tests/thread/stress_recurse.py b/tests/thread/stress_recurse.py index 68367c4dd7..9bccd54820 100644 --- a/tests/thread/stress_recurse.py +++ b/tests/thread/stress_recurse.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time def foo(): foo() @@ -21,5 +22,5 @@ def thread_entry(): # busy wait for thread to finish while not finished: - pass + time.sleep(0.01) print('done') diff --git a/tests/thread/thread_exc1.py b/tests/thread/thread_exc1.py index 10fb94b4fb..1c840428a8 100644 --- a/tests/thread/thread_exc1.py +++ b/tests/thread/thread_exc1.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time def foo(): raise ValueError @@ -26,5 +27,5 @@ def thread_entry(): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) print('done') diff --git a/tests/thread/thread_gc1.py b/tests/thread/thread_gc1.py index 8dcbf7e07a..e1aa1c6f16 100644 --- a/tests/thread/thread_gc1.py +++ b/tests/thread/thread_gc1.py @@ -4,6 +4,7 @@ import gc import _thread +import time def thread_entry(n): # allocate a bytearray and fill it @@ -31,4 +32,4 @@ def thread_entry(n): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) diff --git a/tests/thread/thread_ident1.py b/tests/thread/thread_ident1.py index 217fce73b1..66c6c990a3 100644 --- a/tests/thread/thread_ident1.py +++ b/tests/thread/thread_ident1.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time def thread_entry(): tid = _thread.get_ident() @@ -17,5 +18,5 @@ def thread_entry(): _thread.start_new_thread(thread_entry, ()) while not finished: - pass + time.sleep(0.01) print('done') diff --git a/tests/thread/thread_lock3.py b/tests/thread/thread_lock3.py index 607898dad8..0713522a99 100644 --- a/tests/thread/thread_lock3.py +++ b/tests/thread/thread_lock3.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time lock = _thread.allocate_lock() n_thread = 10 @@ -24,4 +25,4 @@ def thread_entry(idx): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) diff --git a/tests/thread/thread_shared1.py b/tests/thread/thread_shared1.py index 13c6651cc4..e81231729f 100644 --- a/tests/thread/thread_shared1.py +++ b/tests/thread/thread_shared1.py @@ -3,6 +3,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time def foo(i): pass @@ -27,5 +28,5 @@ def thread_entry(n, tup): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) print(tup) diff --git a/tests/thread/thread_shared2.py b/tests/thread/thread_shared2.py index e4bfe78022..1d8d97d59f 100644 --- a/tests/thread/thread_shared2.py +++ b/tests/thread/thread_shared2.py @@ -4,6 +4,7 @@ # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread +import time def foo(lst, i): lst[i] += 1 @@ -28,5 +29,5 @@ def thread_entry(n, lst, idx): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) print(lst) diff --git a/tests/thread/thread_stacksize1.py b/tests/thread/thread_stacksize1.py index 62b6e5e40d..bbf1596b4f 100644 --- a/tests/thread/thread_stacksize1.py +++ b/tests/thread/thread_stacksize1.py @@ -4,6 +4,7 @@ import sys import _thread +import time # different implementations have different minimum sizes if sys.implementation.name == 'micropython': @@ -43,5 +44,5 @@ def thread_entry(): # busy wait for threads to finish while n_finished < n_thread: - pass + time.sleep(0.01) print('done')